blob: 07e63b2a7df29260cb956d90c0979f6de72c382b [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
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 Bergeron0ca05682016-09-30 17:46:32 +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 Bergeron0ca05682016-09-30 17:46:32 +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 Bergeron0ca05682016-09-30 17:46:32 +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));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000287static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000288 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
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000444 if (ClForceDynamicShadow) {
445 Mapping.Offset = kDynamicShadowSentinel;
446 }
447
Alexey Samsonov1345d352013-01-16 13:23:28 +0000448 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000449 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000450 Mapping.Scale = ClMappingScale;
451 }
452
Ryan Govostes3f37df02016-05-06 10:25:22 +0000453 if (ClMappingOffset.getNumOccurrences() > 0) {
454 Mapping.Offset = ClMappingOffset;
455 }
456
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000457 // OR-ing shadow offset if more efficient (at least on x86) if the offset
458 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000459 // offset is not necessary 1/8-th of the address space. On SystemZ,
460 // we could OR the constant in a single instruction, but it's more
461 // efficient to load it once and use indexed addressing.
462 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000463 && !(Mapping.Offset & (Mapping.Offset - 1))
464 && Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000465
Alexey Samsonov1345d352013-01-16 13:23:28 +0000466 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000467}
468
Alexey Samsonov1345d352013-01-16 13:23:28 +0000469static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000470 // Redzone used for stack and globals is at least 32 bytes.
471 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000472 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000473}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000474
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000475/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000476struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000477 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
478 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000479 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000480 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000481 UseAfterScope(UseAfterScope || ClUseAfterScope),
482 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000483 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
484 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000485 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000486 return "AddressSanitizerFunctionPass";
487 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000488 void getAnalysisUsage(AnalysisUsage &AU) const override {
489 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000490 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000491 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000492 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000493 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000494 if (AI.isArrayAllocation()) {
495 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000496 assert(CI && "non-constant array size");
497 ArraySize = CI->getZExtValue();
498 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000499 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000500 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000501 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000502 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000503 }
504 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000505 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000506
Anna Zaks8ed1d812015-02-27 03:12:36 +0000507 /// If it is an interesting memory access, return the PointerOperand
508 /// and set IsWrite/Alignment. Otherwise return nullptr.
509 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000510 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000511 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000512 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000513 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000514 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
515 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000516 Value *SizeArgument, bool UseCalls, uint32_t Exp);
517 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
518 uint32_t TypeSize, bool IsWrite,
519 Value *SizeArgument, bool UseCalls,
520 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000521 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
522 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000523 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000524 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000525 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000526 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000527 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000528 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000529 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000530 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000531 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000532 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000533 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000534 static char ID; // Pass identification, replacement for typeid
535
Yury Gribov3ae427d2014-12-01 08:47:58 +0000536 DominatorTree &getDominatorTree() const { return *DT; }
537
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000538 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000539 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000540
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000541 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000542 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000543 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
544 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000545
Reid Kleckner2f907552015-07-21 17:40:14 +0000546 /// Helper to cleanup per-function state.
547 struct FunctionStateRAII {
548 AddressSanitizer *Pass;
549 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
550 assert(Pass->ProcessedAllocas.empty() &&
551 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000552 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000553 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000554 ~FunctionStateRAII() {
555 Pass->LocalDynamicShadow = nullptr;
556 Pass->ProcessedAllocas.clear();
557 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000558 };
559
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000560 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000561 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000562 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000563 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000564 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000565 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000566 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000567 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000568 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000569 Function *AsanCtorFunction = nullptr;
570 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000571 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000572 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000573 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
574 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
575 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
576 // This array is indexed by AccessIsWrite and Experiment.
577 Function *AsanErrorCallbackSized[2][2];
578 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000579 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000580 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000581 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000582 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000583 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000584
585 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000586};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000587
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000588class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000589 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000590 explicit AddressSanitizerModule(bool CompileKernel = false,
591 bool Recover = false)
592 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
593 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000594 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000595 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000596 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000597
Kostya Serebryany20a79972012-11-22 03:18:50 +0000598 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000599 void initializeCallbacks(Module &M);
600
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000601 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000602 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000603 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000604 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000605 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000606 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000607 return RedzoneSizeForScale(Mapping.Scale);
608 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000609
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000610 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000611 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000612 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000613 Type *IntptrTy;
614 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000615 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000616 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000617 Function *AsanPoisonGlobals;
618 Function *AsanUnpoisonGlobals;
619 Function *AsanRegisterGlobals;
620 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000621 Function *AsanRegisterImageGlobals;
622 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000623};
624
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000625// Stack poisoning does not play well with exception handling.
626// When an exception is thrown, we essentially bypass the code
627// that unpoisones the stack. This is why the run-time library has
628// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
629// stack in the interceptor. This however does not work inside the
630// actual function which catches the exception. Most likely because the
631// compiler hoists the load of the shadow value somewhere too high.
632// This causes asan to report a non-existing bug on 453.povray.
633// It sounds like an LLVM bug.
634struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
635 Function &F;
636 AddressSanitizer &ASan;
637 DIBuilder DIB;
638 LLVMContext *C;
639 Type *IntptrTy;
640 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000641 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000643 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000644 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000645 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000646 unsigned StackAlignment;
647
Kostya Serebryany6805de52013-09-10 13:16:56 +0000648 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000649 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000650 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000651 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000652 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000653
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000654 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
655 struct AllocaPoisonCall {
656 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000657 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000658 uint64_t Size;
659 bool DoPoison;
660 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000661 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
662 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000663
Yury Gribov98b18592015-05-28 07:51:49 +0000664 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
665 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
666 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000667 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000668
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000669 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000670 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000671 AllocaForValueMapTy AllocaForValue;
672
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000673 bool HasNonEmptyInlineAsm = false;
674 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000675 std::unique_ptr<CallInst> EmptyInlineAsm;
676
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000677 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000678 : F(F),
679 ASan(ASan),
680 DIB(*F.getParent(), /*AllowUnresolved*/ false),
681 C(ASan.C),
682 IntptrTy(ASan.IntptrTy),
683 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
684 Mapping(ASan.Mapping),
685 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000686 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000687
688 bool runOnFunction() {
689 if (!ClStack) return false;
690 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000691 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000692
Yury Gribov55441bb2014-11-21 10:29:50 +0000693 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000694
695 initializeCallbacks(*F.getParent());
696
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000697 processDynamicAllocas();
698 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000699
700 if (ClDebugStack) {
701 DEBUG(dbgs() << F);
702 }
703 return true;
704 }
705
Yury Gribov55441bb2014-11-21 10:29:50 +0000706 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000707 // poisoned red zones around all of them.
708 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000709 void processStaticAllocas();
710 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000711
Yury Gribov98b18592015-05-28 07:51:49 +0000712 void createDynamicAllocasInitStorage();
713
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000714 // ----------------------- Visitors.
715 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000716 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000717
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000718 /// \brief Collect all Resume instructions.
719 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
720
721 /// \brief Collect all CatchReturnInst instructions.
722 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
723
Yury Gribov98b18592015-05-28 07:51:49 +0000724 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
725 Value *SavedStack) {
726 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000727 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
728 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
729 // need to adjust extracted SP to compute the address of the most recent
730 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
731 // this purpose.
732 if (!isa<ReturnInst>(InstBefore)) {
733 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
734 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
735 {IntptrTy});
736
737 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
738
739 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
740 DynamicAreaOffset);
741 }
742
Yury Gribov781bce22015-05-28 08:03:28 +0000743 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000744 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000745 }
746
Yury Gribov55441bb2014-11-21 10:29:50 +0000747 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000748 void unpoisonDynamicAllocas() {
749 for (auto &Ret : RetVec)
750 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000751
Yury Gribov98b18592015-05-28 07:51:49 +0000752 for (auto &StackRestoreInst : StackRestoreVec)
753 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
754 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000755 }
756
Yury Gribov55441bb2014-11-21 10:29:50 +0000757 // Deploy and poison redzones around dynamic alloca call. To do this, we
758 // should replace this call with another one with changed parameters and
759 // replace all its uses with new address, so
760 // addr = alloca type, old_size, align
761 // is replaced by
762 // new_size = (old_size + additional_size) * sizeof(type)
763 // tmp = alloca i8, new_size, max(align, 32)
764 // addr = tmp + 32 (first 32 bytes are for the left redzone).
765 // Additional_size is added to make new memory allocation contain not only
766 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000767 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000768
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000769 /// \brief Collect Alloca instructions we want (and can) handle.
770 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000771 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000772 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000773 return;
774 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000775
776 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000777 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000778 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000779 else
780 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000781 }
782
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000783 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
784 /// errors.
785 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000786 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000787 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000788 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000789 if (!ASan.UseAfterScope)
790 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000791 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000792 return;
793 // Found lifetime intrinsic, add ASan instrumentation if necessary.
794 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
795 // If size argument is undefined, don't do anything.
796 if (Size->isMinusOne()) return;
797 // Check that size doesn't saturate uint64_t and can
798 // be stored in IntptrTy.
799 const uint64_t SizeValue = Size->getValue().getLimitedValue();
800 if (SizeValue == ~0ULL ||
801 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
802 return;
803 // Find alloca instruction that corresponds to llvm.lifetime argument.
804 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000805 if (!AI || !ASan.isInterestingAlloca(*AI))
806 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000807 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000808 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000809 if (AI->isStaticAlloca())
810 StaticAllocaPoisonCallVec.push_back(APC);
811 else if (ClInstrumentDynamicAllocas)
812 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000813 }
814
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000815 void visitCallSite(CallSite CS) {
816 Instruction *I = CS.getInstruction();
817 if (CallInst *CI = dyn_cast<CallInst>(I)) {
818 HasNonEmptyInlineAsm |=
819 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
820 HasReturnsTwiceCall |= CI->canReturnTwice();
821 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000822 }
823
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000824 // ---------------------- Helpers.
825 void initializeCallbacks(Module &M);
826
Yury Gribov3ae427d2014-12-01 08:47:58 +0000827 bool doesDominateAllExits(const Instruction *I) const {
828 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000829 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000830 }
831 return true;
832 }
833
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000834 /// Finds alloca where the value comes from.
835 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000836
837 // Copies bytes from ShadowBytes into shadow memory for indexes where
838 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
839 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
840 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
841 IRBuilder<> &IRB, Value *ShadowBase);
842 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
843 size_t Begin, size_t End, IRBuilder<> &IRB,
844 Value *ShadowBase);
845 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
846 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
847 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
848
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000849 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000850
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000851 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
852 bool Dynamic);
853 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
854 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000855};
856
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000857} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000858
859char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000860INITIALIZE_PASS_BEGIN(
861 AddressSanitizer, "asan",
862 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
863 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000864INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000865INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000866INITIALIZE_PASS_END(
867 AddressSanitizer, "asan",
868 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
869 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000870FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000871 bool Recover,
872 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000873 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000874 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000875}
876
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000877char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000878INITIALIZE_PASS(
879 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000880 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000881 "ModulePass",
882 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000883ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
884 bool Recover) {
885 assert(!CompileKernel || Recover);
886 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000887}
888
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000889static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000890 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000891 assert(Res < kNumberOfAccessSizes);
892 return Res;
893}
894
Bill Wendling58f8cef2013-08-06 22:52:42 +0000895// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000896static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
897 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000898 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000899 // We use private linkage for module-local strings. If they can be merged
900 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000901 GlobalVariable *GV =
902 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000903 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000904 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000905 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
906 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000907}
908
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000909/// \brief Create a global describing a source location.
910static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
911 LocationMetadata MD) {
912 Constant *LocData[] = {
913 createPrivateGlobalForString(M, MD.Filename, true),
914 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
915 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
916 };
917 auto LocStruct = ConstantStruct::getAnon(LocData);
918 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
919 GlobalValue::PrivateLinkage, LocStruct,
920 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000921 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000922 return GV;
923}
924
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000925/// \brief Check if \p G has been created by a trusted compiler pass.
926static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
927 // Do not instrument asan globals.
928 if (G->getName().startswith(kAsanGenPrefix) ||
929 G->getName().startswith(kSanCovGenPrefix) ||
930 G->getName().startswith(kODRGenPrefix))
931 return true;
932
933 // Do not instrument gcov counter arrays.
934 if (G->getName() == "__llvm_gcov_ctr")
935 return true;
936
937 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000938}
939
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000940Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
941 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000942 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000943 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000944 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000945 Value *ShadowBase;
946 if (LocalDynamicShadow)
947 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000948 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000949 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
950 if (Mapping.OrShadowOffset)
951 return IRB.CreateOr(Shadow, ShadowBase);
952 else
953 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000954}
955
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000956// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000957void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
958 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000959 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000960 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000961 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000962 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
963 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
964 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000965 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000966 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000967 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000968 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
969 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
970 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000971 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000972 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000973}
974
Anna Zaks8ed1d812015-02-27 03:12:36 +0000975/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000976bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000977 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
978
979 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
980 return PreviouslySeenAllocaInfo->getSecond();
981
Yury Gribov98b18592015-05-28 07:51:49 +0000982 bool IsInteresting =
983 (AI.getAllocatedType()->isSized() &&
984 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000985 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000986 // We are only interested in allocas not promotable to registers.
987 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000988 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
989 // inalloca allocas are not treated as static, and we don't want
990 // dynamic alloca instrumentation for them as well.
991 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000992
993 ProcessedAllocas[&AI] = IsInteresting;
994 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000995}
996
997/// If I is an interesting memory access, return the PointerOperand
998/// and set IsWrite/Alignment. Otherwise return nullptr.
999Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1000 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001001 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001002 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001003 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001004 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001005
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001006 // Do not instrument the load fetching the dynamic shadow address.
1007 if (LocalDynamicShadow == I)
1008 return nullptr;
1009
Anna Zaks8ed1d812015-02-27 03:12:36 +00001010 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001011 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001012 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001013 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001014 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001015 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001016 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001017 PtrOperand = LI->getPointerOperand();
1018 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001019 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001020 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001021 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001022 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001023 PtrOperand = SI->getPointerOperand();
1024 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001025 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001026 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001027 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001028 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001029 PtrOperand = RMW->getPointerOperand();
1030 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001031 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001032 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001033 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001034 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001035 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +00001036 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001037
Anna Zaks644d9d32016-06-22 00:15:52 +00001038 // Do not instrument acesses from different address spaces; we cannot deal
1039 // with them.
1040 if (PtrOperand) {
1041 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1042 if (PtrTy->getPointerAddressSpace() != 0)
1043 return nullptr;
1044 }
1045
Anna Zaks8ed1d812015-02-27 03:12:36 +00001046 // Treat memory accesses to promotable allocas as non-interesting since they
1047 // will not cause memory violations. This greatly speeds up the instrumented
1048 // executable at -O0.
1049 if (ClSkipPromotableAllocas)
1050 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1051 return isInterestingAlloca(*AI) ? AI : nullptr;
1052
1053 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001054}
1055
Kostya Serebryany796f6552014-02-27 12:45:36 +00001056static bool isPointerOperand(Value *V) {
1057 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1058}
1059
1060// This is a rough heuristic; it may cause both false positives and
1061// false negatives. The proper implementation requires cooperation with
1062// the frontend.
1063static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1064 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001065 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001066 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001067 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001068 } else {
1069 return false;
1070 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001071 return isPointerOperand(I->getOperand(0)) &&
1072 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001073}
1074
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001075bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1076 // If a global variable does not have dynamic initialization we don't
1077 // have to instrument it. However, if a global does not have initializer
1078 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001079 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001080}
1081
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001082void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1083 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001084 IRBuilder<> IRB(I);
1085 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1086 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001087 for (Value *&i : Param) {
1088 if (i->getType()->isPointerTy())
1089 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001090 }
David Blaikieff6409d2015-05-18 22:13:54 +00001091 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001092}
1093
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001094void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001095 Instruction *I, bool UseCalls,
1096 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001097 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001098 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001099 uint64_t TypeSize = 0;
1100 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001101 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001102
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001103 // Optimization experiments.
1104 // The experiments can be used to evaluate potential optimizations that remove
1105 // instrumentation (assess false negatives). Instead of completely removing
1106 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1107 // experiments that want to remove instrumentation of this instruction).
1108 // If Exp is non-zero, this pass will emit special calls into runtime
1109 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1110 // make runtime terminate the program in a special way (with a different
1111 // exit status). Then you run the new compiler on a buggy corpus, collect
1112 // the special terminations (ideally, you don't see them at all -- no false
1113 // negatives) and make the decision on the optimization.
1114 uint32_t Exp = ClForceExperiment;
1115
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001116 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001117 // If initialization order checking is disabled, a simple access to a
1118 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001119 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001120 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001121 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1122 NumOptimizedAccessesToGlobalVar++;
1123 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001125 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001126
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001127 if (ClOpt && ClOptStack) {
1128 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001129 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001130 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1131 NumOptimizedAccessesToStackVar++;
1132 return;
1133 }
1134 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001135
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001136 if (IsWrite)
1137 NumInstrumentedWrites++;
1138 else
1139 NumInstrumentedReads++;
1140
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001141 unsigned Granularity = 1 << Mapping.Scale;
1142 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1143 // if the data is properly aligned.
1144 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1145 TypeSize == 128) &&
1146 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001147 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1148 Exp);
1149 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1150 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001151}
1152
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001153Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1154 Value *Addr, bool IsWrite,
1155 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001156 Value *SizeArgument,
1157 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001158 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001159 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1160 CallInst *Call = nullptr;
1161 if (SizeArgument) {
1162 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001163 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1164 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001165 else
David Blaikieff6409d2015-05-18 22:13:54 +00001166 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1167 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001168 } else {
1169 if (Exp == 0)
1170 Call =
1171 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1172 else
David Blaikieff6409d2015-05-18 22:13:54 +00001173 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1174 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001175 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001176
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001177 // We don't do Call->setDoesNotReturn() because the BB already has
1178 // UnreachableInst at the end.
1179 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001180 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001181 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001182}
1183
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001184Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001185 Value *ShadowValue,
1186 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001187 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001188 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001189 Value *LastAccessedByte =
1190 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001191 // (Addr & (Granularity - 1)) + size - 1
1192 if (TypeSize / 8 > 1)
1193 LastAccessedByte = IRB.CreateAdd(
1194 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1195 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001196 LastAccessedByte =
1197 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001198 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1199 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1200}
1201
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001202void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001203 Instruction *InsertBefore, Value *Addr,
1204 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001205 Value *SizeArgument, bool UseCalls,
1206 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001207 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001208 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001209 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1210
1211 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001212 if (Exp == 0)
1213 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1214 AddrLong);
1215 else
David Blaikieff6409d2015-05-18 22:13:54 +00001216 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1217 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001218 return;
1219 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001221 Type *ShadowTy =
1222 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001223 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1224 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1225 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001226 Value *ShadowValue =
1227 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001228
1229 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001230 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001231 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001232
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001233 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001234 // We use branch weights for the slow path check, to indicate that the slow
1235 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001236 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1237 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001238 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001239 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001240 IRB.SetInsertPoint(CheckTerm);
1241 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001242 if (Recover) {
1243 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1244 } else {
1245 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001246 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001247 CrashTerm = new UnreachableInst(*C, CrashBlock);
1248 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1249 ReplaceInstWithInst(CheckTerm, NewTerm);
1250 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001251 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001252 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001253 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001254
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001255 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001256 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001257 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001258}
1259
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001260// Instrument unusual size or unusual alignment.
1261// We can not do it with a single check, so we do 1-byte check for the first
1262// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1263// to report the actual access size.
1264void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1265 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1266 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1267 IRBuilder<> IRB(I);
1268 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1269 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1270 if (UseCalls) {
1271 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001272 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1273 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001274 else
David Blaikieff6409d2015-05-18 22:13:54 +00001275 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1276 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001277 } else {
1278 Value *LastByte = IRB.CreateIntToPtr(
1279 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1280 Addr->getType());
1281 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1282 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1283 }
1284}
1285
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001286void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1287 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001288 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001289 IRBuilder<> IRB(&GlobalInit.front(),
1290 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001291
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001292 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001293 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1294 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001295
1296 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001297 for (auto &BB : GlobalInit.getBasicBlockList())
1298 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001299 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001300}
1301
1302void AddressSanitizerModule::createInitializerPoisonCalls(
1303 Module &M, GlobalValue *ModuleName) {
1304 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1305
1306 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1307 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001308 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001309 ConstantStruct *CS = cast<ConstantStruct>(OP);
1310
1311 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001312 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001313 if (F->getName() == kAsanModuleCtorName) continue;
1314 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1315 // Don't instrument CTORs that will run before asan.module_ctor.
1316 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1317 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001318 }
1319 }
1320}
1321
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001322bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001323 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001324 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001325
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001326 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001327 if (!Ty->isSized()) return false;
1328 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001329 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001330 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001331 // Don't handle ODR linkage types and COMDATs since other modules may be built
1332 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001333 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1334 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1335 G->getLinkage() != GlobalVariable::InternalLinkage)
1336 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001337 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001338 // Two problems with thread-locals:
1339 // - The address of the main thread's copy can't be computed at link-time.
1340 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001341 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001342 // For now, just ignore this Global if the alignment is large.
1343 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001344
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001345 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001346 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001347
Anna Zaks11904602015-06-09 00:58:08 +00001348 // Globals from llvm.metadata aren't emitted, do not instrument them.
1349 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001350 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001351 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001352
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001353 // Do not instrument function pointers to initialization and termination
1354 // routines: dynamic linker will not properly handle redzones.
1355 if (Section.startswith(".preinit_array") ||
1356 Section.startswith(".init_array") ||
1357 Section.startswith(".fini_array")) {
1358 return false;
1359 }
1360
Anna Zaks11904602015-06-09 00:58:08 +00001361 // Callbacks put into the CRT initializer/terminator sections
1362 // should not be instrumented.
1363 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1364 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1365 if (Section.startswith(".CRT")) {
1366 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1367 return false;
1368 }
1369
Kuba Brecka1001bb52014-12-05 22:19:18 +00001370 if (TargetTriple.isOSBinFormatMachO()) {
1371 StringRef ParsedSegment, ParsedSection;
1372 unsigned TAA = 0, StubSize = 0;
1373 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001374 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1375 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001376 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001377
1378 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1379 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1380 // them.
1381 if (ParsedSegment == "__OBJC" ||
1382 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1383 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1384 return false;
1385 }
1386 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1387 // Constant CFString instances are compiled in the following way:
1388 // -- the string buffer is emitted into
1389 // __TEXT,__cstring,cstring_literals
1390 // -- the constant NSConstantString structure referencing that buffer
1391 // is placed into __DATA,__cfstring
1392 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1393 // Moreover, it causes the linker to crash on OS X 10.7
1394 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1395 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1396 return false;
1397 }
1398 // The linker merges the contents of cstring_literals and removes the
1399 // trailing zeroes.
1400 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1401 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1402 return false;
1403 }
1404 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001405 }
1406
1407 return true;
1408}
1409
Ryan Govostes653f9d02016-03-28 20:28:57 +00001410// On Mach-O platforms, we emit global metadata in a separate section of the
1411// binary in order to allow the linker to properly dead strip. This is only
1412// supported on recent versions of ld64.
1413bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001414 if (!ClUseMachOGlobalsSection)
1415 return false;
1416
Ryan Govostes653f9d02016-03-28 20:28:57 +00001417 if (!TargetTriple.isOSBinFormatMachO())
1418 return false;
1419
1420 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1421 return true;
1422 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001423 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001424 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1425 return true;
1426
1427 return false;
1428}
1429
Alexey Samsonov788381b2012-12-25 12:28:20 +00001430void AddressSanitizerModule::initializeCallbacks(Module &M) {
1431 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001432
Alexey Samsonov788381b2012-12-25 12:28:20 +00001433 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001434 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001435 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001436 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001437 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001438 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001439 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001440
Alexey Samsonov788381b2012-12-25 12:28:20 +00001441 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001442 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001443 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001444 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001445 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001446 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1447 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001448 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001449
1450 // Declare the functions that find globals in a shared object and then invoke
1451 // the (un)register function on them.
1452 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1453 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1454 IRB.getVoidTy(), IntptrTy, nullptr));
1455 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001456
Ryan Govostes653f9d02016-03-28 20:28:57 +00001457 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1458 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1459 IRB.getVoidTy(), IntptrTy, nullptr));
1460 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001461}
1462
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001463// This function replaces all global variables with new variables that have
1464// trailing redzones. It also creates a function that poisons
1465// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001466bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001467 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001468
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1470
Alexey Samsonova02e6642014-05-29 18:40:48 +00001471 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001472 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001473 }
1474
1475 size_t n = GlobalsToChange.size();
1476 if (n == 0) return false;
1477
1478 // A global is described by a structure
1479 // size_t beg;
1480 // size_t size;
1481 // size_t size_with_redzone;
1482 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001483 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001484 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001485 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001486 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001487 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001488 StructType *GlobalStructTy =
1489 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001490 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001491 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001492
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001493 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001494
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001495 // We shouldn't merge same module names, as this string serves as unique
1496 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001497 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001498 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001499
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001500 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001501 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001502 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001503 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001504
1505 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001506 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001507 // Create string holding the global name (use global name from metadata
1508 // if it's available, otherwise just write the name of global variable).
1509 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001510 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001511 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001512
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001513 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001514 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001515 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001516 // MinRZ <= RZ <= kMaxGlobalRedzone
1517 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001518 uint64_t RZ = std::max(
1519 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001520 uint64_t RightRedzoneSize = RZ;
1521 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001522 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001523 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001524 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1525
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001526 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001527 Constant *NewInitializer =
1528 ConstantStruct::get(NewTy, G->getInitializer(),
1529 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001531 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001532 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1533 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1534 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001535 GlobalVariable *NewGlobal =
1536 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1537 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001538 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001539 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001540
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001541 // Transfer the debug info. The payload starts at offset zero so we can
1542 // copy the debug info over as is.
1543 SmallVector<DIGlobalVariable *, 1> GVs;
1544 G->getDebugInfo(GVs);
1545 for (auto *GV : GVs)
1546 NewGlobal->addDebugInfo(GV);
1547
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001548 Value *Indices2[2];
1549 Indices2[0] = IRB.getInt32(0);
1550 Indices2[1] = IRB.getInt32(0);
1551
1552 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001553 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001554 NewGlobal->takeName(G);
1555 G->eraseFromParent();
1556
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001557 Constant *SourceLoc;
1558 if (!MD.SourceLoc.empty()) {
1559 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1560 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1561 } else {
1562 SourceLoc = ConstantInt::get(IntptrTy, 0);
1563 }
1564
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001565 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1566 GlobalValue *InstrumentedGlobal = NewGlobal;
1567
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001568 bool CanUsePrivateAliases =
1569 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001570 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1571 // Create local alias for NewGlobal to avoid crash on ODR between
1572 // instrumented and non-instrumented libraries.
1573 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1574 NameForGlobal + M.getName(), NewGlobal);
1575
1576 // With local aliases, we need to provide another externally visible
1577 // symbol __odr_asan_XXX to detect ODR violation.
1578 auto *ODRIndicatorSym =
1579 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1580 Constant::getNullValue(IRB.getInt8Ty()),
1581 kODRGenPrefix + NameForGlobal, nullptr,
1582 NewGlobal->getThreadLocalMode());
1583
1584 // Set meaningful attributes for indicator symbol.
1585 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1586 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1587 ODRIndicatorSym->setAlignment(1);
1588 ODRIndicator = ODRIndicatorSym;
1589 InstrumentedGlobal = GA;
1590 }
1591
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001592 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001593 GlobalStructTy,
1594 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001595 ConstantInt::get(IntptrTy, SizeInBytes),
1596 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1597 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001598 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001599 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1600 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001601
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001602 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001603
Kostya Serebryany20343352012-10-17 13:40:06 +00001604 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001605 }
1606
Ryan Govostes653f9d02016-03-28 20:28:57 +00001607
1608 GlobalVariable *AllGlobals = nullptr;
1609 GlobalVariable *RegisteredFlag = nullptr;
1610
1611 // On recent Mach-O platforms, we emit the global metadata in a way that
1612 // allows the linker to properly strip dead globals.
1613 if (ShouldUseMachOGlobalsSection()) {
1614 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1615 // to look up the loaded image that contains it. Second, we can store in it
1616 // whether registration has already occurred, to prevent duplicate
1617 // registration.
1618 //
1619 // Common linkage allows us to coalesce needles defined in each object
1620 // file so that there's only one per shared library.
1621 RegisteredFlag = new GlobalVariable(
1622 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1623 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1624
1625 // We also emit a structure which binds the liveness of the global
1626 // variable to the metadata struct.
1627 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1628
1629 for (size_t i = 0; i < n; i++) {
1630 GlobalVariable *Metadata = new GlobalVariable(
1631 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1632 Initializers[i], "");
1633 Metadata->setSection("__DATA,__asan_globals,regular");
1634 Metadata->setAlignment(1); // don't leave padding in between
1635
1636 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1637 Initializers[i]->getAggregateElement(0u),
1638 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1639 nullptr);
1640 GlobalVariable *Liveness = new GlobalVariable(
1641 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1642 LivenessBinder, "");
1643 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1644 }
1645 } else {
1646 // On all other platfoms, we just emit an array of global metadata
1647 // structures.
1648 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1649 AllGlobals = new GlobalVariable(
1650 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1651 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1652 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001653
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001654 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001655 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001656 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001657
Ryan Govostes653f9d02016-03-28 20:28:57 +00001658 // Create a call to register the globals with the runtime.
1659 if (ShouldUseMachOGlobalsSection()) {
1660 IRB.CreateCall(AsanRegisterImageGlobals,
1661 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1662 } else {
1663 IRB.CreateCall(AsanRegisterGlobals,
1664 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1665 ConstantInt::get(IntptrTy, n)});
1666 }
1667
1668 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001669 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001670 Function *AsanDtorFunction =
1671 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1672 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001673 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1674 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001675
1676 if (ShouldUseMachOGlobalsSection()) {
1677 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1678 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1679 } else {
1680 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1681 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1682 ConstantInt::get(IntptrTy, n)});
1683 }
1684
Alexey Samsonov1f647502014-05-29 01:10:14 +00001685 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001686
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001687 DEBUG(dbgs() << M);
1688 return true;
1689}
1690
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001691bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001692 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001693 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001694 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001695 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001696 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001697 initializeCallbacks(M);
1698
1699 bool Changed = false;
1700
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001701 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1702 if (ClGlobals && !CompileKernel) {
1703 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1704 assert(CtorFunc);
1705 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1706 Changed |= InstrumentGlobals(IRB, M);
1707 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001708
1709 return Changed;
1710}
1711
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001712void AddressSanitizer::initializeCallbacks(Module &M) {
1713 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001714 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001715 // IsWrite, TypeSize and Exp are encoded in the function name.
1716 for (int Exp = 0; Exp < 2; Exp++) {
1717 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1718 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1719 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001720 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001721 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001722 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001723 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001724 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001725 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001726 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1727 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001728 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001729 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001730 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1731 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1732 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001733 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001734 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001735 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001736 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001737 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001738 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001739 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001740 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1741 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001742 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001743 }
1744 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001745
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001746 const std::string MemIntrinCallbackPrefix =
1747 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001748 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001749 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001750 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001751 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001752 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001753 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001754 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001755 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001756 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001757
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001758 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001759 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001760
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001761 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001762 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001763 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001764 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001765 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1766 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1767 StringRef(""), StringRef(""),
1768 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001769}
1770
1771// virtual
1772bool AddressSanitizer::doInitialization(Module &M) {
1773 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001774
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001775 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001776
1777 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001778 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001779 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001780 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001781
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001782 if (!CompileKernel) {
1783 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001784 createSanitizerCtorAndInitFunctions(
1785 M, kAsanModuleCtorName, kAsanInitName,
1786 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001787 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1788 }
1789 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001790 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001791}
1792
Keno Fischere03fae42015-12-05 14:42:34 +00001793bool AddressSanitizer::doFinalization(Module &M) {
1794 GlobalsMD.reset();
1795 return false;
1796}
1797
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001798bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1799 // For each NSObject descendant having a +load method, this method is invoked
1800 // by the ObjC runtime before any of the static constructors is called.
1801 // Therefore we need to instrument such methods with a call to __asan_init
1802 // at the beginning in order to initialize our runtime before any access to
1803 // the shadow memory.
1804 // We cannot just ignore these methods, because they may call other
1805 // instrumented functions.
1806 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001807 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001808 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001809 return true;
1810 }
1811 return false;
1812}
1813
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001814void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
1815 // Generate code only when dynamic addressing is needed.
1816 if (Mapping.Offset != kDynamicShadowSentinel)
1817 return;
1818
1819 IRBuilder<> IRB(&F.front().front());
1820 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
1821 kAsanShadowMemoryDynamicAddress, IntptrTy);
1822 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
1823}
1824
Reid Kleckner2f907552015-07-21 17:40:14 +00001825void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1826 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1827 // to it as uninteresting. This assumes we haven't started processing allocas
1828 // yet. This check is done up front because iterating the use list in
1829 // isInterestingAlloca would be algorithmically slower.
1830 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1831
1832 // Try to get the declaration of llvm.localescape. If it's not in the module,
1833 // we can exit early.
1834 if (!F.getParent()->getFunction("llvm.localescape")) return;
1835
1836 // Look for a call to llvm.localescape call in the entry block. It can't be in
1837 // any other block.
1838 for (Instruction &I : F.getEntryBlock()) {
1839 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1840 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1841 // We found a call. Mark all the allocas passed in as uninteresting.
1842 for (Value *Arg : II->arg_operands()) {
1843 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1844 assert(AI && AI->isStaticAlloca() &&
1845 "non-static alloca arg to localescape");
1846 ProcessedAllocas[AI] = false;
1847 }
1848 break;
1849 }
1850 }
1851}
1852
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001853bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001854 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001855 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001856 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00001857 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001858
Etienne Bergeron78582b22016-09-15 15:45:05 +00001859 bool FunctionModified = false;
1860
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001861 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00001862 // This function needs to be called even if the function body is not
1863 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001864 if (maybeInsertAsanInitAtFunctionEntry(F))
1865 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00001866
1867 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00001868 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001869
Etienne Bergeron752f8832016-09-14 17:18:37 +00001870 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
1871
1872 initializeCallbacks(*F.getParent());
1873 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001874
Reid Kleckner2f907552015-07-21 17:40:14 +00001875 FunctionStateRAII CleanupObj(this);
1876
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001877 maybeInsertDynamicShadowAtFunctionEntry(F);
1878
Reid Kleckner2f907552015-07-21 17:40:14 +00001879 // We can't instrument allocas used with llvm.localescape. Only static allocas
1880 // can be passed to that intrinsic.
1881 markEscapedLocalAllocas(F);
1882
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001883 // We want to instrument every address only once per basic block (unless there
1884 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001885 SmallSet<Value *, 16> TempsToInstrument;
1886 SmallVector<Instruction *, 16> ToInstrument;
1887 SmallVector<Instruction *, 8> NoReturnCalls;
1888 SmallVector<BasicBlock *, 16> AllBlocks;
1889 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001890 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001891 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001892 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001893 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001894 const TargetLibraryInfo *TLI =
1895 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001896
1897 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001898 for (auto &BB : F) {
1899 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001900 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001901 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001902 for (auto &Inst : BB) {
1903 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001904 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1905 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001906 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001907 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001908 continue; // We've seen this temp in the current BB.
1909 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001910 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001911 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1912 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001913 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001914 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001915 // ok, take it.
1916 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001917 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001918 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001919 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001920 // A call inside BB.
1921 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001922 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001923 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001924 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1925 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001926 continue;
1927 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001928 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001929 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001930 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001931 }
1932 }
1933
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001934 bool UseCalls =
1935 CompileKernel ||
1936 (ClInstrumentationWithCallsThreshold >= 0 &&
1937 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001938 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001939 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1940 /*RoundToAlign=*/true);
1941
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001942 // Instrument.
1943 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001944 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001945 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1946 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001947 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001948 instrumentMop(ObjSizeVis, Inst, UseCalls,
1949 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001950 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001951 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001952 }
1953 NumInstrumented++;
1954 }
1955
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001956 FunctionStackPoisoner FSP(F, *this);
1957 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001958
1959 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1960 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001961 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001962 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001963 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001964 }
1965
Alexey Samsonova02e6642014-05-29 18:40:48 +00001966 for (auto Inst : PointerComparisonsOrSubtracts) {
1967 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001968 NumInstrumented++;
1969 }
1970
Etienne Bergeron78582b22016-09-15 15:45:05 +00001971 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
1972 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00001973
Etienne Bergeron78582b22016-09-15 15:45:05 +00001974 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
1975 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001976
Etienne Bergeron78582b22016-09-15 15:45:05 +00001977 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001978}
1979
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001980// Workaround for bug 11395: we don't want to instrument stack in functions
1981// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1982// FIXME: remove once the bug 11395 is fixed.
1983bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1984 if (LongSize != 32) return false;
1985 CallInst *CI = dyn_cast<CallInst>(I);
1986 if (!CI || !CI->isInlineAsm()) return false;
1987 if (CI->getNumArgOperands() <= 5) return false;
1988 // We have inline assembly with quite a few arguments.
1989 return true;
1990}
1991
1992void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1993 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001994 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1995 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001996 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1997 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1998 IntptrTy, nullptr));
1999 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002000 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2001 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002002 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002003 if (ASan.UseAfterScope) {
2004 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2005 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2006 IntptrTy, IntptrTy, nullptr));
2007 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2008 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2009 IntptrTy, IntptrTy, nullptr));
2010 }
2011
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002012 if (ClExperimentalPoisoning) {
2013 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2014 std::ostringstream Name;
2015 Name << kAsanSetShadowPrefix;
2016 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2017 AsanSetShadowFunc[Val] =
2018 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2019 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2020 }
2021 }
2022
Yury Gribov98b18592015-05-28 07:51:49 +00002023 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2024 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2025 AsanAllocasUnpoisonFunc =
2026 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2027 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002028}
2029
Vitaly Buka793913c2016-08-29 18:17:21 +00002030void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2031 ArrayRef<uint8_t> ShadowBytes,
2032 size_t Begin, size_t End,
2033 IRBuilder<> &IRB,
2034 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002035 if (Begin >= End)
2036 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002037
2038 const size_t LargestStoreSizeInBytes =
2039 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2040
2041 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2042
2043 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002044 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2045 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2046 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002047 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002048 if (!ShadowMask[i]) {
2049 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002050 ++i;
2051 continue;
2052 }
2053
2054 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2055 // Fit store size into the range.
2056 while (StoreSizeInBytes > End - i)
2057 StoreSizeInBytes /= 2;
2058
2059 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002060 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002061 while (j <= StoreSizeInBytes / 2)
2062 StoreSizeInBytes /= 2;
2063 }
2064
2065 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002066 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2067 if (IsLittleEndian)
2068 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2069 else
2070 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002071 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002072
2073 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2074 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002075 IRB.CreateAlignedStore(
2076 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002077
2078 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002079 }
2080}
2081
Vitaly Buka793913c2016-08-29 18:17:21 +00002082void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2083 ArrayRef<uint8_t> ShadowBytes,
2084 IRBuilder<> &IRB, Value *ShadowBase) {
2085 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2086}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002087
Vitaly Buka793913c2016-08-29 18:17:21 +00002088void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2089 ArrayRef<uint8_t> ShadowBytes,
2090 size_t Begin, size_t End,
2091 IRBuilder<> &IRB, Value *ShadowBase) {
2092 assert(ShadowMask.size() == ShadowBytes.size());
2093 size_t Done = Begin;
2094 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2095 if (!ShadowMask[i]) {
2096 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002097 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002098 }
2099 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002100 if (!AsanSetShadowFunc[Val])
2101 continue;
2102
2103 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002104 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002105 }
2106
2107 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002108 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002109 IRB.CreateCall(AsanSetShadowFunc[Val],
2110 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2111 ConstantInt::get(IntptrTy, j - i)});
2112 Done = j;
2113 }
2114 }
2115
Vitaly Buka793913c2016-08-29 18:17:21 +00002116 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002117}
2118
Kostya Serebryany6805de52013-09-10 13:16:56 +00002119// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2120// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2121static int StackMallocSizeClass(uint64_t LocalStackSize) {
2122 assert(LocalStackSize <= kMaxStackMallocSize);
2123 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002124 for (int i = 0;; i++, MaxSize *= 2)
2125 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002126 llvm_unreachable("impossible LocalStackSize");
2127}
2128
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002129PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2130 Value *ValueIfTrue,
2131 Instruction *ThenTerm,
2132 Value *ValueIfFalse) {
2133 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2134 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2135 PHI->addIncoming(ValueIfFalse, CondBlock);
2136 BasicBlock *ThenBlock = ThenTerm->getParent();
2137 PHI->addIncoming(ValueIfTrue, ThenBlock);
2138 return PHI;
2139}
2140
2141Value *FunctionStackPoisoner::createAllocaForLayout(
2142 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2143 AllocaInst *Alloca;
2144 if (Dynamic) {
2145 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2146 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2147 "MyAlloca");
2148 } else {
2149 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2150 nullptr, "MyAlloca");
2151 assert(Alloca->isStaticAlloca());
2152 }
2153 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2154 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2155 Alloca->setAlignment(FrameAlignment);
2156 return IRB.CreatePointerCast(Alloca, IntptrTy);
2157}
2158
Yury Gribov98b18592015-05-28 07:51:49 +00002159void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2160 BasicBlock &FirstBB = *F.begin();
2161 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2162 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2163 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2164 DynamicAllocaLayout->setAlignment(32);
2165}
2166
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002167void FunctionStackPoisoner::processDynamicAllocas() {
2168 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2169 assert(DynamicAllocaPoisonCallVec.empty());
2170 return;
2171 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002172
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002173 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2174 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002175 assert(APC.InsBefore);
2176 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002177 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002178 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002179
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002180 IRBuilder<> IRB(APC.InsBefore);
2181 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002182 // Dynamic allocas will be unpoisoned unconditionally below in
2183 // unpoisonDynamicAllocas.
2184 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002185 }
2186
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002187 // Handle dynamic allocas.
2188 createDynamicAllocasInitStorage();
2189 for (auto &AI : DynamicAllocaVec)
2190 handleDynamicAllocaCall(AI);
2191 unpoisonDynamicAllocas();
2192}
Yury Gribov98b18592015-05-28 07:51:49 +00002193
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002194void FunctionStackPoisoner::processStaticAllocas() {
2195 if (AllocaVec.empty()) {
2196 assert(StaticAllocaPoisonCallVec.empty());
2197 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002198 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002199
Kostya Serebryany6805de52013-09-10 13:16:56 +00002200 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002201 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002202 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002203 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002204
2205 Instruction *InsBefore = AllocaVec[0];
2206 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002207 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002208
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002209 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2210 // debug info is broken, because only entry-block allocas are treated as
2211 // regular stack slots.
2212 auto InsBeforeB = InsBefore->getParent();
2213 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002214 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2215 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002216 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2217 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002218
Reid Kleckner2f907552015-07-21 17:40:14 +00002219 // If we have a call to llvm.localescape, keep it in the entry block.
2220 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2221
Vitaly Buka793913c2016-08-29 18:17:21 +00002222 // Find static allocas with lifetime analysis.
2223 DenseMap<const AllocaInst *, const ASanStackVariableDescription *>
2224 AllocaToSVDMap;
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002225 for (const auto &APC : StaticAllocaPoisonCallVec) {
2226 assert(APC.InsBefore);
2227 assert(APC.AI);
2228 assert(ASan.isInterestingAlloca(*APC.AI));
2229 assert(APC.AI->isStaticAlloca());
2230
Vitaly Buka793913c2016-08-29 18:17:21 +00002231 if (ClExperimentalPoisoning) {
2232 AllocaToSVDMap[APC.AI] = nullptr;
2233 } else {
2234 IRBuilder<> IRB(APC.InsBefore);
2235 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2236 }
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002237 }
2238
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002239 SmallVector<ASanStackVariableDescription, 16> SVD;
2240 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002241 for (AllocaInst *AI : AllocaVec) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002242 size_t UseAfterScopePoisonSize =
2243 AllocaToSVDMap.find(AI) != AllocaToSVDMap.end()
2244 ? ASan.getAllocaSizeInBytes(*AI)
2245 : 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002246 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002247 ASan.getAllocaSizeInBytes(*AI),
Vitaly Buka793913c2016-08-29 18:17:21 +00002248 UseAfterScopePoisonSize,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002249 AI->getAlignment(),
2250 AI,
2251 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002252 SVD.push_back(D);
2253 }
2254 // Minimal header size (left redzone) is 4 pointers,
2255 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2256 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002257 const ASanStackFrameLayout &L =
2258 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002259
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002260 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2261 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002262 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2263 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002264 bool DoDynamicAlloca = ClDynamicAllocaStack;
2265 // Don't do dynamic alloca or stack malloc if:
2266 // 1) There is inline asm: too often it makes assumptions on which registers
2267 // are available.
2268 // 2) There is a returns_twice call (typically setjmp), which is
2269 // optimization-hostile, and doesn't play well with introduced indirect
2270 // register-relative calculation of local variable addresses.
2271 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2272 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002273
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002274 Value *StaticAlloca =
2275 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2276
2277 Value *FakeStack;
2278 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002279
2280 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002281 // void *FakeStack = __asan_option_detect_stack_use_after_return
2282 // ? __asan_stack_malloc_N(LocalStackSize)
2283 // : nullptr;
2284 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002285 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2286 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2287 Value *UseAfterReturnIsEnabled =
2288 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002289 Constant::getNullValue(IRB.getInt32Ty()));
2290 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002291 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002292 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002293 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002294 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2295 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2296 Value *FakeStackValue =
2297 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2298 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002299 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002300 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002301 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002302 ConstantInt::get(IntptrTy, 0));
2303
2304 Value *NoFakeStack =
2305 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2306 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2307 IRBIf.SetInsertPoint(Term);
2308 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2309 Value *AllocaValue =
2310 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2311 IRB.SetInsertPoint(InsBefore);
2312 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2313 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2314 } else {
2315 // void *FakeStack = nullptr;
2316 // void *LocalStackBase = alloca(LocalStackSize);
2317 FakeStack = ConstantInt::get(IntptrTy, 0);
2318 LocalStackBase =
2319 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002320 }
2321
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002322 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002323 for (const auto &Desc : SVD) {
2324 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002325 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002326 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002327 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002328 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002329 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002330 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002331
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002332 // The left-most redzone has enough space for at least 4 pointers.
2333 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002334 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2335 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2336 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002337 // Write the frame description constant to redzone[1].
2338 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002339 IRB.CreateAdd(LocalStackBase,
2340 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2341 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002342 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002343 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002344 /*AllowMerging*/ true);
2345 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002346 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002347 // Write the PC to redzone[2].
2348 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002349 IRB.CreateAdd(LocalStackBase,
2350 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2351 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002352 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002353
Vitaly Buka793913c2016-08-29 18:17:21 +00002354 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2355
2356 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002357 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002358 // As mask we must use most poisoned case: red zones and after scope.
2359 // As bytes we can use either the same or just red zones only.
2360 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2361
2362 if (ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
2363 // Complete AllocaToSVDMap
2364 for (const auto &Desc : SVD) {
2365 auto It = AllocaToSVDMap.find(Desc.AI);
2366 if (It != AllocaToSVDMap.end()) {
2367 It->second = &Desc;
2368 }
2369 }
2370
2371 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2372
2373 // Poison static allocas near lifetime intrinsics.
2374 for (const auto &APC : StaticAllocaPoisonCallVec) {
2375 // Must be already set.
2376 assert(AllocaToSVDMap[APC.AI]);
2377 const auto &Desc = *AllocaToSVDMap[APC.AI];
2378 assert(Desc.Offset % L.Granularity == 0);
2379 size_t Begin = Desc.Offset / L.Granularity;
2380 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2381
2382 IRBuilder<> IRB(APC.InsBefore);
2383 copyToShadow(ShadowAfterScope,
2384 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2385 IRB, ShadowBase);
2386 }
2387 }
2388
2389 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002390
Vitaly Buka79b75d32016-06-09 23:05:35 +00002391 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002392 // Do this always as poisonAlloca can be disabled with
2393 // detect_stack_use_after_scope=0.
Vitaly Buka793913c2016-08-29 18:17:21 +00002394 copyToShadow(ShadowAfterScope, ShadowClean, IRB, ShadowBase);
2395 if (!ClExperimentalPoisoning && !StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002396 // If we poisoned some allocas in llvm.lifetime analysis,
2397 // unpoison whole stack frame now.
2398 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002399 }
2400 };
2401
Vitaly Buka793913c2016-08-29 18:17:21 +00002402 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002403
Kostya Serebryany530e2072013-12-23 14:15:08 +00002404 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002405 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002406 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002407 // Mark the current frame as retired.
2408 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2409 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002410 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002411 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002412 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002413 // // In use-after-return mode, poison the whole stack frame.
2414 // if StackMallocIdx <= 4
2415 // // For small sizes inline the whole thing:
2416 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002417 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002418 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002419 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002420 // else
2421 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002422 Value *Cmp =
2423 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002424 TerminatorInst *ThenTerm, *ElseTerm;
2425 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2426
2427 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002428 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002429 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002430 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2431 kAsanStackUseAfterReturnMagic);
2432 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2433 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002434 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002435 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002436 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2437 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2438 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2439 IRBPoison.CreateStore(
2440 Constant::getNullValue(IRBPoison.getInt8Ty()),
2441 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2442 } else {
2443 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002444 IRBPoison.CreateCall(
2445 AsanStackFreeFunc[StackMallocIdx],
2446 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002447 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002448
2449 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002450 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002451 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002452 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002453 }
2454 }
2455
Kostya Serebryany09959942012-10-19 06:20:53 +00002456 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002457 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002458}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002459
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002460void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002461 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002462 // For now just insert the call to ASan runtime.
2463 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2464 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002465 IRB.CreateCall(
2466 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2467 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002468}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002469
2470// Handling llvm.lifetime intrinsics for a given %alloca:
2471// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2472// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2473// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2474// could be poisoned by previous llvm.lifetime.end instruction, as the
2475// variable may go in and out of scope several times, e.g. in loops).
2476// (3) if we poisoned at least one %alloca in a function,
2477// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002478
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002479AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2480 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002481 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002482 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002483 // See if we've already calculated (or started to calculate) alloca for a
2484 // given value.
2485 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002486 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002487 // Store 0 while we're calculating alloca for value V to avoid
2488 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002489 AllocaForValue[V] = nullptr;
2490 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002491 if (CastInst *CI = dyn_cast<CastInst>(V))
2492 Res = findAllocaForValue(CI->getOperand(0));
2493 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002494 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002495 // Allow self-referencing phi-nodes.
2496 if (IncValue == PN) continue;
2497 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2498 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002499 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2500 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002501 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002502 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002503 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2504 Res = findAllocaForValue(EP->getPointerOperand());
2505 } else {
2506 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002507 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002508 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002509 return Res;
2510}
Yury Gribov55441bb2014-11-21 10:29:50 +00002511
Yury Gribov98b18592015-05-28 07:51:49 +00002512void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002513 IRBuilder<> IRB(AI);
2514
Yury Gribov55441bb2014-11-21 10:29:50 +00002515 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2516 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2517
2518 Value *Zero = Constant::getNullValue(IntptrTy);
2519 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2520 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002521
2522 // Since we need to extend alloca with additional memory to locate
2523 // redzones, and OldSize is number of allocated blocks with
2524 // ElementSize size, get allocated memory size in bytes by
2525 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002526 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002527 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002528 Value *OldSize =
2529 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2530 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002531
2532 // PartialSize = OldSize % 32
2533 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2534
2535 // Misalign = kAllocaRzSize - PartialSize;
2536 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2537
2538 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2539 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2540 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2541
2542 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2543 // Align is added to locate left redzone, PartialPadding for possible
2544 // partial redzone and kAllocaRzSize for right redzone respectively.
2545 Value *AdditionalChunkSize = IRB.CreateAdd(
2546 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2547
2548 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2549
2550 // Insert new alloca with new NewSize and Align params.
2551 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2552 NewAlloca->setAlignment(Align);
2553
2554 // NewAddress = Address + Align
2555 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2556 ConstantInt::get(IntptrTy, Align));
2557
Yury Gribov98b18592015-05-28 07:51:49 +00002558 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002559 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002560
2561 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2562 // for unpoisoning stuff.
2563 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2564
Yury Gribov55441bb2014-11-21 10:29:50 +00002565 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2566
Yury Gribov98b18592015-05-28 07:51:49 +00002567 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002568 AI->replaceAllUsesWith(NewAddressPtr);
2569
Yury Gribov98b18592015-05-28 07:51:49 +00002570 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002571 AI->eraseFromParent();
2572}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002573
2574// isSafeAccess returns true if Addr is always inbounds with respect to its
2575// base object. For example, it is a field access or an array access with
2576// constant inbounds index.
2577bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2578 Value *Addr, uint64_t TypeSize) const {
2579 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2580 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002581 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002582 int64_t Offset = SizeOffset.second.getSExtValue();
2583 // Three checks are required to ensure safety:
2584 // . Offset >= 0 (since the offset is given from the base ptr)
2585 // . Size >= Offset (unsigned)
2586 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002587 return Offset >= 0 && Size >= uint64_t(Offset) &&
2588 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002589}