blob: c5bcb39992f62fe1d245456872ad8491f893c98d [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron6ba51762016-09-19 15:58:38 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
72static const uint64_t kIOSShadowOffset64 = 0x120200000;
73static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
74static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000075static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000076static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000077static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000078static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000079static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000080static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000081static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000082static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
83static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000084static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron6ba51762016-09-19 15:58:38 +000085// The shadow memory space is dynamically allocated.
86static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000088static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000089static const size_t kMaxStackMallocSize = 1 << 16; // 64K
90static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
91static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
92
Craig Topperd3a34f82013-07-16 01:17:10 +000093static const char *const kAsanModuleCtorName = "asan.module_ctor";
94static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000095static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000098static const char *const kAsanUnregisterGlobalsName =
99 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000100static const char *const kAsanRegisterImageGlobalsName =
101 "__asan_register_image_globals";
102static const char *const kAsanUnregisterImageGlobalsName =
103 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000104static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
105static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000106static const char *const kAsanInitName = "__asan_init";
107static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000108 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000109static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
110static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000111static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000112static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000113static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
114static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000115static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000116static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000117static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000118static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000119static const char *const kAsanPoisonStackMemoryName =
120 "__asan_poison_stack_memory";
121static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000122 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000123static const char *const kAsanGlobalsRegisteredFlagName =
124 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000126static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000127 "__asan_option_detect_stack_use_after_return";
128
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000129static const char *const kAsanShadowMemoryDynamicAddress =
130 "__asan_shadow_memory_dynamic_address";
131
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000132static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
133static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000134
Kostya Serebryany874dae62012-07-16 16:15:40 +0000135// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
136static const size_t kNumberOfAccessSizes = 5;
137
Yury Gribov55441bb2014-11-21 10:29:50 +0000138static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000139
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000140// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000141static cl::opt<bool> ClEnableKasan(
142 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
143 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000144static cl::opt<bool> ClRecover(
145 "asan-recover",
146 cl::desc("Enable recovery mode (continue-after-error)."),
147 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000148
149// This flag may need to be replaced with -f[no-]asan-reads.
150static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000151 cl::desc("instrument read instructions"),
152 cl::Hidden, cl::init(true));
153static cl::opt<bool> ClInstrumentWrites(
154 "asan-instrument-writes", cl::desc("instrument write instructions"),
155 cl::Hidden, cl::init(true));
156static cl::opt<bool> ClInstrumentAtomics(
157 "asan-instrument-atomics",
158 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
159 cl::init(true));
160static cl::opt<bool> ClAlwaysSlowPath(
161 "asan-always-slow-path",
162 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
163 cl::init(false));
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000164static cl::opt<bool> ClForceDynamicShadow(
165 "asan-force-dynamic-shadow",
166 cl::desc("Load shadow address into a local variable for each function"),
167 cl::Hidden, cl::init(false));
168
Kostya Serebryany874dae62012-07-16 16:15:40 +0000169// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000170// in any given BB. Normally, this should be set to unlimited (INT_MAX),
171// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
172// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000173static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
174 "asan-max-ins-per-bb", cl::init(10000),
175 cl::desc("maximal number of instructions to instrument in any given BB"),
176 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000177// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000178static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
179 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000180static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
181 "asan-max-inline-poisoning-size",
182 cl::desc(
183 "Inline shadow poisoning for blocks up to the given size in bytes."),
184 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000186 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000187 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000188static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
189 cl::desc("Check stack-use-after-scope"),
190 cl::Hidden, cl::init(false));
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000191static cl::opt<bool> ClExperimentalPoisoning(
192 "asan-experimental-poisoning",
193 cl::desc("Enable experimental red zones and scope poisoning"), cl::Hidden,
Vitaly Buka3c4f6bf2016-08-29 19:28:34 +0000194 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000195// This flag may need to be replaced with -f[no]asan-globals.
196static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::desc("Handle global objects"), cl::Hidden,
198 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000199static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200 cl::desc("Handle C++ initializer order"),
201 cl::Hidden, cl::init(true));
202static cl::opt<bool> ClInvalidPointerPairs(
203 "asan-detect-invalid-pointer-pair",
204 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
205 cl::init(false));
206static cl::opt<unsigned> ClRealignStack(
207 "asan-realign-stack",
208 cl::desc("Realign stack to the value of this flag (power of two)"),
209 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000210static cl::opt<int> ClInstrumentationWithCallsThreshold(
211 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000212 cl::desc(
213 "If the function being instrumented contains more than "
214 "this number of memory accesses, use callbacks instead of "
215 "inline checks (-1 means never use callbacks)."),
216 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000217static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000218 "asan-memory-access-callback-prefix",
219 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
220 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000221static cl::opt<bool>
222 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
223 cl::desc("instrument dynamic allocas"),
224 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000225static cl::opt<bool> ClSkipPromotableAllocas(
226 "asan-skip-promotable-allocas",
227 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
228 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229
230// These flags allow to change the shadow mapping.
231// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000232// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000233static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234 cl::desc("scale of asan shadow mapping"),
235 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000236static cl::opt<unsigned long long> ClMappingOffset(
237 "asan-mapping-offset",
238 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
239 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000240
241// Optimization flags. Not user visible, used mostly for testing
242// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000243static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
244 cl::Hidden, cl::init(true));
245static cl::opt<bool> ClOptSameTemp(
246 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
247 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000248static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000249 cl::desc("Don't instrument scalar globals"),
250 cl::Hidden, cl::init(true));
251static cl::opt<bool> ClOptStack(
252 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
253 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000254
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000255static cl::opt<bool> ClDynamicAllocaStack(
256 "asan-stack-dynamic-alloca",
257 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000258 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000259
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000260static cl::opt<uint32_t> ClForceExperiment(
261 "asan-force-experiment",
262 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
263 cl::init(0));
264
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000265static cl::opt<bool>
266 ClUsePrivateAliasForGlobals("asan-use-private-alias",
267 cl::desc("Use private aliases for global"
268 " variables"),
269 cl::Hidden, cl::init(false));
270
Ryan Govostese51401b2016-07-05 21:53:08 +0000271static cl::opt<bool>
272 ClUseMachOGlobalsSection("asan-globals-live-support",
273 cl::desc("Use linker features to support dead "
274 "code stripping of globals "
275 "(Mach-O only)"),
276 cl::Hidden, cl::init(false));
277
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000278// Debug flags.
279static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
280 cl::init(0));
281static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
282 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000283static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
284 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000285static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
286 cl::Hidden, cl::init(-1));
287static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
288 cl::Hidden, cl::init(-1));
289
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000290STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
291STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000292STATISTIC(NumOptimizedAccessesToGlobalVar,
293 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000294STATISTIC(NumOptimizedAccessesToStackVar,
295 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000296
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000297namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000298/// Frontend-provided metadata for source location.
299struct LocationMetadata {
300 StringRef Filename;
301 int LineNo;
302 int ColumnNo;
303
304 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
305
306 bool empty() const { return Filename.empty(); }
307
308 void parse(MDNode *MDN) {
309 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000310 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
311 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000312 LineNo =
313 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
314 ColumnNo =
315 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000316 }
317};
318
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000319/// Frontend-provided metadata for global variables.
320class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000321 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000322 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000323 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000324 LocationMetadata SourceLoc;
325 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000326 bool IsDynInit;
327 bool IsBlacklisted;
328 };
329
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000330 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000331
Keno Fischere03fae42015-12-05 14:42:34 +0000332 void reset() {
333 inited_ = false;
334 Entries.clear();
335 }
336
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000337 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000338 assert(!inited_);
339 inited_ = true;
340 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000341 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000342 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000343 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000344 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000345 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000346 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000347 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000348 // We can already have an entry for GV if it was merged with another
349 // global.
350 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000351 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
352 E.SourceLoc.parse(Loc);
353 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
354 E.Name = Name->getString();
355 ConstantInt *IsDynInit =
356 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000357 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000358 ConstantInt *IsBlacklisted =
359 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000360 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000361 }
362 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000363
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000364 /// Returns metadata entry for a given global.
365 Entry get(GlobalVariable *G) const {
366 auto Pos = Entries.find(G);
367 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000368 }
369
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000370 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000371 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000372 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000373};
374
Alexey Samsonov1345d352013-01-16 13:23:28 +0000375/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000376/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000377struct ShadowMapping {
378 int Scale;
379 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000380 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000381};
382
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000383static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
384 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000385 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000386 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000387 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
388 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000389 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
390 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000391 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000392 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000393 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000394 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
395 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000396 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
397 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000398 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000399 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000400
401 ShadowMapping Mapping;
402
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000403 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000404 // Android is always PIE, which means that the beginning of the address
405 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000406 if (IsAndroid)
407 Mapping.Offset = 0;
408 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000409 Mapping.Offset = kMIPS32_ShadowOffset32;
410 else if (IsFreeBSD)
411 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000412 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000413 // If we're targeting iOS and x86, the binary is built for iOS simulator.
414 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000415 else if (IsWindows)
416 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000417 else
418 Mapping.Offset = kDefaultShadowOffset32;
419 } else { // LongSize == 64
420 if (IsPPC64)
421 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000422 else if (IsSystemZ)
423 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000424 else if (IsFreeBSD)
425 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000426 else if (IsLinux && IsX86_64) {
427 if (IsKasan)
428 Mapping.Offset = kLinuxKasan_ShadowOffset64;
429 else
430 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000431 } else if (IsWindows && IsX86_64) {
432 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000433 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000434 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000435 else if (IsIOS)
436 // If we're targeting iOS and x86, the binary is built for iOS simulator.
437 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000438 else if (IsAArch64)
439 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000440 else
441 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000442 }
443
444 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000445 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000446 Mapping.Scale = ClMappingScale;
447 }
448
Ryan Govostes3f37df02016-05-06 10:25:22 +0000449 if (ClMappingOffset.getNumOccurrences() > 0) {
450 Mapping.Offset = ClMappingOffset;
451 }
452
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000453 // OR-ing shadow offset if more efficient (at least on x86) if the offset
454 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000455 // offset is not necessary 1/8-th of the address space. On SystemZ,
456 // we could OR the constant in a single instruction, but it's more
457 // efficient to load it once and use indexed addressing.
458 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000459 && !(Mapping.Offset & (Mapping.Offset - 1))
460 && Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000461
Alexey Samsonov1345d352013-01-16 13:23:28 +0000462 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000463}
464
Alexey Samsonov1345d352013-01-16 13:23:28 +0000465static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000466 // Redzone used for stack and globals is at least 32 bytes.
467 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000468 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000469}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000470
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000471/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000472struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000473 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
474 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000475 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000476 Recover(Recover || ClRecover),
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000477 UseAfterScope(UseAfterScope || ClUseAfterScope),
478 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000479 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
480 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000481 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000482 return "AddressSanitizerFunctionPass";
483 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000484 void getAnalysisUsage(AnalysisUsage &AU) const override {
485 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000486 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000487 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000488 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000489 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000490 if (AI.isArrayAllocation()) {
491 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000492 assert(CI && "non-constant array size");
493 ArraySize = CI->getZExtValue();
494 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000495 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000496 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000497 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000498 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000499 }
500 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000501 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000502
Anna Zaks8ed1d812015-02-27 03:12:36 +0000503 /// If it is an interesting memory access, return the PointerOperand
504 /// and set IsWrite/Alignment. Otherwise return nullptr.
505 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000506 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000507 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000508 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000509 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000510 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
511 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000512 Value *SizeArgument, bool UseCalls, uint32_t Exp);
513 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
514 uint32_t TypeSize, bool IsWrite,
515 Value *SizeArgument, bool UseCalls,
516 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000517 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
518 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000519 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000520 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000521 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000522 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000523 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000524 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000525 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000526 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000527 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000528 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000529 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000530 static char ID; // Pass identification, replacement for typeid
531
Yury Gribov3ae427d2014-12-01 08:47:58 +0000532 DominatorTree &getDominatorTree() const { return *DT; }
533
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000534 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000535 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000536
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000537 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000538 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000539 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
540 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000541
Reid Kleckner2f907552015-07-21 17:40:14 +0000542 /// Helper to cleanup per-function state.
543 struct FunctionStateRAII {
544 AddressSanitizer *Pass;
545 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
546 assert(Pass->ProcessedAllocas.empty() &&
547 "last pass forgot to clear cache");
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000548 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000549 }
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000550 ~FunctionStateRAII() {
551 Pass->LocalDynamicShadow = nullptr;
552 Pass->ProcessedAllocas.clear();
553 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000554 };
555
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000556 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000557 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000558 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000559 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000560 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000561 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000562 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000563 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000564 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000565 Function *AsanCtorFunction = nullptr;
566 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000567 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000568 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000569 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
570 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
571 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
572 // This array is indexed by AccessIsWrite and Experiment.
573 Function *AsanErrorCallbackSized[2][2];
574 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000575 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000576 InlineAsm *EmptyAsm;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000577 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000578 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000579 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000580
581 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000582};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000583
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000584class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000585 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000586 explicit AddressSanitizerModule(bool CompileKernel = false,
587 bool Recover = false)
588 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
589 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000590 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000591 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000592 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000593
Kostya Serebryany20a79972012-11-22 03:18:50 +0000594 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000595 void initializeCallbacks(Module &M);
596
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000597 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000598 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000599 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000600 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000601 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000602 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000603 return RedzoneSizeForScale(Mapping.Scale);
604 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000605
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000606 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000607 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000608 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000609 Type *IntptrTy;
610 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000611 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000612 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000613 Function *AsanPoisonGlobals;
614 Function *AsanUnpoisonGlobals;
615 Function *AsanRegisterGlobals;
616 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000617 Function *AsanRegisterImageGlobals;
618 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000619};
620
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000621// Stack poisoning does not play well with exception handling.
622// When an exception is thrown, we essentially bypass the code
623// that unpoisones the stack. This is why the run-time library has
624// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
625// stack in the interceptor. This however does not work inside the
626// actual function which catches the exception. Most likely because the
627// compiler hoists the load of the shadow value somewhere too high.
628// This causes asan to report a non-existing bug on 453.povray.
629// It sounds like an LLVM bug.
630struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
631 Function &F;
632 AddressSanitizer &ASan;
633 DIBuilder DIB;
634 LLVMContext *C;
635 Type *IntptrTy;
636 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000637 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000638
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000639 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000640 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000641 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642 unsigned StackAlignment;
643
Kostya Serebryany6805de52013-09-10 13:16:56 +0000644 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000645 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000646 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000647 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000648 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000649
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000650 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
651 struct AllocaPoisonCall {
652 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000653 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000654 uint64_t Size;
655 bool DoPoison;
656 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000657 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
658 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000659
Yury Gribov98b18592015-05-28 07:51:49 +0000660 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
661 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
662 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000663 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000664
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000665 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000666 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000667 AllocaForValueMapTy AllocaForValue;
668
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000669 bool HasNonEmptyInlineAsm = false;
670 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000671 std::unique_ptr<CallInst> EmptyInlineAsm;
672
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000673 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000674 : F(F),
675 ASan(ASan),
676 DIB(*F.getParent(), /*AllowUnresolved*/ false),
677 C(ASan.C),
678 IntptrTy(ASan.IntptrTy),
679 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
680 Mapping(ASan.Mapping),
681 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000682 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000683
684 bool runOnFunction() {
685 if (!ClStack) return false;
686 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000687 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000688
Yury Gribov55441bb2014-11-21 10:29:50 +0000689 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000690
691 initializeCallbacks(*F.getParent());
692
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000693 processDynamicAllocas();
694 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695
696 if (ClDebugStack) {
697 DEBUG(dbgs() << F);
698 }
699 return true;
700 }
701
Yury Gribov55441bb2014-11-21 10:29:50 +0000702 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000703 // poisoned red zones around all of them.
704 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000705 void processStaticAllocas();
706 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000707
Yury Gribov98b18592015-05-28 07:51:49 +0000708 void createDynamicAllocasInitStorage();
709
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000710 // ----------------------- Visitors.
711 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000712 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000713
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000714 /// \brief Collect all Resume instructions.
715 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
716
717 /// \brief Collect all CatchReturnInst instructions.
718 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
719
Yury Gribov98b18592015-05-28 07:51:49 +0000720 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
721 Value *SavedStack) {
722 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000723 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
724 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
725 // need to adjust extracted SP to compute the address of the most recent
726 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
727 // this purpose.
728 if (!isa<ReturnInst>(InstBefore)) {
729 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
730 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
731 {IntptrTy});
732
733 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
734
735 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
736 DynamicAreaOffset);
737 }
738
Yury Gribov781bce22015-05-28 08:03:28 +0000739 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000740 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000741 }
742
Yury Gribov55441bb2014-11-21 10:29:50 +0000743 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000744 void unpoisonDynamicAllocas() {
745 for (auto &Ret : RetVec)
746 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000747
Yury Gribov98b18592015-05-28 07:51:49 +0000748 for (auto &StackRestoreInst : StackRestoreVec)
749 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
750 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000751 }
752
Yury Gribov55441bb2014-11-21 10:29:50 +0000753 // Deploy and poison redzones around dynamic alloca call. To do this, we
754 // should replace this call with another one with changed parameters and
755 // replace all its uses with new address, so
756 // addr = alloca type, old_size, align
757 // is replaced by
758 // new_size = (old_size + additional_size) * sizeof(type)
759 // tmp = alloca i8, new_size, max(align, 32)
760 // addr = tmp + 32 (first 32 bytes are for the left redzone).
761 // Additional_size is added to make new memory allocation contain not only
762 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000763 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000764
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000765 /// \brief Collect Alloca instructions we want (and can) handle.
766 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000767 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000768 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000769 return;
770 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000771
772 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000773 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000774 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000775 else
776 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000777 }
778
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000779 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
780 /// errors.
781 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000782 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000783 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000784 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000785 if (!ASan.UseAfterScope)
786 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000787 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000788 return;
789 // Found lifetime intrinsic, add ASan instrumentation if necessary.
790 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
791 // If size argument is undefined, don't do anything.
792 if (Size->isMinusOne()) return;
793 // Check that size doesn't saturate uint64_t and can
794 // be stored in IntptrTy.
795 const uint64_t SizeValue = Size->getValue().getLimitedValue();
796 if (SizeValue == ~0ULL ||
797 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
798 return;
799 // Find alloca instruction that corresponds to llvm.lifetime argument.
800 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000801 if (!AI || !ASan.isInterestingAlloca(*AI))
802 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000803 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000804 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000805 if (AI->isStaticAlloca())
806 StaticAllocaPoisonCallVec.push_back(APC);
807 else if (ClInstrumentDynamicAllocas)
808 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000809 }
810
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000811 void visitCallSite(CallSite CS) {
812 Instruction *I = CS.getInstruction();
813 if (CallInst *CI = dyn_cast<CallInst>(I)) {
814 HasNonEmptyInlineAsm |=
815 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
816 HasReturnsTwiceCall |= CI->canReturnTwice();
817 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000818 }
819
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000820 // ---------------------- Helpers.
821 void initializeCallbacks(Module &M);
822
Yury Gribov3ae427d2014-12-01 08:47:58 +0000823 bool doesDominateAllExits(const Instruction *I) const {
824 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000825 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000826 }
827 return true;
828 }
829
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000830 /// Finds alloca where the value comes from.
831 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000832
833 // Copies bytes from ShadowBytes into shadow memory for indexes where
834 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
835 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
836 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
837 IRBuilder<> &IRB, Value *ShadowBase);
838 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
839 size_t Begin, size_t End, IRBuilder<> &IRB,
840 Value *ShadowBase);
841 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
842 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
843 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
844
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000845 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000846
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000847 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
848 bool Dynamic);
849 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
850 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000851};
852
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000853} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000854
855char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000856INITIALIZE_PASS_BEGIN(
857 AddressSanitizer, "asan",
858 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
859 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000860INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000861INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000862INITIALIZE_PASS_END(
863 AddressSanitizer, "asan",
864 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
865 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000866FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000867 bool Recover,
868 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000869 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000870 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000871}
872
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000873char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000874INITIALIZE_PASS(
875 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000876 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000877 "ModulePass",
878 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000879ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
880 bool Recover) {
881 assert(!CompileKernel || Recover);
882 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000883}
884
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000885static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000886 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000887 assert(Res < kNumberOfAccessSizes);
888 return Res;
889}
890
Bill Wendling58f8cef2013-08-06 22:52:42 +0000891// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
893 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000894 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000895 // We use private linkage for module-local strings. If they can be merged
896 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000897 GlobalVariable *GV =
898 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000899 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000900 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000901 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
902 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000903}
904
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000905/// \brief Create a global describing a source location.
906static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
907 LocationMetadata MD) {
908 Constant *LocData[] = {
909 createPrivateGlobalForString(M, MD.Filename, true),
910 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
911 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
912 };
913 auto LocStruct = ConstantStruct::getAnon(LocData);
914 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
915 GlobalValue::PrivateLinkage, LocStruct,
916 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000917 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000918 return GV;
919}
920
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000921/// \brief Check if \p G has been created by a trusted compiler pass.
922static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
923 // Do not instrument asan globals.
924 if (G->getName().startswith(kAsanGenPrefix) ||
925 G->getName().startswith(kSanCovGenPrefix) ||
926 G->getName().startswith(kODRGenPrefix))
927 return true;
928
929 // Do not instrument gcov counter arrays.
930 if (G->getName() == "__llvm_gcov_ctr")
931 return true;
932
933 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000934}
935
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000936Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
937 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000938 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000939 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000940 // (Shadow >> scale) | offset
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000941 Value *ShadowBase;
942 if (LocalDynamicShadow)
943 ShadowBase = LocalDynamicShadow;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000944 else
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000945 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
946 if (Mapping.OrShadowOffset)
947 return IRB.CreateOr(Shadow, ShadowBase);
948 else
949 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000950}
951
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000952// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000953void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
954 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000955 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000956 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000957 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000958 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
959 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
960 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000961 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000962 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000963 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000964 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
965 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
966 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000967 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000968 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000969}
970
Anna Zaks8ed1d812015-02-27 03:12:36 +0000971/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000972bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000973 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
974
975 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
976 return PreviouslySeenAllocaInfo->getSecond();
977
Yury Gribov98b18592015-05-28 07:51:49 +0000978 bool IsInteresting =
979 (AI.getAllocatedType()->isSized() &&
980 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000981 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000982 // We are only interested in allocas not promotable to registers.
983 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000984 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
985 // inalloca allocas are not treated as static, and we don't want
986 // dynamic alloca instrumentation for them as well.
987 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000988
989 ProcessedAllocas[&AI] = IsInteresting;
990 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000991}
992
993/// If I is an interesting memory access, return the PointerOperand
994/// and set IsWrite/Alignment. Otherwise return nullptr.
995Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
996 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000997 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000998 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000999 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001000 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001001
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001002 // Do not instrument the load fetching the dynamic shadow address.
1003 if (LocalDynamicShadow == I)
1004 return nullptr;
1005
Anna Zaks8ed1d812015-02-27 03:12:36 +00001006 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001007 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001008 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001009 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001010 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001011 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001012 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001013 PtrOperand = LI->getPointerOperand();
1014 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001015 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001016 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001017 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001018 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001019 PtrOperand = SI->getPointerOperand();
1020 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001021 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001022 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001023 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001024 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001025 PtrOperand = RMW->getPointerOperand();
1026 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001027 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001028 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001029 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001030 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001031 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +00001032 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001033
Anna Zaks644d9d32016-06-22 00:15:52 +00001034 // Do not instrument acesses from different address spaces; we cannot deal
1035 // with them.
1036 if (PtrOperand) {
1037 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1038 if (PtrTy->getPointerAddressSpace() != 0)
1039 return nullptr;
1040 }
1041
Anna Zaks8ed1d812015-02-27 03:12:36 +00001042 // Treat memory accesses to promotable allocas as non-interesting since they
1043 // will not cause memory violations. This greatly speeds up the instrumented
1044 // executable at -O0.
1045 if (ClSkipPromotableAllocas)
1046 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1047 return isInterestingAlloca(*AI) ? AI : nullptr;
1048
1049 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001050}
1051
Kostya Serebryany796f6552014-02-27 12:45:36 +00001052static bool isPointerOperand(Value *V) {
1053 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1054}
1055
1056// This is a rough heuristic; it may cause both false positives and
1057// false negatives. The proper implementation requires cooperation with
1058// the frontend.
1059static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1060 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001061 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001062 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001063 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001064 } else {
1065 return false;
1066 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001067 return isPointerOperand(I->getOperand(0)) &&
1068 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001069}
1070
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001071bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1072 // If a global variable does not have dynamic initialization we don't
1073 // have to instrument it. However, if a global does not have initializer
1074 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001075 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001076}
1077
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001078void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1079 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001080 IRBuilder<> IRB(I);
1081 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1082 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001083 for (Value *&i : Param) {
1084 if (i->getType()->isPointerTy())
1085 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001086 }
David Blaikieff6409d2015-05-18 22:13:54 +00001087 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001088}
1089
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001090void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001091 Instruction *I, bool UseCalls,
1092 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001093 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001094 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001095 uint64_t TypeSize = 0;
1096 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001097 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001098
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001099 // Optimization experiments.
1100 // The experiments can be used to evaluate potential optimizations that remove
1101 // instrumentation (assess false negatives). Instead of completely removing
1102 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1103 // experiments that want to remove instrumentation of this instruction).
1104 // If Exp is non-zero, this pass will emit special calls into runtime
1105 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1106 // make runtime terminate the program in a special way (with a different
1107 // exit status). Then you run the new compiler on a buggy corpus, collect
1108 // the special terminations (ideally, you don't see them at all -- no false
1109 // negatives) and make the decision on the optimization.
1110 uint32_t Exp = ClForceExperiment;
1111
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001112 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001113 // If initialization order checking is disabled, a simple access to a
1114 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001115 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001116 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001117 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1118 NumOptimizedAccessesToGlobalVar++;
1119 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001120 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001121 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001122
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001123 if (ClOpt && ClOptStack) {
1124 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001125 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001126 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1127 NumOptimizedAccessesToStackVar++;
1128 return;
1129 }
1130 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001131
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001132 if (IsWrite)
1133 NumInstrumentedWrites++;
1134 else
1135 NumInstrumentedReads++;
1136
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001137 unsigned Granularity = 1 << Mapping.Scale;
1138 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1139 // if the data is properly aligned.
1140 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1141 TypeSize == 128) &&
1142 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001143 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1144 Exp);
1145 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1146 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001147}
1148
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001149Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1150 Value *Addr, bool IsWrite,
1151 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001152 Value *SizeArgument,
1153 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001154 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001155 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1156 CallInst *Call = nullptr;
1157 if (SizeArgument) {
1158 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001159 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1160 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001161 else
David Blaikieff6409d2015-05-18 22:13:54 +00001162 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1163 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001164 } else {
1165 if (Exp == 0)
1166 Call =
1167 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1168 else
David Blaikieff6409d2015-05-18 22:13:54 +00001169 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1170 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001171 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001172
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001173 // We don't do Call->setDoesNotReturn() because the BB already has
1174 // UnreachableInst at the end.
1175 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001176 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001177 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001178}
1179
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001180Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001181 Value *ShadowValue,
1182 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001183 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001184 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001185 Value *LastAccessedByte =
1186 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001187 // (Addr & (Granularity - 1)) + size - 1
1188 if (TypeSize / 8 > 1)
1189 LastAccessedByte = IRB.CreateAdd(
1190 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1191 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001192 LastAccessedByte =
1193 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001194 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1195 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1196}
1197
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001198void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001199 Instruction *InsertBefore, Value *Addr,
1200 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001201 Value *SizeArgument, bool UseCalls,
1202 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001203 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001204 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001205 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1206
1207 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001208 if (Exp == 0)
1209 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1210 AddrLong);
1211 else
David Blaikieff6409d2015-05-18 22:13:54 +00001212 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1213 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001214 return;
1215 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001216
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001217 Type *ShadowTy =
1218 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001219 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1220 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1221 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001222 Value *ShadowValue =
1223 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001224
1225 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001226 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001227 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001228
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001229 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001230 // We use branch weights for the slow path check, to indicate that the slow
1231 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001232 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1233 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001234 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001235 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001236 IRB.SetInsertPoint(CheckTerm);
1237 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001238 if (Recover) {
1239 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1240 } else {
1241 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001242 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001243 CrashTerm = new UnreachableInst(*C, CrashBlock);
1244 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1245 ReplaceInstWithInst(CheckTerm, NewTerm);
1246 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001247 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001248 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001249 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001250
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001251 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001252 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001253 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001254}
1255
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001256// Instrument unusual size or unusual alignment.
1257// We can not do it with a single check, so we do 1-byte check for the first
1258// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1259// to report the actual access size.
1260void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1261 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1262 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1263 IRBuilder<> IRB(I);
1264 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1265 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1266 if (UseCalls) {
1267 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001268 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1269 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001270 else
David Blaikieff6409d2015-05-18 22:13:54 +00001271 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1272 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001273 } else {
1274 Value *LastByte = IRB.CreateIntToPtr(
1275 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1276 Addr->getType());
1277 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1278 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1279 }
1280}
1281
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001282void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1283 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001284 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001285 IRBuilder<> IRB(&GlobalInit.front(),
1286 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001287
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001288 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001289 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1290 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001291
1292 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001293 for (auto &BB : GlobalInit.getBasicBlockList())
1294 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001295 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001296}
1297
1298void AddressSanitizerModule::createInitializerPoisonCalls(
1299 Module &M, GlobalValue *ModuleName) {
1300 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1301
1302 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1303 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001304 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001305 ConstantStruct *CS = cast<ConstantStruct>(OP);
1306
1307 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001308 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001309 if (F->getName() == kAsanModuleCtorName) continue;
1310 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1311 // Don't instrument CTORs that will run before asan.module_ctor.
1312 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1313 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001314 }
1315 }
1316}
1317
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001318bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001319 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001320 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001321
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001322 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001323 if (!Ty->isSized()) return false;
1324 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001325 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001326 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001327 // Don't handle ODR linkage types and COMDATs since other modules may be built
1328 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001329 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1330 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1331 G->getLinkage() != GlobalVariable::InternalLinkage)
1332 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001333 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001334 // Two problems with thread-locals:
1335 // - The address of the main thread's copy can't be computed at link-time.
1336 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001337 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001338 // For now, just ignore this Global if the alignment is large.
1339 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001340
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001341 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001342 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001343
Anna Zaks11904602015-06-09 00:58:08 +00001344 // Globals from llvm.metadata aren't emitted, do not instrument them.
1345 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001346 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001347 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001348
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001349 // Do not instrument function pointers to initialization and termination
1350 // routines: dynamic linker will not properly handle redzones.
1351 if (Section.startswith(".preinit_array") ||
1352 Section.startswith(".init_array") ||
1353 Section.startswith(".fini_array")) {
1354 return false;
1355 }
1356
Anna Zaks11904602015-06-09 00:58:08 +00001357 // Callbacks put into the CRT initializer/terminator sections
1358 // should not be instrumented.
1359 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1360 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1361 if (Section.startswith(".CRT")) {
1362 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1363 return false;
1364 }
1365
Kuba Brecka1001bb52014-12-05 22:19:18 +00001366 if (TargetTriple.isOSBinFormatMachO()) {
1367 StringRef ParsedSegment, ParsedSection;
1368 unsigned TAA = 0, StubSize = 0;
1369 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001370 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1371 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001372 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001373
1374 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1375 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1376 // them.
1377 if (ParsedSegment == "__OBJC" ||
1378 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1379 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1380 return false;
1381 }
1382 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1383 // Constant CFString instances are compiled in the following way:
1384 // -- the string buffer is emitted into
1385 // __TEXT,__cstring,cstring_literals
1386 // -- the constant NSConstantString structure referencing that buffer
1387 // is placed into __DATA,__cfstring
1388 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1389 // Moreover, it causes the linker to crash on OS X 10.7
1390 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1391 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1392 return false;
1393 }
1394 // The linker merges the contents of cstring_literals and removes the
1395 // trailing zeroes.
1396 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1397 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1398 return false;
1399 }
1400 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001401 }
1402
1403 return true;
1404}
1405
Ryan Govostes653f9d02016-03-28 20:28:57 +00001406// On Mach-O platforms, we emit global metadata in a separate section of the
1407// binary in order to allow the linker to properly dead strip. This is only
1408// supported on recent versions of ld64.
1409bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001410 if (!ClUseMachOGlobalsSection)
1411 return false;
1412
Ryan Govostes653f9d02016-03-28 20:28:57 +00001413 if (!TargetTriple.isOSBinFormatMachO())
1414 return false;
1415
1416 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1417 return true;
1418 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001419 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001420 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1421 return true;
1422
1423 return false;
1424}
1425
Alexey Samsonov788381b2012-12-25 12:28:20 +00001426void AddressSanitizerModule::initializeCallbacks(Module &M) {
1427 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001428
Alexey Samsonov788381b2012-12-25 12:28:20 +00001429 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001430 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001431 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001432 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001433 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001434 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001435 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001436
Alexey Samsonov788381b2012-12-25 12:28:20 +00001437 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001438 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001439 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001440 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001441 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001442 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1443 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001444 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001445
1446 // Declare the functions that find globals in a shared object and then invoke
1447 // the (un)register function on them.
1448 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1449 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1450 IRB.getVoidTy(), IntptrTy, nullptr));
1451 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001452
Ryan Govostes653f9d02016-03-28 20:28:57 +00001453 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1454 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1455 IRB.getVoidTy(), IntptrTy, nullptr));
1456 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001457}
1458
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001459// This function replaces all global variables with new variables that have
1460// trailing redzones. It also creates a function that poisons
1461// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001462bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001463 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001464
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001465 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1466
Alexey Samsonova02e6642014-05-29 18:40:48 +00001467 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001468 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469 }
1470
1471 size_t n = GlobalsToChange.size();
1472 if (n == 0) return false;
1473
1474 // A global is described by a structure
1475 // size_t beg;
1476 // size_t size;
1477 // size_t size_with_redzone;
1478 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001479 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001480 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001481 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001482 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001483 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001484 StructType *GlobalStructTy =
1485 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001486 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001487 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001488
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001489 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001490
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001491 // We shouldn't merge same module names, as this string serves as unique
1492 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001493 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001494 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001495
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001496 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001497 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001498 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001500
1501 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001502 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001503 // Create string holding the global name (use global name from metadata
1504 // if it's available, otherwise just write the name of global variable).
1505 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001506 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001507 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001508
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001509 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001510 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001511 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001512 // MinRZ <= RZ <= kMaxGlobalRedzone
1513 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001514 uint64_t RZ = std::max(
1515 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001516 uint64_t RightRedzoneSize = RZ;
1517 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001518 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001519 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001520 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1521
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001522 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001523 Constant *NewInitializer =
1524 ConstantStruct::get(NewTy, G->getInitializer(),
1525 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001526
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001527 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001528 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1529 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1530 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001531 GlobalVariable *NewGlobal =
1532 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1533 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001534 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001535 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001536
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001537 // Transfer the debug info. The payload starts at offset zero so we can
1538 // copy the debug info over as is.
1539 SmallVector<DIGlobalVariable *, 1> GVs;
1540 G->getDebugInfo(GVs);
1541 for (auto *GV : GVs)
1542 NewGlobal->addDebugInfo(GV);
1543
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001544 Value *Indices2[2];
1545 Indices2[0] = IRB.getInt32(0);
1546 Indices2[1] = IRB.getInt32(0);
1547
1548 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001549 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001550 NewGlobal->takeName(G);
1551 G->eraseFromParent();
1552
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001553 Constant *SourceLoc;
1554 if (!MD.SourceLoc.empty()) {
1555 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1556 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1557 } else {
1558 SourceLoc = ConstantInt::get(IntptrTy, 0);
1559 }
1560
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001561 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1562 GlobalValue *InstrumentedGlobal = NewGlobal;
1563
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001564 bool CanUsePrivateAliases =
1565 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001566 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1567 // Create local alias for NewGlobal to avoid crash on ODR between
1568 // instrumented and non-instrumented libraries.
1569 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1570 NameForGlobal + M.getName(), NewGlobal);
1571
1572 // With local aliases, we need to provide another externally visible
1573 // symbol __odr_asan_XXX to detect ODR violation.
1574 auto *ODRIndicatorSym =
1575 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1576 Constant::getNullValue(IRB.getInt8Ty()),
1577 kODRGenPrefix + NameForGlobal, nullptr,
1578 NewGlobal->getThreadLocalMode());
1579
1580 // Set meaningful attributes for indicator symbol.
1581 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1582 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1583 ODRIndicatorSym->setAlignment(1);
1584 ODRIndicator = ODRIndicatorSym;
1585 InstrumentedGlobal = GA;
1586 }
1587
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001588 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001589 GlobalStructTy,
1590 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001591 ConstantInt::get(IntptrTy, SizeInBytes),
1592 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1593 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001594 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001595 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1596 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001597
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001598 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001599
Kostya Serebryany20343352012-10-17 13:40:06 +00001600 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001601 }
1602
Ryan Govostes653f9d02016-03-28 20:28:57 +00001603
1604 GlobalVariable *AllGlobals = nullptr;
1605 GlobalVariable *RegisteredFlag = nullptr;
1606
1607 // On recent Mach-O platforms, we emit the global metadata in a way that
1608 // allows the linker to properly strip dead globals.
1609 if (ShouldUseMachOGlobalsSection()) {
1610 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1611 // to look up the loaded image that contains it. Second, we can store in it
1612 // whether registration has already occurred, to prevent duplicate
1613 // registration.
1614 //
1615 // Common linkage allows us to coalesce needles defined in each object
1616 // file so that there's only one per shared library.
1617 RegisteredFlag = new GlobalVariable(
1618 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1619 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1620
1621 // We also emit a structure which binds the liveness of the global
1622 // variable to the metadata struct.
1623 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1624
1625 for (size_t i = 0; i < n; i++) {
1626 GlobalVariable *Metadata = new GlobalVariable(
1627 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1628 Initializers[i], "");
1629 Metadata->setSection("__DATA,__asan_globals,regular");
1630 Metadata->setAlignment(1); // don't leave padding in between
1631
1632 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1633 Initializers[i]->getAggregateElement(0u),
1634 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1635 nullptr);
1636 GlobalVariable *Liveness = new GlobalVariable(
1637 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1638 LivenessBinder, "");
1639 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1640 }
1641 } else {
1642 // On all other platfoms, we just emit an array of global metadata
1643 // structures.
1644 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1645 AllGlobals = new GlobalVariable(
1646 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1647 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1648 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001649
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001650 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001651 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001652 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001653
Ryan Govostes653f9d02016-03-28 20:28:57 +00001654 // Create a call to register the globals with the runtime.
1655 if (ShouldUseMachOGlobalsSection()) {
1656 IRB.CreateCall(AsanRegisterImageGlobals,
1657 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1658 } else {
1659 IRB.CreateCall(AsanRegisterGlobals,
1660 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1661 ConstantInt::get(IntptrTy, n)});
1662 }
1663
1664 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001665 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001666 Function *AsanDtorFunction =
1667 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1668 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001669 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1670 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001671
1672 if (ShouldUseMachOGlobalsSection()) {
1673 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1674 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1675 } else {
1676 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1677 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1678 ConstantInt::get(IntptrTy, n)});
1679 }
1680
Alexey Samsonov1f647502014-05-29 01:10:14 +00001681 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001682
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001683 DEBUG(dbgs() << M);
1684 return true;
1685}
1686
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001687bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001688 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001689 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001690 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001691 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001692 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001693 initializeCallbacks(M);
1694
1695 bool Changed = false;
1696
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001697 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1698 if (ClGlobals && !CompileKernel) {
1699 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1700 assert(CtorFunc);
1701 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1702 Changed |= InstrumentGlobals(IRB, M);
1703 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001704
1705 return Changed;
1706}
1707
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001708void AddressSanitizer::initializeCallbacks(Module &M) {
1709 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001710 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001711 // IsWrite, TypeSize and Exp are encoded in the function name.
1712 for (int Exp = 0; Exp < 2; Exp++) {
1713 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1714 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1715 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001716 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001717 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001718 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001719 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001720 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001721 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001722 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1723 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001724 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001725 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001726 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1727 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1728 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001729 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001730 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001731 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001732 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001733 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001734 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001735 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001736 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1737 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001738 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001739 }
1740 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001741
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001742 const std::string MemIntrinCallbackPrefix =
1743 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001744 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001745 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001746 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001747 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001748 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001749 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001750 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001751 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001752 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001753
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001754 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001755 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001756
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001757 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001758 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001759 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001760 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001761 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1762 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1763 StringRef(""), StringRef(""),
1764 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001765}
1766
1767// virtual
1768bool AddressSanitizer::doInitialization(Module &M) {
1769 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001770
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001771 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001772
1773 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001774 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001775 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001776 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001777
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001778 if (!CompileKernel) {
1779 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001780 createSanitizerCtorAndInitFunctions(
1781 M, kAsanModuleCtorName, kAsanInitName,
1782 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001783 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1784 }
1785 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001786 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001787}
1788
Keno Fischere03fae42015-12-05 14:42:34 +00001789bool AddressSanitizer::doFinalization(Module &M) {
1790 GlobalsMD.reset();
1791 return false;
1792}
1793
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001794bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1795 // For each NSObject descendant having a +load method, this method is invoked
1796 // by the ObjC runtime before any of the static constructors is called.
1797 // Therefore we need to instrument such methods with a call to __asan_init
1798 // at the beginning in order to initialize our runtime before any access to
1799 // the shadow memory.
1800 // We cannot just ignore these methods, because they may call other
1801 // instrumented functions.
1802 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001803 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001804 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001805 return true;
1806 }
1807 return false;
1808}
1809
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001810void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
1811 // Generate code only when dynamic addressing is needed.
1812 if (!ClForceDynamicShadow && Mapping.Offset != kDynamicShadowSentinel)
1813 return;
1814
1815 IRBuilder<> IRB(&F.front().front());
1816 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
1817 kAsanShadowMemoryDynamicAddress, IntptrTy);
1818 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
1819}
1820
Reid Kleckner2f907552015-07-21 17:40:14 +00001821void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1822 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1823 // to it as uninteresting. This assumes we haven't started processing allocas
1824 // yet. This check is done up front because iterating the use list in
1825 // isInterestingAlloca would be algorithmically slower.
1826 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1827
1828 // Try to get the declaration of llvm.localescape. If it's not in the module,
1829 // we can exit early.
1830 if (!F.getParent()->getFunction("llvm.localescape")) return;
1831
1832 // Look for a call to llvm.localescape call in the entry block. It can't be in
1833 // any other block.
1834 for (Instruction &I : F.getEntryBlock()) {
1835 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1836 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1837 // We found a call. Mark all the allocas passed in as uninteresting.
1838 for (Value *Arg : II->arg_operands()) {
1839 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1840 assert(AI && AI->isStaticAlloca() &&
1841 "non-static alloca arg to localescape");
1842 ProcessedAllocas[AI] = false;
1843 }
1844 break;
1845 }
1846 }
1847}
1848
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001849bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001850 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001851 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001852 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00001853 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001854
Etienne Bergeron78582b22016-09-15 15:45:05 +00001855 bool FunctionModified = false;
1856
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001857 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00001858 // This function needs to be called even if the function body is not
1859 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001860 if (maybeInsertAsanInitAtFunctionEntry(F))
1861 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001862
1863 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001864 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001865
Etienne Bergeron752f8832016-09-14 17:18:37 +00001866 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1867
1868 initializeCallbacks(*F.getParent());
1869 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001870
Reid Kleckner2f907552015-07-21 17:40:14 +00001871 FunctionStateRAII CleanupObj(this);
1872
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001873 maybeInsertDynamicShadowAtFunctionEntry(F);
1874
Reid Kleckner2f907552015-07-21 17:40:14 +00001875 // We can't instrument allocas used with llvm.localescape. Only static allocas
1876 // can be passed to that intrinsic.
1877 markEscapedLocalAllocas(F);
1878
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001879 // We want to instrument every address only once per basic block (unless there
1880 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001881 SmallSet<Value *, 16> TempsToInstrument;
1882 SmallVector<Instruction *, 16> ToInstrument;
1883 SmallVector<Instruction *, 8> NoReturnCalls;
1884 SmallVector<BasicBlock *, 16> AllBlocks;
1885 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001886 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001887 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001888 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001889 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001890 const TargetLibraryInfo *TLI =
1891 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001892
1893 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001894 for (auto &BB : F) {
1895 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001896 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001897 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001898 for (auto &Inst : BB) {
1899 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001900 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1901 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001902 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001903 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001904 continue; // We've seen this temp in the current BB.
1905 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001906 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001907 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1908 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001909 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001910 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001911 // ok, take it.
1912 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001913 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001914 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001915 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001916 // A call inside BB.
1917 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001918 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001919 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001920 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1921 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001922 continue;
1923 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001924 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001925 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001926 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001927 }
1928 }
1929
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001930 bool UseCalls =
1931 CompileKernel ||
1932 (ClInstrumentationWithCallsThreshold >= 0 &&
1933 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001934 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001935 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1936 /*RoundToAlign=*/true);
1937
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001938 // Instrument.
1939 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001940 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001941 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1942 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001943 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001944 instrumentMop(ObjSizeVis, Inst, UseCalls,
1945 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001946 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001947 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001948 }
1949 NumInstrumented++;
1950 }
1951
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001952 FunctionStackPoisoner FSP(F, *this);
1953 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001954
1955 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1956 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001957 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001958 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001959 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001960 }
1961
Alexey Samsonova02e6642014-05-29 18:40:48 +00001962 for (auto Inst : PointerComparisonsOrSubtracts) {
1963 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001964 NumInstrumented++;
1965 }
1966
Etienne Bergeron78582b22016-09-15 15:45:05 +00001967 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
1968 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00001969
Etienne Bergeron78582b22016-09-15 15:45:05 +00001970 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
1971 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001972
Etienne Bergeron78582b22016-09-15 15:45:05 +00001973 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001974}
1975
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001976// Workaround for bug 11395: we don't want to instrument stack in functions
1977// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1978// FIXME: remove once the bug 11395 is fixed.
1979bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1980 if (LongSize != 32) return false;
1981 CallInst *CI = dyn_cast<CallInst>(I);
1982 if (!CI || !CI->isInlineAsm()) return false;
1983 if (CI->getNumArgOperands() <= 5) return false;
1984 // We have inline assembly with quite a few arguments.
1985 return true;
1986}
1987
1988void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1989 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001990 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1991 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001992 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1993 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1994 IntptrTy, nullptr));
1995 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001996 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1997 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001998 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001999 if (ASan.UseAfterScope) {
2000 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2001 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2002 IntptrTy, IntptrTy, nullptr));
2003 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2004 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2005 IntptrTy, IntptrTy, nullptr));
2006 }
2007
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002008 if (ClExperimentalPoisoning) {
2009 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2010 std::ostringstream Name;
2011 Name << kAsanSetShadowPrefix;
2012 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2013 AsanSetShadowFunc[Val] =
2014 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2015 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2016 }
2017 }
2018
Yury Gribov98b18592015-05-28 07:51:49 +00002019 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2020 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2021 AsanAllocasUnpoisonFunc =
2022 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2023 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002024}
2025
Vitaly Buka793913c2016-08-29 18:17:21 +00002026void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2027 ArrayRef<uint8_t> ShadowBytes,
2028 size_t Begin, size_t End,
2029 IRBuilder<> &IRB,
2030 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002031 if (Begin >= End)
2032 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002033
2034 const size_t LargestStoreSizeInBytes =
2035 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2036
2037 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2038
2039 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002040 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2041 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2042 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002043 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002044 if (!ShadowMask[i]) {
2045 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002046 ++i;
2047 continue;
2048 }
2049
2050 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2051 // Fit store size into the range.
2052 while (StoreSizeInBytes > End - i)
2053 StoreSizeInBytes /= 2;
2054
2055 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002056 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002057 while (j <= StoreSizeInBytes / 2)
2058 StoreSizeInBytes /= 2;
2059 }
2060
2061 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002062 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2063 if (IsLittleEndian)
2064 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2065 else
2066 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002067 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002068
2069 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2070 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002071 IRB.CreateAlignedStore(
2072 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002073
2074 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002075 }
2076}
2077
Vitaly Buka793913c2016-08-29 18:17:21 +00002078void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2079 ArrayRef<uint8_t> ShadowBytes,
2080 IRBuilder<> &IRB, Value *ShadowBase) {
2081 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2082}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002083
Vitaly Buka793913c2016-08-29 18:17:21 +00002084void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2085 ArrayRef<uint8_t> ShadowBytes,
2086 size_t Begin, size_t End,
2087 IRBuilder<> &IRB, Value *ShadowBase) {
2088 assert(ShadowMask.size() == ShadowBytes.size());
2089 size_t Done = Begin;
2090 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2091 if (!ShadowMask[i]) {
2092 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002093 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002094 }
2095 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002096 if (!AsanSetShadowFunc[Val])
2097 continue;
2098
2099 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002100 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002101 }
2102
2103 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002104 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002105 IRB.CreateCall(AsanSetShadowFunc[Val],
2106 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2107 ConstantInt::get(IntptrTy, j - i)});
2108 Done = j;
2109 }
2110 }
2111
Vitaly Buka793913c2016-08-29 18:17:21 +00002112 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002113}
2114
Kostya Serebryany6805de52013-09-10 13:16:56 +00002115// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2116// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2117static int StackMallocSizeClass(uint64_t LocalStackSize) {
2118 assert(LocalStackSize <= kMaxStackMallocSize);
2119 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002120 for (int i = 0;; i++, MaxSize *= 2)
2121 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002122 llvm_unreachable("impossible LocalStackSize");
2123}
2124
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002125PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2126 Value *ValueIfTrue,
2127 Instruction *ThenTerm,
2128 Value *ValueIfFalse) {
2129 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2130 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2131 PHI->addIncoming(ValueIfFalse, CondBlock);
2132 BasicBlock *ThenBlock = ThenTerm->getParent();
2133 PHI->addIncoming(ValueIfTrue, ThenBlock);
2134 return PHI;
2135}
2136
2137Value *FunctionStackPoisoner::createAllocaForLayout(
2138 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2139 AllocaInst *Alloca;
2140 if (Dynamic) {
2141 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2142 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2143 "MyAlloca");
2144 } else {
2145 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2146 nullptr, "MyAlloca");
2147 assert(Alloca->isStaticAlloca());
2148 }
2149 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2150 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2151 Alloca->setAlignment(FrameAlignment);
2152 return IRB.CreatePointerCast(Alloca, IntptrTy);
2153}
2154
Yury Gribov98b18592015-05-28 07:51:49 +00002155void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2156 BasicBlock &FirstBB = *F.begin();
2157 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2158 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2159 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2160 DynamicAllocaLayout->setAlignment(32);
2161}
2162
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002163void FunctionStackPoisoner::processDynamicAllocas() {
2164 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2165 assert(DynamicAllocaPoisonCallVec.empty());
2166 return;
2167 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002168
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002169 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2170 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002171 assert(APC.InsBefore);
2172 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002173 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002174 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002175
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002176 IRBuilder<> IRB(APC.InsBefore);
2177 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002178 // Dynamic allocas will be unpoisoned unconditionally below in
2179 // unpoisonDynamicAllocas.
2180 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002181 }
2182
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002183 // Handle dynamic allocas.
2184 createDynamicAllocasInitStorage();
2185 for (auto &AI : DynamicAllocaVec)
2186 handleDynamicAllocaCall(AI);
2187 unpoisonDynamicAllocas();
2188}
Yury Gribov98b18592015-05-28 07:51:49 +00002189
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002190void FunctionStackPoisoner::processStaticAllocas() {
2191 if (AllocaVec.empty()) {
2192 assert(StaticAllocaPoisonCallVec.empty());
2193 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002194 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002195
Kostya Serebryany6805de52013-09-10 13:16:56 +00002196 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002197 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002198 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002199 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002200
2201 Instruction *InsBefore = AllocaVec[0];
2202 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002203 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002204
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002205 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2206 // debug info is broken, because only entry-block allocas are treated as
2207 // regular stack slots.
2208 auto InsBeforeB = InsBefore->getParent();
2209 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002210 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2211 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002212 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2213 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002214
Reid Kleckner2f907552015-07-21 17:40:14 +00002215 // If we have a call to llvm.localescape, keep it in the entry block.
2216 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2217
Vitaly Buka793913c2016-08-29 18:17:21 +00002218 // Find static allocas with lifetime analysis.
2219 DenseMap<const AllocaInst *, const ASanStackVariableDescription *>
2220 AllocaToSVDMap;
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002221 for (const auto &APC : StaticAllocaPoisonCallVec) {
2222 assert(APC.InsBefore);
2223 assert(APC.AI);
2224 assert(ASan.isInterestingAlloca(*APC.AI));
2225 assert(APC.AI->isStaticAlloca());
2226
Vitaly Buka793913c2016-08-29 18:17:21 +00002227 if (ClExperimentalPoisoning) {
2228 AllocaToSVDMap[APC.AI] = nullptr;
2229 } else {
2230 IRBuilder<> IRB(APC.InsBefore);
2231 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2232 }
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002233 }
2234
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002235 SmallVector<ASanStackVariableDescription, 16> SVD;
2236 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002237 for (AllocaInst *AI : AllocaVec) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002238 size_t UseAfterScopePoisonSize =
2239 AllocaToSVDMap.find(AI) != AllocaToSVDMap.end()
2240 ? ASan.getAllocaSizeInBytes(*AI)
2241 : 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002242 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002243 ASan.getAllocaSizeInBytes(*AI),
Vitaly Buka793913c2016-08-29 18:17:21 +00002244 UseAfterScopePoisonSize,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002245 AI->getAlignment(),
2246 AI,
2247 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002248 SVD.push_back(D);
2249 }
2250 // Minimal header size (left redzone) is 4 pointers,
2251 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2252 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002253 const ASanStackFrameLayout &L =
2254 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002255
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002256 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2257 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002258 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2259 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002260 bool DoDynamicAlloca = ClDynamicAllocaStack;
2261 // Don't do dynamic alloca or stack malloc if:
2262 // 1) There is inline asm: too often it makes assumptions on which registers
2263 // are available.
2264 // 2) There is a returns_twice call (typically setjmp), which is
2265 // optimization-hostile, and doesn't play well with introduced indirect
2266 // register-relative calculation of local variable addresses.
2267 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2268 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002269
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002270 Value *StaticAlloca =
2271 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2272
2273 Value *FakeStack;
2274 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002275
2276 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002277 // void *FakeStack = __asan_option_detect_stack_use_after_return
2278 // ? __asan_stack_malloc_N(LocalStackSize)
2279 // : nullptr;
2280 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002281 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2282 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2283 Value *UseAfterReturnIsEnabled =
2284 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002285 Constant::getNullValue(IRB.getInt32Ty()));
2286 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002287 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002288 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002289 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002290 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2291 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2292 Value *FakeStackValue =
2293 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2294 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002295 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002296 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002297 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002298 ConstantInt::get(IntptrTy, 0));
2299
2300 Value *NoFakeStack =
2301 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2302 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2303 IRBIf.SetInsertPoint(Term);
2304 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2305 Value *AllocaValue =
2306 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2307 IRB.SetInsertPoint(InsBefore);
2308 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2309 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2310 } else {
2311 // void *FakeStack = nullptr;
2312 // void *LocalStackBase = alloca(LocalStackSize);
2313 FakeStack = ConstantInt::get(IntptrTy, 0);
2314 LocalStackBase =
2315 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002316 }
2317
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002318 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002319 for (const auto &Desc : SVD) {
2320 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002321 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002322 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002323 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002324 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002325 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002326 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002327
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002328 // The left-most redzone has enough space for at least 4 pointers.
2329 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002330 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2331 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2332 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002333 // Write the frame description constant to redzone[1].
2334 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002335 IRB.CreateAdd(LocalStackBase,
2336 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2337 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002338 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002339 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002340 /*AllowMerging*/ true);
2341 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002342 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002343 // Write the PC to redzone[2].
2344 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002345 IRB.CreateAdd(LocalStackBase,
2346 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2347 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002348 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002349
Vitaly Buka793913c2016-08-29 18:17:21 +00002350 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2351
2352 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002353 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002354 // As mask we must use most poisoned case: red zones and after scope.
2355 // As bytes we can use either the same or just red zones only.
2356 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2357
2358 if (ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
2359 // Complete AllocaToSVDMap
2360 for (const auto &Desc : SVD) {
2361 auto It = AllocaToSVDMap.find(Desc.AI);
2362 if (It != AllocaToSVDMap.end()) {
2363 It->second = &Desc;
2364 }
2365 }
2366
2367 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2368
2369 // Poison static allocas near lifetime intrinsics.
2370 for (const auto &APC : StaticAllocaPoisonCallVec) {
2371 // Must be already set.
2372 assert(AllocaToSVDMap[APC.AI]);
2373 const auto &Desc = *AllocaToSVDMap[APC.AI];
2374 assert(Desc.Offset % L.Granularity == 0);
2375 size_t Begin = Desc.Offset / L.Granularity;
2376 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2377
2378 IRBuilder<> IRB(APC.InsBefore);
2379 copyToShadow(ShadowAfterScope,
2380 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2381 IRB, ShadowBase);
2382 }
2383 }
2384
2385 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002386
Vitaly Buka79b75d32016-06-09 23:05:35 +00002387 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002388 // Do this always as poisonAlloca can be disabled with
2389 // detect_stack_use_after_scope=0.
Vitaly Buka793913c2016-08-29 18:17:21 +00002390 copyToShadow(ShadowAfterScope, ShadowClean, IRB, ShadowBase);
2391 if (!ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002392 // If we poisoned some allocas in llvm.lifetime analysis,
2393 // unpoison whole stack frame now.
2394 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002395 }
2396 };
2397
Vitaly Buka793913c2016-08-29 18:17:21 +00002398 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002399
Kostya Serebryany530e2072013-12-23 14:15:08 +00002400 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002401 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002402 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002403 // Mark the current frame as retired.
2404 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2405 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002406 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002407 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002408 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002409 // // In use-after-return mode, poison the whole stack frame.
2410 // if StackMallocIdx <= 4
2411 // // For small sizes inline the whole thing:
2412 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002413 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002414 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002415 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002416 // else
2417 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002418 Value *Cmp =
2419 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002420 TerminatorInst *ThenTerm, *ElseTerm;
2421 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2422
2423 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002424 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002425 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002426 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2427 kAsanStackUseAfterReturnMagic);
2428 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2429 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002430 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002431 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002432 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2433 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2434 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2435 IRBPoison.CreateStore(
2436 Constant::getNullValue(IRBPoison.getInt8Ty()),
2437 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2438 } else {
2439 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002440 IRBPoison.CreateCall(
2441 AsanStackFreeFunc[StackMallocIdx],
2442 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002443 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002444
2445 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002446 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002447 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002448 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002449 }
2450 }
2451
Kostya Serebryany09959942012-10-19 06:20:53 +00002452 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002453 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002454}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002455
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002456void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002457 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002458 // For now just insert the call to ASan runtime.
2459 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2460 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002461 IRB.CreateCall(
2462 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2463 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002464}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002465
2466// Handling llvm.lifetime intrinsics for a given %alloca:
2467// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2468// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2469// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2470// could be poisoned by previous llvm.lifetime.end instruction, as the
2471// variable may go in and out of scope several times, e.g. in loops).
2472// (3) if we poisoned at least one %alloca in a function,
2473// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002474
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002475AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2476 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002477 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002478 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002479 // See if we've already calculated (or started to calculate) alloca for a
2480 // given value.
2481 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002482 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002483 // Store 0 while we're calculating alloca for value V to avoid
2484 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002485 AllocaForValue[V] = nullptr;
2486 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002487 if (CastInst *CI = dyn_cast<CastInst>(V))
2488 Res = findAllocaForValue(CI->getOperand(0));
2489 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002490 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002491 // Allow self-referencing phi-nodes.
2492 if (IncValue == PN) continue;
2493 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2494 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002495 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2496 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002497 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002498 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002499 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2500 Res = findAllocaForValue(EP->getPointerOperand());
2501 } else {
2502 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002503 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002504 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002505 return Res;
2506}
Yury Gribov55441bb2014-11-21 10:29:50 +00002507
Yury Gribov98b18592015-05-28 07:51:49 +00002508void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002509 IRBuilder<> IRB(AI);
2510
Yury Gribov55441bb2014-11-21 10:29:50 +00002511 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2512 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2513
2514 Value *Zero = Constant::getNullValue(IntptrTy);
2515 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2516 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002517
2518 // Since we need to extend alloca with additional memory to locate
2519 // redzones, and OldSize is number of allocated blocks with
2520 // ElementSize size, get allocated memory size in bytes by
2521 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002522 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002523 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002524 Value *OldSize =
2525 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2526 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002527
2528 // PartialSize = OldSize % 32
2529 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2530
2531 // Misalign = kAllocaRzSize - PartialSize;
2532 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2533
2534 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2535 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2536 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2537
2538 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2539 // Align is added to locate left redzone, PartialPadding for possible
2540 // partial redzone and kAllocaRzSize for right redzone respectively.
2541 Value *AdditionalChunkSize = IRB.CreateAdd(
2542 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2543
2544 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2545
2546 // Insert new alloca with new NewSize and Align params.
2547 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2548 NewAlloca->setAlignment(Align);
2549
2550 // NewAddress = Address + Align
2551 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2552 ConstantInt::get(IntptrTy, Align));
2553
Yury Gribov98b18592015-05-28 07:51:49 +00002554 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002555 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002556
2557 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2558 // for unpoisoning stuff.
2559 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2560
Yury Gribov55441bb2014-11-21 10:29:50 +00002561 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2562
Yury Gribov98b18592015-05-28 07:51:49 +00002563 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002564 AI->replaceAllUsesWith(NewAddressPtr);
2565
Yury Gribov98b18592015-05-28 07:51:49 +00002566 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002567 AI->eraseFromParent();
2568}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002569
2570// isSafeAccess returns true if Addr is always inbounds with respect to its
2571// base object. For example, it is a field access or an array access with
2572// constant inbounds index.
2573bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2574 Value *Addr, uint64_t TypeSize) const {
2575 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2576 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002577 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002578 int64_t Offset = SizeOffset.second.getSExtValue();
2579 // Three checks are required to ensure safety:
2580 // . Offset >= 0 (since the offset is given from the base ptr)
2581 // . Size >= Offset (unsigned)
2582 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002583 return Offset >= 0 && Size >= uint64_t(Offset) &&
2584 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002585}