blob: b4c0942b32411a75c340e9684d04db846d88e3a1 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000072static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000074static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000075static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000076static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000077static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000078static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000079static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000080static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000081static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +000083static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
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 =
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +0000124 "__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));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000191// This flag may need to be replaced with -f[no]asan-globals.
192static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000193 cl::desc("Handle global objects"), cl::Hidden,
194 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000195static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196 cl::desc("Handle C++ initializer order"),
197 cl::Hidden, cl::init(true));
198static cl::opt<bool> ClInvalidPointerPairs(
199 "asan-detect-invalid-pointer-pair",
200 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
201 cl::init(false));
202static cl::opt<unsigned> ClRealignStack(
203 "asan-realign-stack",
204 cl::desc("Realign stack to the value of this flag (power of two)"),
205 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000206static cl::opt<int> ClInstrumentationWithCallsThreshold(
207 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000208 cl::desc(
209 "If the function being instrumented contains more than "
210 "this number of memory accesses, use callbacks instead of "
211 "inline checks (-1 means never use callbacks)."),
212 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000213static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000214 "asan-memory-access-callback-prefix",
215 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
216 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000217static cl::opt<bool>
218 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
219 cl::desc("instrument dynamic allocas"),
220 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000221static cl::opt<bool> ClSkipPromotableAllocas(
222 "asan-skip-promotable-allocas",
223 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
224 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000225
226// These flags allow to change the shadow mapping.
227// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000228// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000230 cl::desc("scale of asan shadow mapping"),
231 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000232static cl::opt<unsigned long long> ClMappingOffset(
233 "asan-mapping-offset",
234 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
235 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000236
237// Optimization flags. Not user visible, used mostly for testing
238// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000239static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
240 cl::Hidden, cl::init(true));
241static cl::opt<bool> ClOptSameTemp(
242 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
243 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000244static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000245 cl::desc("Don't instrument scalar globals"),
246 cl::Hidden, cl::init(true));
247static cl::opt<bool> ClOptStack(
248 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
249 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000250
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000251static cl::opt<bool> ClDynamicAllocaStack(
252 "asan-stack-dynamic-alloca",
253 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000254 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000255
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000256static cl::opt<uint32_t> ClForceExperiment(
257 "asan-force-experiment",
258 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
259 cl::init(0));
260
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000261static cl::opt<bool>
262 ClUsePrivateAliasForGlobals("asan-use-private-alias",
263 cl::desc("Use private aliases for global"
264 " variables"),
265 cl::Hidden, cl::init(false));
266
Ryan Govostese51401b2016-07-05 21:53:08 +0000267static cl::opt<bool>
268 ClUseMachOGlobalsSection("asan-globals-live-support",
269 cl::desc("Use linker features to support dead "
270 "code stripping of globals "
271 "(Mach-O only)"),
Anna Zaks9cd5ed12016-11-17 16:55:40 +0000272 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000273
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000274// Debug flags.
275static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
276 cl::init(0));
277static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
278 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000279static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
280 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000281static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
282 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000283static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000284 cl::Hidden, cl::init(-1));
285
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000286STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
287STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000288STATISTIC(NumOptimizedAccessesToGlobalVar,
289 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000290STATISTIC(NumOptimizedAccessesToStackVar,
291 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000292
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000293namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000294/// Frontend-provided metadata for source location.
295struct LocationMetadata {
296 StringRef Filename;
297 int LineNo;
298 int ColumnNo;
299
300 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
301
302 bool empty() const { return Filename.empty(); }
303
304 void parse(MDNode *MDN) {
305 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000306 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
307 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000308 LineNo =
309 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
310 ColumnNo =
311 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000312 }
313};
314
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000315/// Frontend-provided metadata for global variables.
316class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000317 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000318 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000319 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000320 LocationMetadata SourceLoc;
321 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000322 bool IsDynInit;
323 bool IsBlacklisted;
324 };
325
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000326 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000327
Keno Fischere03fae42015-12-05 14:42:34 +0000328 void reset() {
329 inited_ = false;
330 Entries.clear();
331 }
332
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000333 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000334 assert(!inited_);
335 inited_ = true;
336 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000337 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000338 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000339 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000340 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000341 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000342 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000343 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000344 // We can already have an entry for GV if it was merged with another
345 // global.
346 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000347 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
348 E.SourceLoc.parse(Loc);
349 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
350 E.Name = Name->getString();
351 ConstantInt *IsDynInit =
352 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000353 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000354 ConstantInt *IsBlacklisted =
355 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000356 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000357 }
358 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000359
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000360 /// Returns metadata entry for a given global.
361 Entry get(GlobalVariable *G) const {
362 auto Pos = Entries.find(G);
363 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000364 }
365
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000366 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000367 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000368 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000369};
370
Alexey Samsonov1345d352013-01-16 13:23:28 +0000371/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000372/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000373struct ShadowMapping {
374 int Scale;
375 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000376 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000377};
378
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000379static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
380 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000381 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000382 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000383 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000384 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000385 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000386 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
387 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000388 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000389 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000390 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000391 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
392 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000393 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
394 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000395 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000396 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000397 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000398
399 ShadowMapping Mapping;
400
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000401 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000402 // Android is always PIE, which means that the beginning of the address
403 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000404 if (IsAndroid)
405 Mapping.Offset = 0;
406 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000407 Mapping.Offset = kMIPS32_ShadowOffset32;
408 else if (IsFreeBSD)
409 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000410 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000411 // If we're targeting iOS and x86, the binary is built for iOS simulator.
412 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000413 else if (IsWindows)
414 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000415 else
416 Mapping.Offset = kDefaultShadowOffset32;
417 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000418 // Fuchsia is always PIE, which means that the beginning of the address
419 // space is always available.
420 if (IsFuchsia)
421 Mapping.Offset = 0;
422 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000423 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000424 else if (IsSystemZ)
425 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000426 else if (IsFreeBSD)
427 Mapping.Offset = kFreeBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000428 else if (IsPS4CPU)
429 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000430 else if (IsLinux && IsX86_64) {
431 if (IsKasan)
432 Mapping.Offset = kLinuxKasan_ShadowOffset64;
433 else
434 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000435 } else if (IsWindows && IsX86_64) {
436 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000437 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000438 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000439 else if (IsIOS)
440 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000441 // We are using dynamic shadow offset on the 64-bit devices.
442 Mapping.Offset =
443 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000444 else if (IsAArch64)
445 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000446 else
447 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000448 }
449
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000450 if (ClForceDynamicShadow) {
451 Mapping.Offset = kDynamicShadowSentinel;
452 }
453
Alexey Samsonov1345d352013-01-16 13:23:28 +0000454 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000455 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000456 Mapping.Scale = ClMappingScale;
457 }
458
Ryan Govostes3f37df02016-05-06 10:25:22 +0000459 if (ClMappingOffset.getNumOccurrences() > 0) {
460 Mapping.Offset = ClMappingOffset;
461 }
462
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000463 // OR-ing shadow offset if more efficient (at least on x86) if the offset
464 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000465 // offset is not necessary 1/8-th of the address space. On SystemZ,
466 // we could OR the constant in a single instruction, but it's more
467 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000468 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
469 !(Mapping.Offset & (Mapping.Offset - 1)) &&
470 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000471
Alexey Samsonov1345d352013-01-16 13:23:28 +0000472 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000473}
474
Alexey Samsonov1345d352013-01-16 13:23:28 +0000475static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000476 // Redzone used for stack and globals is at least 32 bytes.
477 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000478 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000479}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000480
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000481/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000482struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000483 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
484 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000485 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000486 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000487 UseAfterScope(UseAfterScope || ClUseAfterScope),
488 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000489 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
490 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000491 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000492 return "AddressSanitizerFunctionPass";
493 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000494 void getAnalysisUsage(AnalysisUsage &AU) const override {
495 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000496 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000497 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000498 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000499 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000500 if (AI.isArrayAllocation()) {
501 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000502 assert(CI && "non-constant array size");
503 ArraySize = CI->getZExtValue();
504 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000505 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000506 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000507 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000508 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000509 }
510 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000511 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000512
Anna Zaks8ed1d812015-02-27 03:12:36 +0000513 /// If it is an interesting memory access, return the PointerOperand
514 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000515 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
516 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000517 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000518 uint64_t *TypeSize, unsigned *Alignment,
519 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000520 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000521 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000522 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000523 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
524 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000525 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000526 void instrumentUnusualSizeOrAlignment(Instruction *I,
527 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000528 uint32_t TypeSize, bool IsWrite,
529 Value *SizeArgument, bool UseCalls,
530 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000531 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
532 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000533 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000534 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000535 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000536 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000537 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000538 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000539 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000540 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000541 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000542 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000543 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000544 static char ID; // Pass identification, replacement for typeid
545
Yury Gribov3ae427d2014-12-01 08:47:58 +0000546 DominatorTree &getDominatorTree() const { return *DT; }
547
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000548 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000549 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000550
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000551 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000552 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000553 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
554 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000555
Reid Kleckner2f907552015-07-21 17:40:14 +0000556 /// Helper to cleanup per-function state.
557 struct FunctionStateRAII {
558 AddressSanitizer *Pass;
559 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
560 assert(Pass->ProcessedAllocas.empty() &&
561 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000562 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000563 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000564 ~FunctionStateRAII() {
565 Pass->LocalDynamicShadow = nullptr;
566 Pass->ProcessedAllocas.clear();
567 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000568 };
569
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000570 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000571 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000572 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000573 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000574 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000575 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000576 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000577 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000578 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000579 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000580 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000581 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
582 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
583 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
584 // This array is indexed by AccessIsWrite and Experiment.
585 Function *AsanErrorCallbackSized[2][2];
586 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000587 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000588 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000589 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000590 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000591 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000592
593 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000594};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000595
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000596class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000597 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000598 explicit AddressSanitizerModule(bool CompileKernel = false,
599 bool Recover = false)
600 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
601 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000602 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000603 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000604 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000605
Mehdi Amini117296c2016-10-01 02:56:57 +0000606private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000607 void initializeCallbacks(Module &M);
608
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +0000609 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000610 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
611 ArrayRef<GlobalVariable *> ExtendedGlobals,
612 ArrayRef<Constant *> MetadataInitializers);
613 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
614 ArrayRef<GlobalVariable *> ExtendedGlobals,
615 ArrayRef<Constant *> MetadataInitializers);
616 void
617 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
618 ArrayRef<GlobalVariable *> ExtendedGlobals,
619 ArrayRef<Constant *> MetadataInitializers);
620
621 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
622 StringRef OriginalName);
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +0000623 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000624 IRBuilder<> CreateAsanModuleDtor(Module &M);
625
Kostya Serebryany20a79972012-11-22 03:18:50 +0000626 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000627 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000628 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000629 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000630 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000631 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000632 return RedzoneSizeForScale(Mapping.Scale);
633 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000634
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000635 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000636 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000637 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000638 Type *IntptrTy;
639 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000640 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000641 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000642 Function *AsanPoisonGlobals;
643 Function *AsanUnpoisonGlobals;
644 Function *AsanRegisterGlobals;
645 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000646 Function *AsanRegisterImageGlobals;
647 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000648};
649
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000650// Stack poisoning does not play well with exception handling.
651// When an exception is thrown, we essentially bypass the code
652// that unpoisones the stack. This is why the run-time library has
653// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
654// stack in the interceptor. This however does not work inside the
655// actual function which catches the exception. Most likely because the
656// compiler hoists the load of the shadow value somewhere too high.
657// This causes asan to report a non-existing bug on 453.povray.
658// It sounds like an LLVM bug.
659struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
660 Function &F;
661 AddressSanitizer &ASan;
662 DIBuilder DIB;
663 LLVMContext *C;
664 Type *IntptrTy;
665 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000666 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000667
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000668 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000669 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000670 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000671 unsigned StackAlignment;
672
Kostya Serebryany6805de52013-09-10 13:16:56 +0000673 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000674 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000675 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000676 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000677 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000678
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000679 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
680 struct AllocaPoisonCall {
681 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000682 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000683 uint64_t Size;
684 bool DoPoison;
685 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000686 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
687 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000688
Yury Gribov98b18592015-05-28 07:51:49 +0000689 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
690 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
691 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000692 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000693
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000694 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000695 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000696 AllocaForValueMapTy AllocaForValue;
697
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000698 bool HasNonEmptyInlineAsm = false;
699 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000700 std::unique_ptr<CallInst> EmptyInlineAsm;
701
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000702 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000703 : F(F),
704 ASan(ASan),
705 DIB(*F.getParent(), /*AllowUnresolved*/ false),
706 C(ASan.C),
707 IntptrTy(ASan.IntptrTy),
708 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
709 Mapping(ASan.Mapping),
710 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000711 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000712
713 bool runOnFunction() {
714 if (!ClStack) return false;
715 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000716 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000717
Yury Gribov55441bb2014-11-21 10:29:50 +0000718 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000719
720 initializeCallbacks(*F.getParent());
721
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000722 processDynamicAllocas();
723 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000724
725 if (ClDebugStack) {
726 DEBUG(dbgs() << F);
727 }
728 return true;
729 }
730
Yury Gribov55441bb2014-11-21 10:29:50 +0000731 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000732 // poisoned red zones around all of them.
733 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000734 void processStaticAllocas();
735 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000736
Yury Gribov98b18592015-05-28 07:51:49 +0000737 void createDynamicAllocasInitStorage();
738
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000739 // ----------------------- Visitors.
740 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000741 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000742
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000743 /// \brief Collect all Resume instructions.
744 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
745
746 /// \brief Collect all CatchReturnInst instructions.
747 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
748
Yury Gribov98b18592015-05-28 07:51:49 +0000749 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
750 Value *SavedStack) {
751 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000752 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
753 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
754 // need to adjust extracted SP to compute the address of the most recent
755 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
756 // this purpose.
757 if (!isa<ReturnInst>(InstBefore)) {
758 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
759 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
760 {IntptrTy});
761
762 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
763
764 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
765 DynamicAreaOffset);
766 }
767
Yury Gribov781bce22015-05-28 08:03:28 +0000768 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000769 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000770 }
771
Yury Gribov55441bb2014-11-21 10:29:50 +0000772 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000773 void unpoisonDynamicAllocas() {
774 for (auto &Ret : RetVec)
775 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000776
Yury Gribov98b18592015-05-28 07:51:49 +0000777 for (auto &StackRestoreInst : StackRestoreVec)
778 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
779 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000780 }
781
Yury Gribov55441bb2014-11-21 10:29:50 +0000782 // Deploy and poison redzones around dynamic alloca call. To do this, we
783 // should replace this call with another one with changed parameters and
784 // replace all its uses with new address, so
785 // addr = alloca type, old_size, align
786 // is replaced by
787 // new_size = (old_size + additional_size) * sizeof(type)
788 // tmp = alloca i8, new_size, max(align, 32)
789 // addr = tmp + 32 (first 32 bytes are for the left redzone).
790 // Additional_size is added to make new memory allocation contain not only
791 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000792 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000793
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000794 /// \brief Collect Alloca instructions we want (and can) handle.
795 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000796 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000797 if (AI.isStaticAlloca()) {
798 // Skip over allocas that are present *before* the first instrumented
799 // alloca, we don't want to move those around.
800 if (AllocaVec.empty())
801 return;
802
803 StaticAllocasToMoveUp.push_back(&AI);
804 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000805 return;
806 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000807
808 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000809 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000810 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000811 else
812 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000813 }
814
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000815 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
816 /// errors.
817 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000818 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000819 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000820 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000821 if (!ASan.UseAfterScope)
822 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000823 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000824 return;
825 // Found lifetime intrinsic, add ASan instrumentation if necessary.
826 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
827 // If size argument is undefined, don't do anything.
828 if (Size->isMinusOne()) return;
829 // Check that size doesn't saturate uint64_t and can
830 // be stored in IntptrTy.
831 const uint64_t SizeValue = Size->getValue().getLimitedValue();
832 if (SizeValue == ~0ULL ||
833 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
834 return;
835 // Find alloca instruction that corresponds to llvm.lifetime argument.
836 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000837 if (!AI || !ASan.isInterestingAlloca(*AI))
838 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000839 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000840 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000841 if (AI->isStaticAlloca())
842 StaticAllocaPoisonCallVec.push_back(APC);
843 else if (ClInstrumentDynamicAllocas)
844 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000845 }
846
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000847 void visitCallSite(CallSite CS) {
848 Instruction *I = CS.getInstruction();
849 if (CallInst *CI = dyn_cast<CallInst>(I)) {
850 HasNonEmptyInlineAsm |=
851 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
852 HasReturnsTwiceCall |= CI->canReturnTwice();
853 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000854 }
855
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000856 // ---------------------- Helpers.
857 void initializeCallbacks(Module &M);
858
Yury Gribov3ae427d2014-12-01 08:47:58 +0000859 bool doesDominateAllExits(const Instruction *I) const {
860 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000861 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000862 }
863 return true;
864 }
865
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000866 /// Finds alloca where the value comes from.
867 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000868
869 // Copies bytes from ShadowBytes into shadow memory for indexes where
870 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
871 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
872 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
873 IRBuilder<> &IRB, Value *ShadowBase);
874 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
875 size_t Begin, size_t End, IRBuilder<> &IRB,
876 Value *ShadowBase);
877 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
878 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
879 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
880
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000881 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000882
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000883 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
884 bool Dynamic);
885 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
886 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000887};
888
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000889} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000890
891char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892INITIALIZE_PASS_BEGIN(
893 AddressSanitizer, "asan",
894 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
895 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000896INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000897INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000898INITIALIZE_PASS_END(
899 AddressSanitizer, "asan",
900 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
901 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000902FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000903 bool Recover,
904 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000905 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000906 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000907}
908
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000909char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000910INITIALIZE_PASS(
911 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000912 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000913 "ModulePass",
914 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000915ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
916 bool Recover) {
917 assert(!CompileKernel || Recover);
918 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000919}
920
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000921static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000922 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000923 assert(Res < kNumberOfAccessSizes);
924 return Res;
925}
926
Bill Wendling58f8cef2013-08-06 22:52:42 +0000927// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000928static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
929 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000930 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000931 // We use private linkage for module-local strings. If they can be merged
932 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000933 GlobalVariable *GV =
934 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000935 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000936 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000937 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
938 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000939}
940
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000941/// \brief Create a global describing a source location.
942static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
943 LocationMetadata MD) {
944 Constant *LocData[] = {
945 createPrivateGlobalForString(M, MD.Filename, true),
946 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
947 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
948 };
949 auto LocStruct = ConstantStruct::getAnon(LocData);
950 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
951 GlobalValue::PrivateLinkage, LocStruct,
952 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000953 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000954 return GV;
955}
956
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000957/// \brief Check if \p G has been created by a trusted compiler pass.
958static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
959 // Do not instrument asan globals.
960 if (G->getName().startswith(kAsanGenPrefix) ||
961 G->getName().startswith(kSanCovGenPrefix) ||
962 G->getName().startswith(kODRGenPrefix))
963 return true;
964
965 // Do not instrument gcov counter arrays.
966 if (G->getName() == "__llvm_gcov_ctr")
967 return true;
968
969 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000970}
971
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000972Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
973 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000974 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000975 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000976 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000977 Value *ShadowBase;
978 if (LocalDynamicShadow)
979 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000980 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000981 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
982 if (Mapping.OrShadowOffset)
983 return IRB.CreateOr(Shadow, ShadowBase);
984 else
985 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000986}
987
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000988// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000989void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
990 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000991 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000992 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000993 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000994 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
995 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
996 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000997 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000998 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000999 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001000 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1001 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1002 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001003 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001004 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001005}
1006
Anna Zaks8ed1d812015-02-27 03:12:36 +00001007/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001008bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001009 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1010
1011 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1012 return PreviouslySeenAllocaInfo->getSecond();
1013
Yury Gribov98b18592015-05-28 07:51:49 +00001014 bool IsInteresting =
1015 (AI.getAllocatedType()->isSized() &&
1016 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001017 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001018 // We are only interested in allocas not promotable to registers.
1019 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001020 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1021 // inalloca allocas are not treated as static, and we don't want
1022 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001023 !AI.isUsedWithInAlloca() &&
1024 // swifterror allocas are register promoted by ISel
1025 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001026
1027 ProcessedAllocas[&AI] = IsInteresting;
1028 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001029}
1030
Anna Zaks8ed1d812015-02-27 03:12:36 +00001031Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1032 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001033 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001034 unsigned *Alignment,
1035 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001036 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001037 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001038
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001039 // Do not instrument the load fetching the dynamic shadow address.
1040 if (LocalDynamicShadow == I)
1041 return nullptr;
1042
Anna Zaks8ed1d812015-02-27 03:12:36 +00001043 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001044 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001045 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001046 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001047 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001048 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001049 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001050 PtrOperand = LI->getPointerOperand();
1051 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001052 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001053 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001054 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001055 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001056 PtrOperand = SI->getPointerOperand();
1057 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001058 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001059 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001060 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001061 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001062 PtrOperand = RMW->getPointerOperand();
1063 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001064 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001065 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001066 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001067 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001068 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001069 } else if (auto CI = dyn_cast<CallInst>(I)) {
1070 auto *F = dyn_cast<Function>(CI->getCalledValue());
1071 if (F && (F->getName().startswith("llvm.masked.load.") ||
1072 F->getName().startswith("llvm.masked.store."))) {
1073 unsigned OpOffset = 0;
1074 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001075 if (!ClInstrumentWrites)
1076 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001077 // Masked store has an initial operand for the value.
1078 OpOffset = 1;
1079 *IsWrite = true;
1080 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001081 if (!ClInstrumentReads)
1082 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001083 *IsWrite = false;
1084 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001085
1086 auto BasePtr = CI->getOperand(0 + OpOffset);
1087 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1088 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1089 if (auto AlignmentConstant =
1090 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1091 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1092 else
1093 *Alignment = 1; // No alignment guarantees. We probably got Undef
1094 if (MaybeMask)
1095 *MaybeMask = CI->getOperand(2 + OpOffset);
1096 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001097 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001098 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001099
Anna Zaks644d9d32016-06-22 00:15:52 +00001100 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001101 // Do not instrument acesses from different address spaces; we cannot deal
1102 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001103 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1104 if (PtrTy->getPointerAddressSpace() != 0)
1105 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001106
1107 // Ignore swifterror addresses.
1108 // swifterror memory addresses are mem2reg promoted by instruction
1109 // selection. As such they cannot have regular uses like an instrumentation
1110 // function and it makes no sense to track them as memory.
1111 if (PtrOperand->isSwiftError())
1112 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001113 }
1114
Anna Zaks8ed1d812015-02-27 03:12:36 +00001115 // Treat memory accesses to promotable allocas as non-interesting since they
1116 // will not cause memory violations. This greatly speeds up the instrumented
1117 // executable at -O0.
1118 if (ClSkipPromotableAllocas)
1119 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1120 return isInterestingAlloca(*AI) ? AI : nullptr;
1121
1122 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001123}
1124
Kostya Serebryany796f6552014-02-27 12:45:36 +00001125static bool isPointerOperand(Value *V) {
1126 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1127}
1128
1129// This is a rough heuristic; it may cause both false positives and
1130// false negatives. The proper implementation requires cooperation with
1131// the frontend.
1132static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1133 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001134 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001135 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001136 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001137 } else {
1138 return false;
1139 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001140 return isPointerOperand(I->getOperand(0)) &&
1141 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001142}
1143
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001144bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1145 // If a global variable does not have dynamic initialization we don't
1146 // have to instrument it. However, if a global does not have initializer
1147 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001148 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001149}
1150
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001151void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1152 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001153 IRBuilder<> IRB(I);
1154 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1155 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001156 for (Value *&i : Param) {
1157 if (i->getType()->isPointerTy())
1158 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001159 }
David Blaikieff6409d2015-05-18 22:13:54 +00001160 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001161}
1162
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001163static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001164 Instruction *InsertBefore, Value *Addr,
1165 unsigned Alignment, unsigned Granularity,
1166 uint32_t TypeSize, bool IsWrite,
1167 Value *SizeArgument, bool UseCalls,
1168 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001169 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1170 // if the data is properly aligned.
1171 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1172 TypeSize == 128) &&
1173 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001174 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1175 nullptr, UseCalls, Exp);
1176 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1177 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001178}
1179
1180static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1181 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001182 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001183 Value *Addr, unsigned Alignment,
1184 unsigned Granularity, uint32_t TypeSize,
1185 bool IsWrite, Value *SizeArgument,
1186 bool UseCalls, uint32_t Exp) {
1187 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1188 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1189 unsigned Num = VTy->getVectorNumElements();
1190 auto Zero = ConstantInt::get(IntptrTy, 0);
1191 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001192 Value *InstrumentedAddress = nullptr;
1193 Instruction *InsertBefore = I;
1194 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1195 // dyn_cast as we might get UndefValue
1196 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1197 if (Masked->isNullValue())
1198 // Mask is constant false, so no instrumentation needed.
1199 continue;
1200 // If we have a true or undef value, fall through to doInstrumentAddress
1201 // with InsertBefore == I
1202 }
1203 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001204 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001205 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1206 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1207 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001208 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001209
1210 IRBuilder<> IRB(InsertBefore);
1211 InstrumentedAddress =
1212 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1213 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1214 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1215 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001216 }
1217}
1218
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001219void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001220 Instruction *I, bool UseCalls,
1221 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001222 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001223 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001224 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001225 Value *MaybeMask = nullptr;
1226 Value *Addr =
1227 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001228 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001229
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001230 // Optimization experiments.
1231 // The experiments can be used to evaluate potential optimizations that remove
1232 // instrumentation (assess false negatives). Instead of completely removing
1233 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1234 // experiments that want to remove instrumentation of this instruction).
1235 // If Exp is non-zero, this pass will emit special calls into runtime
1236 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1237 // make runtime terminate the program in a special way (with a different
1238 // exit status). Then you run the new compiler on a buggy corpus, collect
1239 // the special terminations (ideally, you don't see them at all -- no false
1240 // negatives) and make the decision on the optimization.
1241 uint32_t Exp = ClForceExperiment;
1242
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001243 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001244 // If initialization order checking is disabled, a simple access to a
1245 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001247 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001248 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1249 NumOptimizedAccessesToGlobalVar++;
1250 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001251 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001252 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001253
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001254 if (ClOpt && ClOptStack) {
1255 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001257 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1258 NumOptimizedAccessesToStackVar++;
1259 return;
1260 }
1261 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001262
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001263 if (IsWrite)
1264 NumInstrumentedWrites++;
1265 else
1266 NumInstrumentedReads++;
1267
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001268 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001269 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001270 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1271 Alignment, Granularity, TypeSize, IsWrite,
1272 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001273 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001274 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001275 IsWrite, nullptr, UseCalls, Exp);
1276 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001277}
1278
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001279Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1280 Value *Addr, bool IsWrite,
1281 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001282 Value *SizeArgument,
1283 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001284 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001285 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1286 CallInst *Call = nullptr;
1287 if (SizeArgument) {
1288 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001289 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1290 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001291 else
David Blaikieff6409d2015-05-18 22:13:54 +00001292 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1293 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001294 } else {
1295 if (Exp == 0)
1296 Call =
1297 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1298 else
David Blaikieff6409d2015-05-18 22:13:54 +00001299 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1300 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001301 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001302
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001303 // We don't do Call->setDoesNotReturn() because the BB already has
1304 // UnreachableInst at the end.
1305 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001306 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001307 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001308}
1309
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001310Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001311 Value *ShadowValue,
1312 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001313 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001314 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001315 Value *LastAccessedByte =
1316 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001317 // (Addr & (Granularity - 1)) + size - 1
1318 if (TypeSize / 8 > 1)
1319 LastAccessedByte = IRB.CreateAdd(
1320 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1321 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001322 LastAccessedByte =
1323 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001324 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1325 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1326}
1327
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001328void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001329 Instruction *InsertBefore, Value *Addr,
1330 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001331 Value *SizeArgument, bool UseCalls,
1332 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001333 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001334 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001335 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1336
1337 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001338 if (Exp == 0)
1339 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1340 AddrLong);
1341 else
David Blaikieff6409d2015-05-18 22:13:54 +00001342 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1343 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001344 return;
1345 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001346
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001347 Type *ShadowTy =
1348 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001349 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1350 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1351 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001352 Value *ShadowValue =
1353 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001354
1355 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001356 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001357 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001358
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001359 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001360 // We use branch weights for the slow path check, to indicate that the slow
1361 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001362 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1363 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001364 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001365 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001366 IRB.SetInsertPoint(CheckTerm);
1367 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001368 if (Recover) {
1369 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1370 } else {
1371 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001372 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001373 CrashTerm = new UnreachableInst(*C, CrashBlock);
1374 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1375 ReplaceInstWithInst(CheckTerm, NewTerm);
1376 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001377 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001378 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001379 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001380
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001381 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001382 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001383 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001384}
1385
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001386// Instrument unusual size or unusual alignment.
1387// We can not do it with a single check, so we do 1-byte check for the first
1388// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1389// to report the actual access size.
1390void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001391 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1392 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1393 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001394 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1395 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1396 if (UseCalls) {
1397 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001398 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1399 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001400 else
David Blaikieff6409d2015-05-18 22:13:54 +00001401 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1402 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001403 } else {
1404 Value *LastByte = IRB.CreateIntToPtr(
1405 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1406 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001407 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1408 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001409 }
1410}
1411
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001412void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1413 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001414 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001415 IRBuilder<> IRB(&GlobalInit.front(),
1416 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001417
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001418 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001419 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1420 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001421
1422 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001423 for (auto &BB : GlobalInit.getBasicBlockList())
1424 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001425 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001426}
1427
1428void AddressSanitizerModule::createInitializerPoisonCalls(
1429 Module &M, GlobalValue *ModuleName) {
1430 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1431
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001432 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001433 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001434 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001435 ConstantStruct *CS = cast<ConstantStruct>(OP);
1436
1437 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001438 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001439 if (F->getName() == kAsanModuleCtorName) continue;
1440 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1441 // Don't instrument CTORs that will run before asan.module_ctor.
1442 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1443 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001444 }
1445 }
1446}
1447
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001448bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001449 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001450 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001451
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001452 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001453 if (!Ty->isSized()) return false;
1454 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001455 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001456 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001457 // Don't handle ODR linkage types and COMDATs since other modules may be built
1458 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001459 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1460 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1461 G->getLinkage() != GlobalVariable::InternalLinkage)
1462 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001463 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001464 // Two problems with thread-locals:
1465 // - The address of the main thread's copy can't be computed at link-time.
1466 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001467 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001468 // For now, just ignore this Global if the alignment is large.
1469 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001470
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001471 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001472 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001473
Anna Zaks11904602015-06-09 00:58:08 +00001474 // Globals from llvm.metadata aren't emitted, do not instrument them.
1475 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001476 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001477 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001478
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001479 // Do not instrument function pointers to initialization and termination
1480 // routines: dynamic linker will not properly handle redzones.
1481 if (Section.startswith(".preinit_array") ||
1482 Section.startswith(".init_array") ||
1483 Section.startswith(".fini_array")) {
1484 return false;
1485 }
1486
Anna Zaks11904602015-06-09 00:58:08 +00001487 // Callbacks put into the CRT initializer/terminator sections
1488 // should not be instrumented.
1489 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1490 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1491 if (Section.startswith(".CRT")) {
1492 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1493 return false;
1494 }
1495
Kuba Brecka1001bb52014-12-05 22:19:18 +00001496 if (TargetTriple.isOSBinFormatMachO()) {
1497 StringRef ParsedSegment, ParsedSection;
1498 unsigned TAA = 0, StubSize = 0;
1499 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001500 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1501 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001502 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001503
1504 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1505 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1506 // them.
1507 if (ParsedSegment == "__OBJC" ||
1508 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1509 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1510 return false;
1511 }
1512 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1513 // Constant CFString instances are compiled in the following way:
1514 // -- the string buffer is emitted into
1515 // __TEXT,__cstring,cstring_literals
1516 // -- the constant NSConstantString structure referencing that buffer
1517 // is placed into __DATA,__cfstring
1518 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1519 // Moreover, it causes the linker to crash on OS X 10.7
1520 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1521 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1522 return false;
1523 }
1524 // The linker merges the contents of cstring_literals and removes the
1525 // trailing zeroes.
1526 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1527 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1528 return false;
1529 }
1530 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001531 }
1532
1533 return true;
1534}
1535
Ryan Govostes653f9d02016-03-28 20:28:57 +00001536// On Mach-O platforms, we emit global metadata in a separate section of the
1537// binary in order to allow the linker to properly dead strip. This is only
1538// supported on recent versions of ld64.
1539bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001540 if (!ClUseMachOGlobalsSection)
1541 return false;
1542
Ryan Govostes653f9d02016-03-28 20:28:57 +00001543 if (!TargetTriple.isOSBinFormatMachO())
1544 return false;
1545
1546 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1547 return true;
1548 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001549 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001550 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1551 return true;
1552
1553 return false;
1554}
1555
Reid Kleckner01660a32016-11-21 20:40:37 +00001556StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1557 switch (TargetTriple.getObjectFormat()) {
1558 case Triple::COFF: return ".ASAN$GL";
1559 case Triple::ELF: return "asan_globals";
1560 case Triple::MachO: return "__DATA,__asan_globals,regular";
1561 default: break;
1562 }
1563 llvm_unreachable("unsupported object format");
1564}
1565
Alexey Samsonov788381b2012-12-25 12:28:20 +00001566void AddressSanitizerModule::initializeCallbacks(Module &M) {
1567 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001568
Alexey Samsonov788381b2012-12-25 12:28:20 +00001569 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001570 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001571 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001572 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001573 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001574 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001575 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001576
Alexey Samsonov788381b2012-12-25 12:28:20 +00001577 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001578 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001579 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001580 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001581 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1582 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001583 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001584 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001585
1586 // Declare the functions that find globals in a shared object and then invoke
1587 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001588 AsanRegisterImageGlobals =
1589 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001590 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001591 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001592
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001593 AsanUnregisterImageGlobals =
1594 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001595 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001596 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001597}
1598
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001599// Put the metadata and the instrumented global in the same group. This ensures
1600// that the metadata is discarded if the instrumented global is discarded.
1601void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +00001602 GlobalVariable *G, GlobalVariable *Metadata) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001603 Module &M = *G->getParent();
1604 Comdat *C = G->getComdat();
1605 if (!C) {
1606 if (!G->hasName()) {
1607 // If G is unnamed, it must be internal. Give it an artificial name
1608 // so we can put it in a comdat.
1609 assert(G->hasLocalLinkage());
1610 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1611 }
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +00001612 C = M.getOrInsertComdat(G->getName());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001613 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1614 if (TargetTriple.isOSBinFormatCOFF())
1615 C->setSelectionKind(Comdat::NoDuplicates);
1616 G->setComdat(C);
1617 }
1618
1619 assert(G->hasComdat());
1620 Metadata->setComdat(G->getComdat());
1621}
1622
1623// Create a separate metadata global and put it in the appropriate ASan
1624// global registration section.
1625GlobalVariable *
1626AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1627 StringRef OriginalName) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001628 GlobalVariable *Metadata =
1629 new GlobalVariable(M, Initializer->getType(), false,
1630 GlobalVariable::InternalLinkage, Initializer,
1631 Twine("__asan_global_") +
1632 GlobalValue::getRealLinkageName(OriginalName));
1633 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001634 return Metadata;
1635}
1636
1637IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001638 Function *AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001639 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1640 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1641 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001642 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001643
1644 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1645}
1646
1647void AddressSanitizerModule::InstrumentGlobalsCOFF(
1648 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1649 ArrayRef<Constant *> MetadataInitializers) {
1650 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001651 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001652
1653 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001654 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001655 GlobalVariable *G = ExtendedGlobals[i];
1656 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001657 CreateMetadataGlobal(M, Initializer, G->getName());
1658
1659 // The MSVC linker always inserts padding when linking incrementally. We
1660 // cope with that by aligning each struct to its size, which must be a power
1661 // of two.
1662 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1663 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1664 "global metadata will not be padded appropriately");
1665 Metadata->setAlignment(SizeOfGlobalStruct);
1666
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +00001667 SetComdatForGlobalMetadata(G, Metadata);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001668 }
1669}
1670
1671void AddressSanitizerModule::InstrumentGlobalsMachO(
1672 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1673 ArrayRef<Constant *> MetadataInitializers) {
1674 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1675
1676 // On recent Mach-O platforms, use a structure which binds the liveness of
1677 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1678 // created to be added to llvm.compiler.used
1679 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1680 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1681
1682 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1683 Constant *Initializer = MetadataInitializers[i];
1684 GlobalVariable *G = ExtendedGlobals[i];
1685 GlobalVariable *Metadata =
1686 CreateMetadataGlobal(M, Initializer, G->getName());
1687
1688 // On recent Mach-O platforms, we emit the global metadata in a way that
1689 // allows the linker to properly strip dead globals.
1690 auto LivenessBinder = ConstantStruct::get(
1691 LivenessTy, Initializer->getAggregateElement(0u),
1692 ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1693 GlobalVariable *Liveness = new GlobalVariable(
1694 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1695 Twine("__asan_binder_") + G->getName());
1696 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1697 LivenessGlobals[i] = Liveness;
1698 }
1699
1700 // Update llvm.compiler.used, adding the new liveness globals. This is
1701 // needed so that during LTO these variables stay alive. The alternative
1702 // would be to have the linker handling the LTO symbols, but libLTO
1703 // current API does not expose access to the section for each symbol.
1704 if (!LivenessGlobals.empty())
1705 appendToCompilerUsed(M, LivenessGlobals);
1706
1707 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1708 // to look up the loaded image that contains it. Second, we can store in it
1709 // whether registration has already occurred, to prevent duplicate
1710 // registration.
1711 //
1712 // common linkage ensures that there is only one global per shared library.
1713 GlobalVariable *RegisteredFlag = new GlobalVariable(
1714 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1715 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1716 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1717
1718 IRB.CreateCall(AsanRegisterImageGlobals,
1719 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1720
1721 // We also need to unregister globals at the end, e.g., when a shared library
1722 // gets closed.
1723 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1724 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1725 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1726}
1727
1728void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1729 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1730 ArrayRef<Constant *> MetadataInitializers) {
1731 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1732 unsigned N = ExtendedGlobals.size();
1733 assert(N > 0);
1734
1735 // On platforms that don't have a custom metadata section, we emit an array
1736 // of global metadata structures.
1737 ArrayType *ArrayOfGlobalStructTy =
1738 ArrayType::get(MetadataInitializers[0]->getType(), N);
1739 auto AllGlobals = new GlobalVariable(
1740 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1741 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1742
1743 IRB.CreateCall(AsanRegisterGlobals,
1744 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1745 ConstantInt::get(IntptrTy, N)});
1746
1747 // We also need to unregister globals at the end, e.g., when a shared library
1748 // gets closed.
1749 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1750 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1751 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1752 ConstantInt::get(IntptrTy, N)});
1753}
1754
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001755// This function replaces all global variables with new variables that have
1756// trailing redzones. It also creates a function that poisons
1757// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001758bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001759 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001760
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001761 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1762
Alexey Samsonova02e6642014-05-29 18:40:48 +00001763 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001764 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001765 }
1766
1767 size_t n = GlobalsToChange.size();
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001768 if (n == 0) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001769
Reid Kleckner78565832016-11-29 01:32:21 +00001770 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001771
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001772 // A global is described by a structure
1773 // size_t beg;
1774 // size_t size;
1775 // size_t size_with_redzone;
1776 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001777 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001778 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001779 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001780 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001781 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001782 StructType *GlobalStructTy =
1783 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001784 IntptrTy, IntptrTy, IntptrTy, nullptr);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001785 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1786 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001787
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001788 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001789
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001790 // We shouldn't merge same module names, as this string serves as unique
1791 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001792 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001793 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001794
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001795 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001796 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001797 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001798
1799 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001800 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001801 // Create string holding the global name (use global name from metadata
1802 // if it's available, otherwise just write the name of global variable).
1803 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001804 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001805 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001806
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001807 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001808 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001809 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001810 // MinRZ <= RZ <= kMaxGlobalRedzone
1811 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001812 uint64_t RZ = std::max(
1813 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001814 uint64_t RightRedzoneSize = RZ;
1815 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001816 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001817 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001818 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1819
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001820 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001821 Constant *NewInitializer =
1822 ConstantStruct::get(NewTy, G->getInitializer(),
1823 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001824
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001825 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001826 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1827 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1828 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001829 GlobalVariable *NewGlobal =
1830 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1831 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001832 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001833 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001834
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001835 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1836 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1837 G->isConstant()) {
1838 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1839 if (Seq && Seq->isCString())
1840 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1841 }
1842
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001843 // Transfer the debug info. The payload starts at offset zero so we can
1844 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001845 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001846 G->getDebugInfo(GVs);
1847 for (auto *GV : GVs)
1848 NewGlobal->addDebugInfo(GV);
1849
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001850 Value *Indices2[2];
1851 Indices2[0] = IRB.getInt32(0);
1852 Indices2[1] = IRB.getInt32(0);
1853
1854 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001855 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001856 NewGlobal->takeName(G);
1857 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001858 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001859
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001860 Constant *SourceLoc;
1861 if (!MD.SourceLoc.empty()) {
1862 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1863 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1864 } else {
1865 SourceLoc = ConstantInt::get(IntptrTy, 0);
1866 }
1867
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001868 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1869 GlobalValue *InstrumentedGlobal = NewGlobal;
1870
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001871 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00001872 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1873 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001874 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1875 // Create local alias for NewGlobal to avoid crash on ODR between
1876 // instrumented and non-instrumented libraries.
1877 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1878 NameForGlobal + M.getName(), NewGlobal);
1879
1880 // With local aliases, we need to provide another externally visible
1881 // symbol __odr_asan_XXX to detect ODR violation.
1882 auto *ODRIndicatorSym =
1883 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1884 Constant::getNullValue(IRB.getInt8Ty()),
1885 kODRGenPrefix + NameForGlobal, nullptr,
1886 NewGlobal->getThreadLocalMode());
1887
1888 // Set meaningful attributes for indicator symbol.
1889 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1890 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1891 ODRIndicatorSym->setAlignment(1);
1892 ODRIndicator = ODRIndicatorSym;
1893 InstrumentedGlobal = GA;
1894 }
1895
Reid Kleckner01660a32016-11-21 20:40:37 +00001896 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001897 GlobalStructTy,
1898 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001899 ConstantInt::get(IntptrTy, SizeInBytes),
1900 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1901 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001902 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001903 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1904 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001905
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001906 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001907
Kostya Serebryany20343352012-10-17 13:40:06 +00001908 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00001909
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001910 Initializers[i] = Initializer;
1911 }
Reid Kleckner01660a32016-11-21 20:40:37 +00001912
Evgeniy Stepanovba7c2e92017-04-10 20:36:30 +00001913 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001914 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
1915 } else if (ShouldUseMachOGlobalsSection()) {
1916 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
1917 } else {
1918 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001919 }
1920
Reid Kleckner01660a32016-11-21 20:40:37 +00001921 // Create calls for poisoning before initializers run and unpoisoning after.
1922 if (HasDynamicallyInitializedGlobals)
1923 createInitializerPoisonCalls(M, ModuleName);
1924
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001925 DEBUG(dbgs() << M);
1926 return true;
1927}
1928
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001929bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001930 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001931 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001932 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001933 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001934 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001935 initializeCallbacks(M);
1936
Evgeniy Stepanov039af602017-04-06 19:55:09 +00001937 if (CompileKernel)
1938 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00001939
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001940 Function *AsanCtorFunction;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00001941 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
1942 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
1943 /*InitArgs=*/{}, kAsanVersionCheckName);
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001944 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00001945
1946 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001947 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00001948 if (ClGlobals) {
1949 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanoved7fce72017-04-10 20:36:36 +00001950 Changed |= InstrumentGlobals(IRB, M);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001951 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001952
1953 return Changed;
1954}
1955
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001956void AddressSanitizer::initializeCallbacks(Module &M) {
1957 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001958 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001959 // IsWrite, TypeSize and Exp are encoded in the function name.
1960 for (int Exp = 0; Exp < 2; Exp++) {
1961 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1962 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1963 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001964 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001965 const std::string EndingStr = Recover ? "_noabort" : "";
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001966 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001967 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001968 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001969 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001970 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001971 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001972 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001973 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001974 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001975 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1976 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001977 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001978 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001979 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001980 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001981 IRB.getVoidTy(), IntptrTy, ExpType));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001982 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001983 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001984 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001985 IRB.getVoidTy(), IntptrTy, ExpType));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001986 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001987 }
1988 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001989
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001990 const std::string MemIntrinCallbackPrefix =
1991 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001992 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001993 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001994 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001995 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001996 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00001997 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001998 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001999 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002000 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002001
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002002 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002003 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002004
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002005 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002006 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002007 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002008 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002009 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2010 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2011 StringRef(""), StringRef(""),
2012 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002013}
2014
2015// virtual
2016bool AddressSanitizer::doInitialization(Module &M) {
2017 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002018 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002019
2020 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002021 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002022 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002023 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002024
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002025 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002026 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002027}
2028
Keno Fischere03fae42015-12-05 14:42:34 +00002029bool AddressSanitizer::doFinalization(Module &M) {
2030 GlobalsMD.reset();
2031 return false;
2032}
2033
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002034bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2035 // For each NSObject descendant having a +load method, this method is invoked
2036 // by the ObjC runtime before any of the static constructors is called.
2037 // Therefore we need to instrument such methods with a call to __asan_init
2038 // at the beginning in order to initialize our runtime before any access to
2039 // the shadow memory.
2040 // We cannot just ignore these methods, because they may call other
2041 // instrumented functions.
2042 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002043 Function *AsanInitFunction =
2044 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002045 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002046 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002047 return true;
2048 }
2049 return false;
2050}
2051
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002052void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2053 // Generate code only when dynamic addressing is needed.
2054 if (Mapping.Offset != kDynamicShadowSentinel)
2055 return;
2056
2057 IRBuilder<> IRB(&F.front().front());
2058 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2059 kAsanShadowMemoryDynamicAddress, IntptrTy);
2060 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2061}
2062
Reid Kleckner2f907552015-07-21 17:40:14 +00002063void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2064 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2065 // to it as uninteresting. This assumes we haven't started processing allocas
2066 // yet. This check is done up front because iterating the use list in
2067 // isInterestingAlloca would be algorithmically slower.
2068 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2069
2070 // Try to get the declaration of llvm.localescape. If it's not in the module,
2071 // we can exit early.
2072 if (!F.getParent()->getFunction("llvm.localescape")) return;
2073
2074 // Look for a call to llvm.localescape call in the entry block. It can't be in
2075 // any other block.
2076 for (Instruction &I : F.getEntryBlock()) {
2077 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2078 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2079 // We found a call. Mark all the allocas passed in as uninteresting.
2080 for (Value *Arg : II->arg_operands()) {
2081 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2082 assert(AI && AI->isStaticAlloca() &&
2083 "non-static alloca arg to localescape");
2084 ProcessedAllocas[AI] = false;
2085 }
2086 break;
2087 }
2088 }
2089}
2090
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002091bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002092 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002093 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002094 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002095
Etienne Bergeron78582b22016-09-15 15:45:05 +00002096 bool FunctionModified = false;
2097
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002098 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002099 // This function needs to be called even if the function body is not
2100 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002101 if (maybeInsertAsanInitAtFunctionEntry(F))
2102 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002103
2104 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002105 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002106
Etienne Bergeron752f8832016-09-14 17:18:37 +00002107 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2108
2109 initializeCallbacks(*F.getParent());
2110 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002111
Reid Kleckner2f907552015-07-21 17:40:14 +00002112 FunctionStateRAII CleanupObj(this);
2113
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002114 maybeInsertDynamicShadowAtFunctionEntry(F);
2115
Reid Kleckner2f907552015-07-21 17:40:14 +00002116 // We can't instrument allocas used with llvm.localescape. Only static allocas
2117 // can be passed to that intrinsic.
2118 markEscapedLocalAllocas(F);
2119
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002120 // We want to instrument every address only once per basic block (unless there
2121 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002122 SmallSet<Value *, 16> TempsToInstrument;
2123 SmallVector<Instruction *, 16> ToInstrument;
2124 SmallVector<Instruction *, 8> NoReturnCalls;
2125 SmallVector<BasicBlock *, 16> AllBlocks;
2126 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002127 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002128 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002129 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002130 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002131 const TargetLibraryInfo *TLI =
2132 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002133
2134 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002135 for (auto &BB : F) {
2136 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002137 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002138 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002139 for (auto &Inst : BB) {
2140 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002141 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002142 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002143 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002144 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002145 // If we have a mask, skip instrumentation if we've already
2146 // instrumented the full object. But don't add to TempsToInstrument
2147 // because we might get another load/store with a different mask.
2148 if (MaybeMask) {
2149 if (TempsToInstrument.count(Addr))
2150 continue; // We've seen this (whole) temp in the current BB.
2151 } else {
2152 if (!TempsToInstrument.insert(Addr).second)
2153 continue; // We've seen this temp in the current BB.
2154 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002155 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002156 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002157 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2158 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002159 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002160 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002161 // ok, take it.
2162 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002163 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002164 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002165 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002166 // A call inside BB.
2167 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002168 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002169 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002170 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2171 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002172 continue;
2173 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002174 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002175 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002176 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002177 }
2178 }
2179
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002180 bool UseCalls =
2181 CompileKernel ||
2182 (ClInstrumentationWithCallsThreshold >= 0 &&
2183 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002184 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002185 ObjectSizeOpts ObjSizeOpts;
2186 ObjSizeOpts.RoundToAlign = true;
2187 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002188
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002189 // Instrument.
2190 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002191 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002192 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2193 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002194 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002195 instrumentMop(ObjSizeVis, Inst, UseCalls,
2196 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002197 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002198 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002199 }
2200 NumInstrumented++;
2201 }
2202
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002203 FunctionStackPoisoner FSP(F, *this);
2204 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002205
2206 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2207 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002208 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002209 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002210 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002211 }
2212
Alexey Samsonova02e6642014-05-29 18:40:48 +00002213 for (auto Inst : PointerComparisonsOrSubtracts) {
2214 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002215 NumInstrumented++;
2216 }
2217
Etienne Bergeron78582b22016-09-15 15:45:05 +00002218 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2219 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002220
Etienne Bergeron78582b22016-09-15 15:45:05 +00002221 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2222 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002223
Etienne Bergeron78582b22016-09-15 15:45:05 +00002224 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002225}
2226
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002227// Workaround for bug 11395: we don't want to instrument stack in functions
2228// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2229// FIXME: remove once the bug 11395 is fixed.
2230bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2231 if (LongSize != 32) return false;
2232 CallInst *CI = dyn_cast<CallInst>(I);
2233 if (!CI || !CI->isInlineAsm()) return false;
2234 if (CI->getNumArgOperands() <= 5) return false;
2235 // We have inline assembly with quite a few arguments.
2236 return true;
2237}
2238
2239void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2240 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002241 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2242 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002243 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2244 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002245 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002246 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002247 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002248 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002249 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002250 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002251 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2252 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002253 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002254 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2255 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002256 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002257 }
2258
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002259 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2260 std::ostringstream Name;
2261 Name << kAsanSetShadowPrefix;
2262 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002263 AsanSetShadowFunc[Val] =
2264 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002265 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002266 }
2267
Yury Gribov98b18592015-05-28 07:51:49 +00002268 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002269 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002270 AsanAllocasUnpoisonFunc =
2271 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton5fd75fb2017-04-11 08:36:52 +00002272 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002273}
2274
Vitaly Buka793913c2016-08-29 18:17:21 +00002275void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2276 ArrayRef<uint8_t> ShadowBytes,
2277 size_t Begin, size_t End,
2278 IRBuilder<> &IRB,
2279 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002280 if (Begin >= End)
2281 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002282
2283 const size_t LargestStoreSizeInBytes =
2284 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2285
2286 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2287
2288 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002289 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2290 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2291 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002292 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002293 if (!ShadowMask[i]) {
2294 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002295 ++i;
2296 continue;
2297 }
2298
2299 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2300 // Fit store size into the range.
2301 while (StoreSizeInBytes > End - i)
2302 StoreSizeInBytes /= 2;
2303
2304 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002305 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002306 while (j <= StoreSizeInBytes / 2)
2307 StoreSizeInBytes /= 2;
2308 }
2309
2310 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002311 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2312 if (IsLittleEndian)
2313 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2314 else
2315 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002316 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002317
2318 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2319 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002320 IRB.CreateAlignedStore(
2321 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002322
2323 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002324 }
2325}
2326
Vitaly Buka793913c2016-08-29 18:17:21 +00002327void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2328 ArrayRef<uint8_t> ShadowBytes,
2329 IRBuilder<> &IRB, Value *ShadowBase) {
2330 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2331}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002332
Vitaly Buka793913c2016-08-29 18:17:21 +00002333void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2334 ArrayRef<uint8_t> ShadowBytes,
2335 size_t Begin, size_t End,
2336 IRBuilder<> &IRB, Value *ShadowBase) {
2337 assert(ShadowMask.size() == ShadowBytes.size());
2338 size_t Done = Begin;
2339 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2340 if (!ShadowMask[i]) {
2341 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002342 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002343 }
2344 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002345 if (!AsanSetShadowFunc[Val])
2346 continue;
2347
2348 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002349 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002350 }
2351
2352 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002353 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002354 IRB.CreateCall(AsanSetShadowFunc[Val],
2355 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2356 ConstantInt::get(IntptrTy, j - i)});
2357 Done = j;
2358 }
2359 }
2360
Vitaly Buka793913c2016-08-29 18:17:21 +00002361 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002362}
2363
Kostya Serebryany6805de52013-09-10 13:16:56 +00002364// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2365// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2366static int StackMallocSizeClass(uint64_t LocalStackSize) {
2367 assert(LocalStackSize <= kMaxStackMallocSize);
2368 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002369 for (int i = 0;; i++, MaxSize *= 2)
2370 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002371 llvm_unreachable("impossible LocalStackSize");
2372}
2373
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002374PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2375 Value *ValueIfTrue,
2376 Instruction *ThenTerm,
2377 Value *ValueIfFalse) {
2378 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2379 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2380 PHI->addIncoming(ValueIfFalse, CondBlock);
2381 BasicBlock *ThenBlock = ThenTerm->getParent();
2382 PHI->addIncoming(ValueIfTrue, ThenBlock);
2383 return PHI;
2384}
2385
2386Value *FunctionStackPoisoner::createAllocaForLayout(
2387 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2388 AllocaInst *Alloca;
2389 if (Dynamic) {
2390 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2391 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2392 "MyAlloca");
2393 } else {
2394 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2395 nullptr, "MyAlloca");
2396 assert(Alloca->isStaticAlloca());
2397 }
2398 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2399 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2400 Alloca->setAlignment(FrameAlignment);
2401 return IRB.CreatePointerCast(Alloca, IntptrTy);
2402}
2403
Yury Gribov98b18592015-05-28 07:51:49 +00002404void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2405 BasicBlock &FirstBB = *F.begin();
2406 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2407 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2408 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2409 DynamicAllocaLayout->setAlignment(32);
2410}
2411
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002412void FunctionStackPoisoner::processDynamicAllocas() {
2413 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2414 assert(DynamicAllocaPoisonCallVec.empty());
2415 return;
2416 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002417
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002418 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2419 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002420 assert(APC.InsBefore);
2421 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002422 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002423 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002424
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002425 IRBuilder<> IRB(APC.InsBefore);
2426 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002427 // Dynamic allocas will be unpoisoned unconditionally below in
2428 // unpoisonDynamicAllocas.
2429 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002430 }
2431
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002432 // Handle dynamic allocas.
2433 createDynamicAllocasInitStorage();
2434 for (auto &AI : DynamicAllocaVec)
2435 handleDynamicAllocaCall(AI);
2436 unpoisonDynamicAllocas();
2437}
Yury Gribov98b18592015-05-28 07:51:49 +00002438
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002439void FunctionStackPoisoner::processStaticAllocas() {
2440 if (AllocaVec.empty()) {
2441 assert(StaticAllocaPoisonCallVec.empty());
2442 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002443 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002444
Kostya Serebryany6805de52013-09-10 13:16:56 +00002445 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002446 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002447 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002448 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002449
2450 Instruction *InsBefore = AllocaVec[0];
2451 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002452 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002453
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002454 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2455 // debug info is broken, because only entry-block allocas are treated as
2456 // regular stack slots.
2457 auto InsBeforeB = InsBefore->getParent();
2458 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002459 for (auto *AI : StaticAllocasToMoveUp)
2460 if (AI->getParent() == InsBeforeB)
2461 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002462
Reid Kleckner2f907552015-07-21 17:40:14 +00002463 // If we have a call to llvm.localescape, keep it in the entry block.
2464 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2465
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002466 SmallVector<ASanStackVariableDescription, 16> SVD;
2467 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002468 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002469 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002470 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002471 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002472 AI->getAlignment(),
2473 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002474 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002475 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002476 SVD.push_back(D);
2477 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002478
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002479 // Minimal header size (left redzone) is 4 pointers,
2480 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2481 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002482 const ASanStackFrameLayout &L =
2483 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002484
Vitaly Buka5910a922016-10-18 23:29:52 +00002485 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2486 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2487 for (auto &Desc : SVD)
2488 AllocaToSVDMap[Desc.AI] = &Desc;
2489
2490 // Update SVD with information from lifetime intrinsics.
2491 for (const auto &APC : StaticAllocaPoisonCallVec) {
2492 assert(APC.InsBefore);
2493 assert(APC.AI);
2494 assert(ASan.isInterestingAlloca(*APC.AI));
2495 assert(APC.AI->isStaticAlloca());
2496
2497 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2498 Desc.LifetimeSize = Desc.Size;
2499 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2500 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2501 if (LifetimeLoc->getFile() == FnLoc->getFile())
2502 if (unsigned Line = LifetimeLoc->getLine())
2503 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2504 }
2505 }
2506 }
2507
2508 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2509 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002510 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002511 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2512 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002513 bool DoDynamicAlloca = ClDynamicAllocaStack;
2514 // Don't do dynamic alloca or stack malloc if:
2515 // 1) There is inline asm: too often it makes assumptions on which registers
2516 // are available.
2517 // 2) There is a returns_twice call (typically setjmp), which is
2518 // optimization-hostile, and doesn't play well with introduced indirect
2519 // register-relative calculation of local variable addresses.
2520 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2521 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002522
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002523 Value *StaticAlloca =
2524 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2525
2526 Value *FakeStack;
2527 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002528
2529 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002530 // void *FakeStack = __asan_option_detect_stack_use_after_return
2531 // ? __asan_stack_malloc_N(LocalStackSize)
2532 // : nullptr;
2533 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002534 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2535 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2536 Value *UseAfterReturnIsEnabled =
2537 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002538 Constant::getNullValue(IRB.getInt32Ty()));
2539 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002540 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002541 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002542 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002543 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2544 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2545 Value *FakeStackValue =
2546 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2547 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002548 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002549 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002550 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002551 ConstantInt::get(IntptrTy, 0));
2552
2553 Value *NoFakeStack =
2554 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2555 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2556 IRBIf.SetInsertPoint(Term);
2557 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2558 Value *AllocaValue =
2559 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2560 IRB.SetInsertPoint(InsBefore);
2561 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2562 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2563 } else {
2564 // void *FakeStack = nullptr;
2565 // void *LocalStackBase = alloca(LocalStackSize);
2566 FakeStack = ConstantInt::get(IntptrTy, 0);
2567 LocalStackBase =
2568 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002569 }
2570
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002571 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002572 for (const auto &Desc : SVD) {
2573 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002574 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002575 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002576 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002577 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002578 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002579 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002580
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002581 // The left-most redzone has enough space for at least 4 pointers.
2582 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002583 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2584 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2585 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002586 // Write the frame description constant to redzone[1].
2587 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002588 IRB.CreateAdd(LocalStackBase,
2589 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2590 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002591 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002592 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002593 /*AllowMerging*/ true);
2594 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002595 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002596 // Write the PC to redzone[2].
2597 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002598 IRB.CreateAdd(LocalStackBase,
2599 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2600 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002601 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002602
Vitaly Buka793913c2016-08-29 18:17:21 +00002603 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2604
2605 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002606 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002607 // As mask we must use most poisoned case: red zones and after scope.
2608 // As bytes we can use either the same or just red zones only.
2609 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2610
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002611 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002612 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2613
2614 // Poison static allocas near lifetime intrinsics.
2615 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002616 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002617 assert(Desc.Offset % L.Granularity == 0);
2618 size_t Begin = Desc.Offset / L.Granularity;
2619 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2620
2621 IRBuilder<> IRB(APC.InsBefore);
2622 copyToShadow(ShadowAfterScope,
2623 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2624 IRB, ShadowBase);
2625 }
2626 }
2627
2628 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002629 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002630
Kostya Serebryany530e2072013-12-23 14:15:08 +00002631 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002632 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002633 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002634 // Mark the current frame as retired.
2635 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2636 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002637 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002638 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002639 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002640 // // In use-after-return mode, poison the whole stack frame.
2641 // if StackMallocIdx <= 4
2642 // // For small sizes inline the whole thing:
2643 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002644 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002645 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002646 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002647 // else
2648 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002649 Value *Cmp =
2650 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002651 TerminatorInst *ThenTerm, *ElseTerm;
2652 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2653
2654 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002655 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002656 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002657 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2658 kAsanStackUseAfterReturnMagic);
2659 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2660 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002661 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002662 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002663 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2664 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2665 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2666 IRBPoison.CreateStore(
2667 Constant::getNullValue(IRBPoison.getInt8Ty()),
2668 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2669 } else {
2670 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002671 IRBPoison.CreateCall(
2672 AsanStackFreeFunc[StackMallocIdx],
2673 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002674 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002675
2676 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002677 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002678 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002679 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002680 }
2681 }
2682
Kostya Serebryany09959942012-10-19 06:20:53 +00002683 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002684 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002685}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002686
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002687void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002688 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002689 // For now just insert the call to ASan runtime.
2690 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2691 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002692 IRB.CreateCall(
2693 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2694 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002695}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002696
2697// Handling llvm.lifetime intrinsics for a given %alloca:
2698// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2699// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2700// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2701// could be poisoned by previous llvm.lifetime.end instruction, as the
2702// variable may go in and out of scope several times, e.g. in loops).
2703// (3) if we poisoned at least one %alloca in a function,
2704// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002705
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002706AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2707 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002708 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002709 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002710 // See if we've already calculated (or started to calculate) alloca for a
2711 // given value.
2712 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002713 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002714 // Store 0 while we're calculating alloca for value V to avoid
2715 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002716 AllocaForValue[V] = nullptr;
2717 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002718 if (CastInst *CI = dyn_cast<CastInst>(V))
2719 Res = findAllocaForValue(CI->getOperand(0));
2720 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002721 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002722 // Allow self-referencing phi-nodes.
2723 if (IncValue == PN) continue;
2724 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2725 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002726 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2727 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002728 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002729 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002730 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2731 Res = findAllocaForValue(EP->getPointerOperand());
2732 } else {
2733 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002734 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002735 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002736 return Res;
2737}
Yury Gribov55441bb2014-11-21 10:29:50 +00002738
Yury Gribov98b18592015-05-28 07:51:49 +00002739void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002740 IRBuilder<> IRB(AI);
2741
Yury Gribov55441bb2014-11-21 10:29:50 +00002742 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2743 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2744
2745 Value *Zero = Constant::getNullValue(IntptrTy);
2746 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2747 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002748
2749 // Since we need to extend alloca with additional memory to locate
2750 // redzones, and OldSize is number of allocated blocks with
2751 // ElementSize size, get allocated memory size in bytes by
2752 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002753 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002754 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002755 Value *OldSize =
2756 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2757 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002758
2759 // PartialSize = OldSize % 32
2760 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2761
2762 // Misalign = kAllocaRzSize - PartialSize;
2763 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2764
2765 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2766 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2767 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2768
2769 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2770 // Align is added to locate left redzone, PartialPadding for possible
2771 // partial redzone and kAllocaRzSize for right redzone respectively.
2772 Value *AdditionalChunkSize = IRB.CreateAdd(
2773 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2774
2775 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2776
2777 // Insert new alloca with new NewSize and Align params.
2778 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2779 NewAlloca->setAlignment(Align);
2780
2781 // NewAddress = Address + Align
2782 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2783 ConstantInt::get(IntptrTy, Align));
2784
Yury Gribov98b18592015-05-28 07:51:49 +00002785 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002786 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002787
2788 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2789 // for unpoisoning stuff.
2790 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2791
Yury Gribov55441bb2014-11-21 10:29:50 +00002792 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2793
Yury Gribov98b18592015-05-28 07:51:49 +00002794 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002795 AI->replaceAllUsesWith(NewAddressPtr);
2796
Yury Gribov98b18592015-05-28 07:51:49 +00002797 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002798 AI->eraseFromParent();
2799}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002800
2801// isSafeAccess returns true if Addr is always inbounds with respect to its
2802// base object. For example, it is a field access or an array access with
2803// constant inbounds index.
2804bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2805 Value *Addr, uint64_t TypeSize) const {
2806 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2807 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002808 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002809 int64_t Offset = SizeOffset.second.getSExtValue();
2810 // Three checks are required to ensure safety:
2811 // . Offset >= 0 (since the offset is given from the base ptr)
2812 // . Size >= Offset (unsigned)
2813 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002814 return Offset >= 0 && Size >= uint64_t(Offset) &&
2815 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002816}