blob: 82778fbd4d95952c78e14703c9ac60f13ced10d1 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000072static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000074static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000075static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000076static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000077static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000078static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000079static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000080static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000081static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000083static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000084// The shadow memory space is dynamically allocated.
85static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000086
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000087static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000088static const size_t kMaxStackMallocSize = 1 << 16; // 64K
89static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
90static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
91
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanModuleCtorName = "asan.module_ctor";
93static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000094static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000097static const char *const kAsanUnregisterGlobalsName =
98 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000099static const char *const kAsanRegisterImageGlobalsName =
100 "__asan_register_image_globals";
101static const char *const kAsanUnregisterImageGlobalsName =
102 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000103static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
104static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000105static const char *const kAsanInitName = "__asan_init";
106static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000107 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000108static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
109static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000110static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000111static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000112static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
113static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000114static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000115static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000116static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000117static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000118static const char *const kAsanPoisonStackMemoryName =
119 "__asan_poison_stack_memory";
120static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000121 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000122static const char *const kAsanGlobalsRegisteredFlagName =
123 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000124
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000125static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000126 "__asan_option_detect_stack_use_after_return";
127
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000128static const char *const kAsanShadowMemoryDynamicAddress =
129 "__asan_shadow_memory_dynamic_address";
130
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000131static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
132static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000133
Kostya Serebryany874dae62012-07-16 16:15:40 +0000134// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
135static const size_t kNumberOfAccessSizes = 5;
136
Yury Gribov55441bb2014-11-21 10:29:50 +0000137static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000138
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000139// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000140static cl::opt<bool> ClEnableKasan(
141 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
142 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000143static cl::opt<bool> ClRecover(
144 "asan-recover",
145 cl::desc("Enable recovery mode (continue-after-error)."),
146 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000147
148// This flag may need to be replaced with -f[no-]asan-reads.
149static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150 cl::desc("instrument read instructions"),
151 cl::Hidden, cl::init(true));
152static cl::opt<bool> ClInstrumentWrites(
153 "asan-instrument-writes", cl::desc("instrument write instructions"),
154 cl::Hidden, cl::init(true));
155static cl::opt<bool> ClInstrumentAtomics(
156 "asan-instrument-atomics",
157 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
158 cl::init(true));
159static cl::opt<bool> ClAlwaysSlowPath(
160 "asan-always-slow-path",
161 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
162 cl::init(false));
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000163static cl::opt<bool> ClForceDynamicShadow(
164 "asan-force-dynamic-shadow",
165 cl::desc("Load shadow address into a local variable for each function"),
166 cl::Hidden, cl::init(false));
167
Kostya Serebryany874dae62012-07-16 16:15:40 +0000168// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000169// in any given BB. Normally, this should be set to unlimited (INT_MAX),
170// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
171// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
173 "asan-max-ins-per-bb", cl::init(10000),
174 cl::desc("maximal number of instructions to instrument in any given BB"),
175 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000176// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000177static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
178 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000179static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
180 "asan-max-inline-poisoning-size",
181 cl::desc(
182 "Inline shadow poisoning for blocks up to the given size in bytes."),
183 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000184static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000185 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000187static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
188 cl::desc("Check stack-use-after-scope"),
189 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000190// This flag may need to be replaced with -f[no]asan-globals.
191static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192 cl::desc("Handle global objects"), cl::Hidden,
193 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000194static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000195 cl::desc("Handle C++ initializer order"),
196 cl::Hidden, cl::init(true));
197static cl::opt<bool> ClInvalidPointerPairs(
198 "asan-detect-invalid-pointer-pair",
199 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
200 cl::init(false));
201static cl::opt<unsigned> ClRealignStack(
202 "asan-realign-stack",
203 cl::desc("Realign stack to the value of this flag (power of two)"),
204 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000205static cl::opt<int> ClInstrumentationWithCallsThreshold(
206 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000207 cl::desc(
208 "If the function being instrumented contains more than "
209 "this number of memory accesses, use callbacks instead of "
210 "inline checks (-1 means never use callbacks)."),
211 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000212static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000213 "asan-memory-access-callback-prefix",
214 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
215 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000216static cl::opt<bool>
217 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
218 cl::desc("instrument dynamic allocas"),
219 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000220static cl::opt<bool> ClSkipPromotableAllocas(
221 "asan-skip-promotable-allocas",
222 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
223 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000224
225// These flags allow to change the shadow mapping.
226// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000227// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000228static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000229 cl::desc("scale of asan shadow mapping"),
230 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000231static cl::opt<unsigned long long> ClMappingOffset(
232 "asan-mapping-offset",
233 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
234 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000235
236// Optimization flags. Not user visible, used mostly for testing
237// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000238static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
239 cl::Hidden, cl::init(true));
240static cl::opt<bool> ClOptSameTemp(
241 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
242 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000243static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000244 cl::desc("Don't instrument scalar globals"),
245 cl::Hidden, cl::init(true));
246static cl::opt<bool> ClOptStack(
247 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
248 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000249
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000250static cl::opt<bool> ClDynamicAllocaStack(
251 "asan-stack-dynamic-alloca",
252 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000253 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000254
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000255static cl::opt<uint32_t> ClForceExperiment(
256 "asan-force-experiment",
257 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
258 cl::init(0));
259
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000260static cl::opt<bool>
261 ClUsePrivateAliasForGlobals("asan-use-private-alias",
262 cl::desc("Use private aliases for global"
263 " variables"),
264 cl::Hidden, cl::init(false));
265
Ryan Govostese51401b2016-07-05 21:53:08 +0000266static cl::opt<bool>
267 ClUseMachOGlobalsSection("asan-globals-live-support",
268 cl::desc("Use linker features to support dead "
269 "code stripping of globals "
270 "(Mach-O only)"),
Anna Zaks9cd5ed12016-11-17 16:55:40 +0000271 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000272
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000273// Debug flags.
274static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
275 cl::init(0));
276static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
277 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000278static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
279 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000280static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
281 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000282static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000283 cl::Hidden, cl::init(-1));
284
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000285STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
286STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000287STATISTIC(NumOptimizedAccessesToGlobalVar,
288 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000289STATISTIC(NumOptimizedAccessesToStackVar,
290 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000291
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000292namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000293/// Frontend-provided metadata for source location.
294struct LocationMetadata {
295 StringRef Filename;
296 int LineNo;
297 int ColumnNo;
298
299 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
300
301 bool empty() const { return Filename.empty(); }
302
303 void parse(MDNode *MDN) {
304 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000305 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
306 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000307 LineNo =
308 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
309 ColumnNo =
310 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000311 }
312};
313
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000314/// Frontend-provided metadata for global variables.
315class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000316 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000317 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000318 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000319 LocationMetadata SourceLoc;
320 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000321 bool IsDynInit;
322 bool IsBlacklisted;
323 };
324
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000325 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000326
Keno Fischere03fae42015-12-05 14:42:34 +0000327 void reset() {
328 inited_ = false;
329 Entries.clear();
330 }
331
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000332 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000333 assert(!inited_);
334 inited_ = true;
335 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000336 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000337 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000338 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000339 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000340 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000341 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000342 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000343 // We can already have an entry for GV if it was merged with another
344 // global.
345 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000346 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
347 E.SourceLoc.parse(Loc);
348 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
349 E.Name = Name->getString();
350 ConstantInt *IsDynInit =
351 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000352 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000353 ConstantInt *IsBlacklisted =
354 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000355 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000356 }
357 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000358
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000359 /// Returns metadata entry for a given global.
360 Entry get(GlobalVariable *G) const {
361 auto Pos = Entries.find(G);
362 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000363 }
364
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000365 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000366 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000367 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000368};
369
Alexey Samsonov1345d352013-01-16 13:23:28 +0000370/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000371/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000372struct ShadowMapping {
373 int Scale;
374 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000375 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000376};
377
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000378static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
379 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000380 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000381 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000382 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
383 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000384 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
385 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000386 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000387 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000388 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000389 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
390 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000391 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
392 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000393 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000394 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000395
396 ShadowMapping Mapping;
397
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000398 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000399 // Android is always PIE, which means that the beginning of the address
400 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000401 if (IsAndroid)
402 Mapping.Offset = 0;
403 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000404 Mapping.Offset = kMIPS32_ShadowOffset32;
405 else if (IsFreeBSD)
406 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000407 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000408 // If we're targeting iOS and x86, the binary is built for iOS simulator.
409 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000410 else if (IsWindows)
411 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000412 else
413 Mapping.Offset = kDefaultShadowOffset32;
414 } else { // LongSize == 64
415 if (IsPPC64)
416 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000417 else if (IsSystemZ)
418 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000419 else if (IsFreeBSD)
420 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000421 else if (IsLinux && IsX86_64) {
422 if (IsKasan)
423 Mapping.Offset = kLinuxKasan_ShadowOffset64;
424 else
425 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000426 } else if (IsWindows && IsX86_64) {
427 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000428 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000429 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000430 else if (IsIOS)
431 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000432 // We are using dynamic shadow offset on the 64-bit devices.
433 Mapping.Offset =
434 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000435 else if (IsAArch64)
436 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000437 else
438 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000439 }
440
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000441 if (ClForceDynamicShadow) {
442 Mapping.Offset = kDynamicShadowSentinel;
443 }
444
Alexey Samsonov1345d352013-01-16 13:23:28 +0000445 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000446 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000447 Mapping.Scale = ClMappingScale;
448 }
449
Ryan Govostes3f37df02016-05-06 10:25:22 +0000450 if (ClMappingOffset.getNumOccurrences() > 0) {
451 Mapping.Offset = ClMappingOffset;
452 }
453
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000454 // OR-ing shadow offset if more efficient (at least on x86) if the offset
455 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000456 // offset is not necessary 1/8-th of the address space. On SystemZ,
457 // we could OR the constant in a single instruction, but it's more
458 // efficient to load it once and use indexed addressing.
459 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000460 && !(Mapping.Offset & (Mapping.Offset - 1))
461 && Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000462
Alexey Samsonov1345d352013-01-16 13:23:28 +0000463 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000464}
465
Alexey Samsonov1345d352013-01-16 13:23:28 +0000466static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000467 // Redzone used for stack and globals is at least 32 bytes.
468 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000469 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000470}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000471
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000472/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000473struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000474 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
475 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000476 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000477 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000478 UseAfterScope(UseAfterScope || ClUseAfterScope),
479 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000480 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
481 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000482 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000483 return "AddressSanitizerFunctionPass";
484 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000485 void getAnalysisUsage(AnalysisUsage &AU) const override {
486 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000487 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000488 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000489 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000490 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000491 if (AI.isArrayAllocation()) {
492 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000493 assert(CI && "non-constant array size");
494 ArraySize = CI->getZExtValue();
495 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000496 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000497 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000498 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000499 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000500 }
501 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000502 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000503
Anna Zaks8ed1d812015-02-27 03:12:36 +0000504 /// If it is an interesting memory access, return the PointerOperand
505 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000506 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
507 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000508 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000509 uint64_t *TypeSize, unsigned *Alignment,
510 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000511 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000512 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000513 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000514 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
515 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000516 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000517 void instrumentUnusualSizeOrAlignment(Instruction *I,
518 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000519 uint32_t TypeSize, bool IsWrite,
520 Value *SizeArgument, bool UseCalls,
521 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000522 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
523 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000524 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000525 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000526 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000527 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000528 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000529 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000530 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000531 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000532 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000533 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000534 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000535 static char ID; // Pass identification, replacement for typeid
536
Yury Gribov3ae427d2014-12-01 08:47:58 +0000537 DominatorTree &getDominatorTree() const { return *DT; }
538
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000539 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000540 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000541
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000542 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000543 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000544 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
545 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000546
Reid Kleckner2f907552015-07-21 17:40:14 +0000547 /// Helper to cleanup per-function state.
548 struct FunctionStateRAII {
549 AddressSanitizer *Pass;
550 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
551 assert(Pass->ProcessedAllocas.empty() &&
552 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000553 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000554 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000555 ~FunctionStateRAII() {
556 Pass->LocalDynamicShadow = nullptr;
557 Pass->ProcessedAllocas.clear();
558 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000559 };
560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000561 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000562 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000563 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000564 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000565 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000566 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000567 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000568 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000569 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000570 Function *AsanCtorFunction = nullptr;
571 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000572 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000573 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000574 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
575 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
576 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
577 // This array is indexed by AccessIsWrite and Experiment.
578 Function *AsanErrorCallbackSized[2][2];
579 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000580 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000581 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000582 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000583 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000584 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000585
586 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000587};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000588
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000589class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000590 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000591 explicit AddressSanitizerModule(bool CompileKernel = false,
592 bool Recover = false)
593 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
594 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000595 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000596 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000597 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000598
Mehdi Amini117296c2016-10-01 02:56:57 +0000599private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000600 void initializeCallbacks(Module &M);
601
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000602 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000603 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
604 ArrayRef<GlobalVariable *> ExtendedGlobals,
605 ArrayRef<Constant *> MetadataInitializers);
606 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
607 ArrayRef<GlobalVariable *> ExtendedGlobals,
608 ArrayRef<Constant *> MetadataInitializers);
609 void
610 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
611 ArrayRef<GlobalVariable *> ExtendedGlobals,
612 ArrayRef<Constant *> MetadataInitializers);
613
614 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
615 StringRef OriginalName);
616 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata);
617 IRBuilder<> CreateAsanModuleDtor(Module &M);
618
Kostya Serebryany20a79972012-11-22 03:18:50 +0000619 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000620 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000621 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000622 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000623 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000624 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000625 return RedzoneSizeForScale(Mapping.Scale);
626 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000627
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000628 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000629 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000630 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000631 Type *IntptrTy;
632 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000633 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000634 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000635 Function *AsanPoisonGlobals;
636 Function *AsanUnpoisonGlobals;
637 Function *AsanRegisterGlobals;
638 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000639 Function *AsanRegisterImageGlobals;
640 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000641};
642
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000643// Stack poisoning does not play well with exception handling.
644// When an exception is thrown, we essentially bypass the code
645// that unpoisones the stack. This is why the run-time library has
646// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
647// stack in the interceptor. This however does not work inside the
648// actual function which catches the exception. Most likely because the
649// compiler hoists the load of the shadow value somewhere too high.
650// This causes asan to report a non-existing bug on 453.povray.
651// It sounds like an LLVM bug.
652struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
653 Function &F;
654 AddressSanitizer &ASan;
655 DIBuilder DIB;
656 LLVMContext *C;
657 Type *IntptrTy;
658 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000659 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000660
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000661 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000662 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000663 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000664 unsigned StackAlignment;
665
Kostya Serebryany6805de52013-09-10 13:16:56 +0000666 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000667 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000668 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000669 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000670 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000671
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000672 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
673 struct AllocaPoisonCall {
674 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000675 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000676 uint64_t Size;
677 bool DoPoison;
678 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000679 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
680 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000681
Yury Gribov98b18592015-05-28 07:51:49 +0000682 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
683 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
684 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000685 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000686
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000687 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000688 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000689 AllocaForValueMapTy AllocaForValue;
690
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000691 bool HasNonEmptyInlineAsm = false;
692 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000693 std::unique_ptr<CallInst> EmptyInlineAsm;
694
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000696 : F(F),
697 ASan(ASan),
698 DIB(*F.getParent(), /*AllowUnresolved*/ false),
699 C(ASan.C),
700 IntptrTy(ASan.IntptrTy),
701 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
702 Mapping(ASan.Mapping),
703 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000704 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000705
706 bool runOnFunction() {
707 if (!ClStack) return false;
708 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000709 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000710
Yury Gribov55441bb2014-11-21 10:29:50 +0000711 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000712
713 initializeCallbacks(*F.getParent());
714
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000715 processDynamicAllocas();
716 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000717
718 if (ClDebugStack) {
719 DEBUG(dbgs() << F);
720 }
721 return true;
722 }
723
Yury Gribov55441bb2014-11-21 10:29:50 +0000724 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000725 // poisoned red zones around all of them.
726 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000727 void processStaticAllocas();
728 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000729
Yury Gribov98b18592015-05-28 07:51:49 +0000730 void createDynamicAllocasInitStorage();
731
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000732 // ----------------------- Visitors.
733 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000734 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000735
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000736 /// \brief Collect all Resume instructions.
737 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
738
739 /// \brief Collect all CatchReturnInst instructions.
740 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
741
Yury Gribov98b18592015-05-28 07:51:49 +0000742 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
743 Value *SavedStack) {
744 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000745 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
746 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
747 // need to adjust extracted SP to compute the address of the most recent
748 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
749 // this purpose.
750 if (!isa<ReturnInst>(InstBefore)) {
751 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
752 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
753 {IntptrTy});
754
755 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
756
757 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
758 DynamicAreaOffset);
759 }
760
Yury Gribov781bce22015-05-28 08:03:28 +0000761 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000762 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000763 }
764
Yury Gribov55441bb2014-11-21 10:29:50 +0000765 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000766 void unpoisonDynamicAllocas() {
767 for (auto &Ret : RetVec)
768 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000769
Yury Gribov98b18592015-05-28 07:51:49 +0000770 for (auto &StackRestoreInst : StackRestoreVec)
771 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
772 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000773 }
774
Yury Gribov55441bb2014-11-21 10:29:50 +0000775 // Deploy and poison redzones around dynamic alloca call. To do this, we
776 // should replace this call with another one with changed parameters and
777 // replace all its uses with new address, so
778 // addr = alloca type, old_size, align
779 // is replaced by
780 // new_size = (old_size + additional_size) * sizeof(type)
781 // tmp = alloca i8, new_size, max(align, 32)
782 // addr = tmp + 32 (first 32 bytes are for the left redzone).
783 // Additional_size is added to make new memory allocation contain not only
784 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000785 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000786
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000787 /// \brief Collect Alloca instructions we want (and can) handle.
788 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000789 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000790 if (AI.isStaticAlloca()) {
791 // Skip over allocas that are present *before* the first instrumented
792 // alloca, we don't want to move those around.
793 if (AllocaVec.empty())
794 return;
795
796 StaticAllocasToMoveUp.push_back(&AI);
797 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000798 return;
799 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000800
801 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000802 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000803 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000804 else
805 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000806 }
807
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000808 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
809 /// errors.
810 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000811 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000812 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000813 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000814 if (!ASan.UseAfterScope)
815 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000816 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000817 return;
818 // Found lifetime intrinsic, add ASan instrumentation if necessary.
819 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
820 // If size argument is undefined, don't do anything.
821 if (Size->isMinusOne()) return;
822 // Check that size doesn't saturate uint64_t and can
823 // be stored in IntptrTy.
824 const uint64_t SizeValue = Size->getValue().getLimitedValue();
825 if (SizeValue == ~0ULL ||
826 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
827 return;
828 // Find alloca instruction that corresponds to llvm.lifetime argument.
829 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000830 if (!AI || !ASan.isInterestingAlloca(*AI))
831 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000832 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000833 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000834 if (AI->isStaticAlloca())
835 StaticAllocaPoisonCallVec.push_back(APC);
836 else if (ClInstrumentDynamicAllocas)
837 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000838 }
839
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000840 void visitCallSite(CallSite CS) {
841 Instruction *I = CS.getInstruction();
842 if (CallInst *CI = dyn_cast<CallInst>(I)) {
843 HasNonEmptyInlineAsm |=
844 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
845 HasReturnsTwiceCall |= CI->canReturnTwice();
846 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000847 }
848
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000849 // ---------------------- Helpers.
850 void initializeCallbacks(Module &M);
851
Yury Gribov3ae427d2014-12-01 08:47:58 +0000852 bool doesDominateAllExits(const Instruction *I) const {
853 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000854 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000855 }
856 return true;
857 }
858
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000859 /// Finds alloca where the value comes from.
860 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000861
862 // Copies bytes from ShadowBytes into shadow memory for indexes where
863 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
864 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
865 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
866 IRBuilder<> &IRB, Value *ShadowBase);
867 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
868 size_t Begin, size_t End, IRBuilder<> &IRB,
869 Value *ShadowBase);
870 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
871 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
872 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
873
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000874 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000875
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000876 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
877 bool Dynamic);
878 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
879 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000880};
881
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000882} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000883
884char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000885INITIALIZE_PASS_BEGIN(
886 AddressSanitizer, "asan",
887 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
888 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000889INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000890INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000891INITIALIZE_PASS_END(
892 AddressSanitizer, "asan",
893 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
894 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000895FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000896 bool Recover,
897 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000898 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000899 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000900}
901
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000902char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000903INITIALIZE_PASS(
904 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000905 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000906 "ModulePass",
907 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000908ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
909 bool Recover) {
910 assert(!CompileKernel || Recover);
911 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000912}
913
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000914static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000915 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000916 assert(Res < kNumberOfAccessSizes);
917 return Res;
918}
919
Bill Wendling58f8cef2013-08-06 22:52:42 +0000920// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000921static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
922 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000923 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000924 // We use private linkage for module-local strings. If they can be merged
925 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000926 GlobalVariable *GV =
927 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000928 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000929 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000930 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
931 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000932}
933
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000934/// \brief Create a global describing a source location.
935static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
936 LocationMetadata MD) {
937 Constant *LocData[] = {
938 createPrivateGlobalForString(M, MD.Filename, true),
939 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
940 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
941 };
942 auto LocStruct = ConstantStruct::getAnon(LocData);
943 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
944 GlobalValue::PrivateLinkage, LocStruct,
945 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000946 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000947 return GV;
948}
949
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000950/// \brief Check if \p G has been created by a trusted compiler pass.
951static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
952 // Do not instrument asan globals.
953 if (G->getName().startswith(kAsanGenPrefix) ||
954 G->getName().startswith(kSanCovGenPrefix) ||
955 G->getName().startswith(kODRGenPrefix))
956 return true;
957
958 // Do not instrument gcov counter arrays.
959 if (G->getName() == "__llvm_gcov_ctr")
960 return true;
961
962 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000963}
964
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000965Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
966 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000967 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000968 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000969 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000970 Value *ShadowBase;
971 if (LocalDynamicShadow)
972 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000973 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000974 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
975 if (Mapping.OrShadowOffset)
976 return IRB.CreateOr(Shadow, ShadowBase);
977 else
978 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000979}
980
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000981// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000982void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
983 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000984 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000985 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000986 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000987 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
988 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
989 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000990 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000991 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000992 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000993 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
994 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
995 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000996 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000997 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000998}
999
Anna Zaks8ed1d812015-02-27 03:12:36 +00001000/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001001bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001002 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1003
1004 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1005 return PreviouslySeenAllocaInfo->getSecond();
1006
Yury Gribov98b18592015-05-28 07:51:49 +00001007 bool IsInteresting =
1008 (AI.getAllocatedType()->isSized() &&
1009 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001010 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001011 // We are only interested in allocas not promotable to registers.
1012 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001013 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1014 // inalloca allocas are not treated as static, and we don't want
1015 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001016 !AI.isUsedWithInAlloca() &&
1017 // swifterror allocas are register promoted by ISel
1018 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001019
1020 ProcessedAllocas[&AI] = IsInteresting;
1021 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001022}
1023
Anna Zaks8ed1d812015-02-27 03:12:36 +00001024Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1025 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001026 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001027 unsigned *Alignment,
1028 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001029 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001030 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001031
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001032 // Do not instrument the load fetching the dynamic shadow address.
1033 if (LocalDynamicShadow == I)
1034 return nullptr;
1035
Anna Zaks8ed1d812015-02-27 03:12:36 +00001036 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001037 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001038 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001039 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001040 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001041 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001042 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001043 PtrOperand = LI->getPointerOperand();
1044 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001045 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001046 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001047 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001048 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001049 PtrOperand = SI->getPointerOperand();
1050 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001051 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001052 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001053 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001054 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001055 PtrOperand = RMW->getPointerOperand();
1056 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001057 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001058 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001059 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001060 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001061 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001062 } else if (auto CI = dyn_cast<CallInst>(I)) {
1063 auto *F = dyn_cast<Function>(CI->getCalledValue());
1064 if (F && (F->getName().startswith("llvm.masked.load.") ||
1065 F->getName().startswith("llvm.masked.store."))) {
1066 unsigned OpOffset = 0;
1067 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001068 if (!ClInstrumentWrites)
1069 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001070 // Masked store has an initial operand for the value.
1071 OpOffset = 1;
1072 *IsWrite = true;
1073 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001074 if (!ClInstrumentReads)
1075 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001076 *IsWrite = false;
1077 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001078
1079 auto BasePtr = CI->getOperand(0 + OpOffset);
1080 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1081 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1082 if (auto AlignmentConstant =
1083 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1084 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1085 else
1086 *Alignment = 1; // No alignment guarantees. We probably got Undef
1087 if (MaybeMask)
1088 *MaybeMask = CI->getOperand(2 + OpOffset);
1089 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001090 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001091 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001092
Anna Zaks644d9d32016-06-22 00:15:52 +00001093 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001094 // Do not instrument acesses from different address spaces; we cannot deal
1095 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001096 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1097 if (PtrTy->getPointerAddressSpace() != 0)
1098 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001099
1100 // Ignore swifterror addresses.
1101 // swifterror memory addresses are mem2reg promoted by instruction
1102 // selection. As such they cannot have regular uses like an instrumentation
1103 // function and it makes no sense to track them as memory.
1104 if (PtrOperand->isSwiftError())
1105 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001106 }
1107
Anna Zaks8ed1d812015-02-27 03:12:36 +00001108 // Treat memory accesses to promotable allocas as non-interesting since they
1109 // will not cause memory violations. This greatly speeds up the instrumented
1110 // executable at -O0.
1111 if (ClSkipPromotableAllocas)
1112 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1113 return isInterestingAlloca(*AI) ? AI : nullptr;
1114
1115 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001116}
1117
Kostya Serebryany796f6552014-02-27 12:45:36 +00001118static bool isPointerOperand(Value *V) {
1119 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1120}
1121
1122// This is a rough heuristic; it may cause both false positives and
1123// false negatives. The proper implementation requires cooperation with
1124// the frontend.
1125static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1126 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001127 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001128 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001129 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001130 } else {
1131 return false;
1132 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001133 return isPointerOperand(I->getOperand(0)) &&
1134 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001135}
1136
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001137bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1138 // If a global variable does not have dynamic initialization we don't
1139 // have to instrument it. However, if a global does not have initializer
1140 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001141 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001142}
1143
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001144void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1145 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001146 IRBuilder<> IRB(I);
1147 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1148 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001149 for (Value *&i : Param) {
1150 if (i->getType()->isPointerTy())
1151 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001152 }
David Blaikieff6409d2015-05-18 22:13:54 +00001153 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001154}
1155
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001156static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001157 Instruction *InsertBefore, Value *Addr,
1158 unsigned Alignment, unsigned Granularity,
1159 uint32_t TypeSize, bool IsWrite,
1160 Value *SizeArgument, bool UseCalls,
1161 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001162 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1163 // if the data is properly aligned.
1164 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1165 TypeSize == 128) &&
1166 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001167 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1168 nullptr, UseCalls, Exp);
1169 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1170 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001171}
1172
1173static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1174 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001175 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001176 Value *Addr, unsigned Alignment,
1177 unsigned Granularity, uint32_t TypeSize,
1178 bool IsWrite, Value *SizeArgument,
1179 bool UseCalls, uint32_t Exp) {
1180 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1181 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1182 unsigned Num = VTy->getVectorNumElements();
1183 auto Zero = ConstantInt::get(IntptrTy, 0);
1184 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001185 Value *InstrumentedAddress = nullptr;
1186 Instruction *InsertBefore = I;
1187 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1188 // dyn_cast as we might get UndefValue
1189 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1190 if (Masked->isNullValue())
1191 // Mask is constant false, so no instrumentation needed.
1192 continue;
1193 // If we have a true or undef value, fall through to doInstrumentAddress
1194 // with InsertBefore == I
1195 }
1196 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001197 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001198 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1199 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1200 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001201 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001202
1203 IRBuilder<> IRB(InsertBefore);
1204 InstrumentedAddress =
1205 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1206 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1207 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1208 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001209 }
1210}
1211
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001212void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001213 Instruction *I, bool UseCalls,
1214 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001215 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001216 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001217 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001218 Value *MaybeMask = nullptr;
1219 Value *Addr =
1220 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001221 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001222
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001223 // Optimization experiments.
1224 // The experiments can be used to evaluate potential optimizations that remove
1225 // instrumentation (assess false negatives). Instead of completely removing
1226 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1227 // experiments that want to remove instrumentation of this instruction).
1228 // If Exp is non-zero, this pass will emit special calls into runtime
1229 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1230 // make runtime terminate the program in a special way (with a different
1231 // exit status). Then you run the new compiler on a buggy corpus, collect
1232 // the special terminations (ideally, you don't see them at all -- no false
1233 // negatives) and make the decision on the optimization.
1234 uint32_t Exp = ClForceExperiment;
1235
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001236 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001237 // If initialization order checking is disabled, a simple access to a
1238 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001239 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001240 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001241 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1242 NumOptimizedAccessesToGlobalVar++;
1243 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001244 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001245 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001246
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001247 if (ClOpt && ClOptStack) {
1248 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001249 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001250 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1251 NumOptimizedAccessesToStackVar++;
1252 return;
1253 }
1254 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001255
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001256 if (IsWrite)
1257 NumInstrumentedWrites++;
1258 else
1259 NumInstrumentedReads++;
1260
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001261 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001262 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001263 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1264 Alignment, Granularity, TypeSize, IsWrite,
1265 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001266 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001267 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001268 IsWrite, nullptr, UseCalls, Exp);
1269 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001270}
1271
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001272Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1273 Value *Addr, bool IsWrite,
1274 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001275 Value *SizeArgument,
1276 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001277 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001278 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1279 CallInst *Call = nullptr;
1280 if (SizeArgument) {
1281 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001282 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1283 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001284 else
David Blaikieff6409d2015-05-18 22:13:54 +00001285 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1286 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001287 } else {
1288 if (Exp == 0)
1289 Call =
1290 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1291 else
David Blaikieff6409d2015-05-18 22:13:54 +00001292 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1293 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001294 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001295
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001296 // We don't do Call->setDoesNotReturn() because the BB already has
1297 // UnreachableInst at the end.
1298 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001299 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001300 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001301}
1302
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001303Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001304 Value *ShadowValue,
1305 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001306 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001307 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001308 Value *LastAccessedByte =
1309 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001310 // (Addr & (Granularity - 1)) + size - 1
1311 if (TypeSize / 8 > 1)
1312 LastAccessedByte = IRB.CreateAdd(
1313 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1314 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001315 LastAccessedByte =
1316 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001317 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1318 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1319}
1320
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001321void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001322 Instruction *InsertBefore, Value *Addr,
1323 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001324 Value *SizeArgument, bool UseCalls,
1325 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001326 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001327 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001328 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1329
1330 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001331 if (Exp == 0)
1332 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1333 AddrLong);
1334 else
David Blaikieff6409d2015-05-18 22:13:54 +00001335 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1336 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001337 return;
1338 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001339
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001340 Type *ShadowTy =
1341 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001342 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1343 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1344 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001345 Value *ShadowValue =
1346 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001347
1348 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001349 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001350 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001351
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001352 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001353 // We use branch weights for the slow path check, to indicate that the slow
1354 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001355 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1356 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001357 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001358 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001359 IRB.SetInsertPoint(CheckTerm);
1360 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001361 if (Recover) {
1362 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1363 } else {
1364 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001365 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001366 CrashTerm = new UnreachableInst(*C, CrashBlock);
1367 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1368 ReplaceInstWithInst(CheckTerm, NewTerm);
1369 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001370 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001371 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001372 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001373
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001374 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001375 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001376 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001377}
1378
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001379// Instrument unusual size or unusual alignment.
1380// We can not do it with a single check, so we do 1-byte check for the first
1381// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1382// to report the actual access size.
1383void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001384 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1385 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1386 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001387 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1388 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1389 if (UseCalls) {
1390 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001391 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1392 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001393 else
David Blaikieff6409d2015-05-18 22:13:54 +00001394 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1395 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001396 } else {
1397 Value *LastByte = IRB.CreateIntToPtr(
1398 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1399 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001400 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1401 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001402 }
1403}
1404
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001405void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1406 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001407 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001408 IRBuilder<> IRB(&GlobalInit.front(),
1409 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001410
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001411 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001412 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1413 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001414
1415 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001416 for (auto &BB : GlobalInit.getBasicBlockList())
1417 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001418 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001419}
1420
1421void AddressSanitizerModule::createInitializerPoisonCalls(
1422 Module &M, GlobalValue *ModuleName) {
1423 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1424
1425 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1426 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001427 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001428 ConstantStruct *CS = cast<ConstantStruct>(OP);
1429
1430 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001431 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001432 if (F->getName() == kAsanModuleCtorName) continue;
1433 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1434 // Don't instrument CTORs that will run before asan.module_ctor.
1435 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1436 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001437 }
1438 }
1439}
1440
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001441bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001442 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001443 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001444
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001445 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001446 if (!Ty->isSized()) return false;
1447 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001448 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001449 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001450 // Don't handle ODR linkage types and COMDATs since other modules may be built
1451 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001452 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1453 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1454 G->getLinkage() != GlobalVariable::InternalLinkage)
1455 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001456 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001457 // Two problems with thread-locals:
1458 // - The address of the main thread's copy can't be computed at link-time.
1459 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001460 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001461 // For now, just ignore this Global if the alignment is large.
1462 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001463
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001464 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001465 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001466
Anna Zaks11904602015-06-09 00:58:08 +00001467 // Globals from llvm.metadata aren't emitted, do not instrument them.
1468 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001469 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001470 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001471
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001472 // Do not instrument function pointers to initialization and termination
1473 // routines: dynamic linker will not properly handle redzones.
1474 if (Section.startswith(".preinit_array") ||
1475 Section.startswith(".init_array") ||
1476 Section.startswith(".fini_array")) {
1477 return false;
1478 }
1479
Anna Zaks11904602015-06-09 00:58:08 +00001480 // Callbacks put into the CRT initializer/terminator sections
1481 // should not be instrumented.
1482 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1483 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1484 if (Section.startswith(".CRT")) {
1485 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1486 return false;
1487 }
1488
Kuba Brecka1001bb52014-12-05 22:19:18 +00001489 if (TargetTriple.isOSBinFormatMachO()) {
1490 StringRef ParsedSegment, ParsedSection;
1491 unsigned TAA = 0, StubSize = 0;
1492 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001493 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1494 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001495 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001496
1497 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1498 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1499 // them.
1500 if (ParsedSegment == "__OBJC" ||
1501 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1502 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1503 return false;
1504 }
1505 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1506 // Constant CFString instances are compiled in the following way:
1507 // -- the string buffer is emitted into
1508 // __TEXT,__cstring,cstring_literals
1509 // -- the constant NSConstantString structure referencing that buffer
1510 // is placed into __DATA,__cfstring
1511 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1512 // Moreover, it causes the linker to crash on OS X 10.7
1513 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1514 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1515 return false;
1516 }
1517 // The linker merges the contents of cstring_literals and removes the
1518 // trailing zeroes.
1519 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1520 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1521 return false;
1522 }
1523 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001524 }
1525
1526 return true;
1527}
1528
Ryan Govostes653f9d02016-03-28 20:28:57 +00001529// On Mach-O platforms, we emit global metadata in a separate section of the
1530// binary in order to allow the linker to properly dead strip. This is only
1531// supported on recent versions of ld64.
1532bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001533 if (!ClUseMachOGlobalsSection)
1534 return false;
1535
Ryan Govostes653f9d02016-03-28 20:28:57 +00001536 if (!TargetTriple.isOSBinFormatMachO())
1537 return false;
1538
1539 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1540 return true;
1541 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001542 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001543 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1544 return true;
1545
1546 return false;
1547}
1548
Reid Kleckner01660a32016-11-21 20:40:37 +00001549StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1550 switch (TargetTriple.getObjectFormat()) {
1551 case Triple::COFF: return ".ASAN$GL";
1552 case Triple::ELF: return "asan_globals";
1553 case Triple::MachO: return "__DATA,__asan_globals,regular";
1554 default: break;
1555 }
1556 llvm_unreachable("unsupported object format");
1557}
1558
Alexey Samsonov788381b2012-12-25 12:28:20 +00001559void AddressSanitizerModule::initializeCallbacks(Module &M) {
1560 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001561
Alexey Samsonov788381b2012-12-25 12:28:20 +00001562 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001563 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001564 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001565 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001566 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001567 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001568 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001569
Alexey Samsonov788381b2012-12-25 12:28:20 +00001570 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001571 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001572 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001573 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001574 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001575 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1576 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001577 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001578
1579 // Declare the functions that find globals in a shared object and then invoke
1580 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001581 AsanRegisterImageGlobals =
1582 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1583 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001584 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001585
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001586 AsanUnregisterImageGlobals =
1587 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1588 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001589 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001590}
1591
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001592// Put the metadata and the instrumented global in the same group. This ensures
1593// that the metadata is discarded if the instrumented global is discarded.
1594void AddressSanitizerModule::SetComdatForGlobalMetadata(
1595 GlobalVariable *G, GlobalVariable *Metadata) {
1596 Module &M = *G->getParent();
1597 Comdat *C = G->getComdat();
1598 if (!C) {
1599 if (!G->hasName()) {
1600 // If G is unnamed, it must be internal. Give it an artificial name
1601 // so we can put it in a comdat.
1602 assert(G->hasLocalLinkage());
1603 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1604 }
1605 C = M.getOrInsertComdat(G->getName());
1606 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1607 if (TargetTriple.isOSBinFormatCOFF())
1608 C->setSelectionKind(Comdat::NoDuplicates);
1609 G->setComdat(C);
1610 }
1611
1612 assert(G->hasComdat());
1613 Metadata->setComdat(G->getComdat());
1614}
1615
1616// Create a separate metadata global and put it in the appropriate ASan
1617// global registration section.
1618GlobalVariable *
1619AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1620 StringRef OriginalName) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001621 GlobalVariable *Metadata =
1622 new GlobalVariable(M, Initializer->getType(), false,
1623 GlobalVariable::InternalLinkage, Initializer,
1624 Twine("__asan_global_") +
1625 GlobalValue::getRealLinkageName(OriginalName));
1626 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001627 return Metadata;
1628}
1629
1630IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1631 Function *AsanDtorFunction =
1632 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1633 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1634 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1635 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1636
1637 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1638}
1639
1640void AddressSanitizerModule::InstrumentGlobalsCOFF(
1641 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1642 ArrayRef<Constant *> MetadataInitializers) {
1643 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001644 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001645
1646 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001647 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001648 GlobalVariable *G = ExtendedGlobals[i];
1649 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001650 CreateMetadataGlobal(M, Initializer, G->getName());
1651
1652 // The MSVC linker always inserts padding when linking incrementally. We
1653 // cope with that by aligning each struct to its size, which must be a power
1654 // of two.
1655 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1656 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1657 "global metadata will not be padded appropriately");
1658 Metadata->setAlignment(SizeOfGlobalStruct);
1659
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001660 SetComdatForGlobalMetadata(G, Metadata);
1661 }
1662}
1663
1664void AddressSanitizerModule::InstrumentGlobalsMachO(
1665 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1666 ArrayRef<Constant *> MetadataInitializers) {
1667 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1668
1669 // On recent Mach-O platforms, use a structure which binds the liveness of
1670 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1671 // created to be added to llvm.compiler.used
1672 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1673 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1674
1675 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1676 Constant *Initializer = MetadataInitializers[i];
1677 GlobalVariable *G = ExtendedGlobals[i];
1678 GlobalVariable *Metadata =
1679 CreateMetadataGlobal(M, Initializer, G->getName());
1680
1681 // On recent Mach-O platforms, we emit the global metadata in a way that
1682 // allows the linker to properly strip dead globals.
1683 auto LivenessBinder = ConstantStruct::get(
1684 LivenessTy, Initializer->getAggregateElement(0u),
1685 ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1686 GlobalVariable *Liveness = new GlobalVariable(
1687 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1688 Twine("__asan_binder_") + G->getName());
1689 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1690 LivenessGlobals[i] = Liveness;
1691 }
1692
1693 // Update llvm.compiler.used, adding the new liveness globals. This is
1694 // needed so that during LTO these variables stay alive. The alternative
1695 // would be to have the linker handling the LTO symbols, but libLTO
1696 // current API does not expose access to the section for each symbol.
1697 if (!LivenessGlobals.empty())
1698 appendToCompilerUsed(M, LivenessGlobals);
1699
1700 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1701 // to look up the loaded image that contains it. Second, we can store in it
1702 // whether registration has already occurred, to prevent duplicate
1703 // registration.
1704 //
1705 // common linkage ensures that there is only one global per shared library.
1706 GlobalVariable *RegisteredFlag = new GlobalVariable(
1707 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1708 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1709 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1710
1711 IRB.CreateCall(AsanRegisterImageGlobals,
1712 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1713
1714 // We also need to unregister globals at the end, e.g., when a shared library
1715 // gets closed.
1716 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1717 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1718 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1719}
1720
1721void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1722 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1723 ArrayRef<Constant *> MetadataInitializers) {
1724 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1725 unsigned N = ExtendedGlobals.size();
1726 assert(N > 0);
1727
1728 // On platforms that don't have a custom metadata section, we emit an array
1729 // of global metadata structures.
1730 ArrayType *ArrayOfGlobalStructTy =
1731 ArrayType::get(MetadataInitializers[0]->getType(), N);
1732 auto AllGlobals = new GlobalVariable(
1733 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1734 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1735
1736 IRB.CreateCall(AsanRegisterGlobals,
1737 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1738 ConstantInt::get(IntptrTy, N)});
1739
1740 // We also need to unregister globals at the end, e.g., when a shared library
1741 // gets closed.
1742 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1743 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1744 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1745 ConstantInt::get(IntptrTy, N)});
1746}
1747
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001748// This function replaces all global variables with new variables that have
1749// trailing redzones. It also creates a function that poisons
1750// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001751bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001752 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001753
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001754 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1755
Alexey Samsonova02e6642014-05-29 18:40:48 +00001756 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001757 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001758 }
1759
1760 size_t n = GlobalsToChange.size();
1761 if (n == 0) return false;
1762
Reid Kleckner78565832016-11-29 01:32:21 +00001763 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001764
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001765 // A global is described by a structure
1766 // size_t beg;
1767 // size_t size;
1768 // size_t size_with_redzone;
1769 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001770 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001771 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001772 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001773 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001774 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001775 StructType *GlobalStructTy =
1776 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001777 IntptrTy, IntptrTy, IntptrTy, nullptr);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001778 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1779 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001780
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001781 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001782
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001783 // We shouldn't merge same module names, as this string serves as unique
1784 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001785 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001786 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001787
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001788 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001789 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001790 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001791
1792 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001793 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001794 // Create string holding the global name (use global name from metadata
1795 // if it's available, otherwise just write the name of global variable).
1796 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001797 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001798 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001799
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001800 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001801 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001802 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001803 // MinRZ <= RZ <= kMaxGlobalRedzone
1804 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001805 uint64_t RZ = std::max(
1806 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001807 uint64_t RightRedzoneSize = RZ;
1808 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001809 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001810 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001811 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1812
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001813 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001814 Constant *NewInitializer =
1815 ConstantStruct::get(NewTy, G->getInitializer(),
1816 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001817
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001818 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001819 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1820 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1821 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001822 GlobalVariable *NewGlobal =
1823 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1824 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001825 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001826 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001827
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001828 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1829 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1830 G->isConstant()) {
1831 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1832 if (Seq && Seq->isCString())
1833 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1834 }
1835
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001836 // Transfer the debug info. The payload starts at offset zero so we can
1837 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001838 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001839 G->getDebugInfo(GVs);
1840 for (auto *GV : GVs)
1841 NewGlobal->addDebugInfo(GV);
1842
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001843 Value *Indices2[2];
1844 Indices2[0] = IRB.getInt32(0);
1845 Indices2[1] = IRB.getInt32(0);
1846
1847 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001848 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001849 NewGlobal->takeName(G);
1850 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001851 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001852
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001853 Constant *SourceLoc;
1854 if (!MD.SourceLoc.empty()) {
1855 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1856 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1857 } else {
1858 SourceLoc = ConstantInt::get(IntptrTy, 0);
1859 }
1860
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001861 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1862 GlobalValue *InstrumentedGlobal = NewGlobal;
1863
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001864 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00001865 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1866 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001867 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1868 // Create local alias for NewGlobal to avoid crash on ODR between
1869 // instrumented and non-instrumented libraries.
1870 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1871 NameForGlobal + M.getName(), NewGlobal);
1872
1873 // With local aliases, we need to provide another externally visible
1874 // symbol __odr_asan_XXX to detect ODR violation.
1875 auto *ODRIndicatorSym =
1876 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1877 Constant::getNullValue(IRB.getInt8Ty()),
1878 kODRGenPrefix + NameForGlobal, nullptr,
1879 NewGlobal->getThreadLocalMode());
1880
1881 // Set meaningful attributes for indicator symbol.
1882 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1883 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1884 ODRIndicatorSym->setAlignment(1);
1885 ODRIndicator = ODRIndicatorSym;
1886 InstrumentedGlobal = GA;
1887 }
1888
Reid Kleckner01660a32016-11-21 20:40:37 +00001889 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001890 GlobalStructTy,
1891 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001892 ConstantInt::get(IntptrTy, SizeInBytes),
1893 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1894 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001895 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001896 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1897 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001898
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001899 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001900
Kostya Serebryany20343352012-10-17 13:40:06 +00001901 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00001902
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001903 Initializers[i] = Initializer;
1904 }
Reid Kleckner01660a32016-11-21 20:40:37 +00001905
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001906 if (TargetTriple.isOSBinFormatCOFF()) {
1907 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
1908 } else if (ShouldUseMachOGlobalsSection()) {
1909 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
1910 } else {
1911 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001912 }
1913
Reid Kleckner01660a32016-11-21 20:40:37 +00001914 // Create calls for poisoning before initializers run and unpoisoning after.
1915 if (HasDynamicallyInitializedGlobals)
1916 createInitializerPoisonCalls(M, ModuleName);
1917
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001918 DEBUG(dbgs() << M);
1919 return true;
1920}
1921
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001922bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001923 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001924 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001925 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001926 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001927 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001928 initializeCallbacks(M);
1929
1930 bool Changed = false;
1931
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001932 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1933 if (ClGlobals && !CompileKernel) {
1934 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1935 assert(CtorFunc);
1936 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1937 Changed |= InstrumentGlobals(IRB, M);
1938 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001939
1940 return Changed;
1941}
1942
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001943void AddressSanitizer::initializeCallbacks(Module &M) {
1944 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001945 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001946 // IsWrite, TypeSize and Exp are encoded in the function name.
1947 for (int Exp = 0; Exp < 2; Exp++) {
1948 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1949 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1950 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001951 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001952 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001953 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001954 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001955 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001956 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001957 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1958 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001959 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001960 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001961 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1962 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1963 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001964 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001965 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001966 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001967 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001968 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001969 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001970 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001971 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1972 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001973 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001974 }
1975 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001976
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001977 const std::string MemIntrinCallbackPrefix =
1978 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001979 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001980 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001981 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001982 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001983 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001984 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001985 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001986 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001987 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001988
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001989 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001990 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001991
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001992 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001993 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001994 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001995 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001996 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1997 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1998 StringRef(""), StringRef(""),
1999 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002000}
2001
2002// virtual
2003bool AddressSanitizer::doInitialization(Module &M) {
2004 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00002005
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002006 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002007
2008 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002009 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002010 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002011 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002012
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002013 if (!CompileKernel) {
2014 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00002015 createSanitizerCtorAndInitFunctions(
2016 M, kAsanModuleCtorName, kAsanInitName,
2017 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002018 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2019 }
2020 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002021 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002022}
2023
Keno Fischere03fae42015-12-05 14:42:34 +00002024bool AddressSanitizer::doFinalization(Module &M) {
2025 GlobalsMD.reset();
2026 return false;
2027}
2028
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002029bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2030 // For each NSObject descendant having a +load method, this method is invoked
2031 // by the ObjC runtime before any of the static constructors is called.
2032 // Therefore we need to instrument such methods with a call to __asan_init
2033 // at the beginning in order to initialize our runtime before any access to
2034 // the shadow memory.
2035 // We cannot just ignore these methods, because they may call other
2036 // instrumented functions.
2037 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002038 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002039 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002040 return true;
2041 }
2042 return false;
2043}
2044
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002045void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2046 // Generate code only when dynamic addressing is needed.
2047 if (Mapping.Offset != kDynamicShadowSentinel)
2048 return;
2049
2050 IRBuilder<> IRB(&F.front().front());
2051 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2052 kAsanShadowMemoryDynamicAddress, IntptrTy);
2053 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2054}
2055
Reid Kleckner2f907552015-07-21 17:40:14 +00002056void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2057 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2058 // to it as uninteresting. This assumes we haven't started processing allocas
2059 // yet. This check is done up front because iterating the use list in
2060 // isInterestingAlloca would be algorithmically slower.
2061 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2062
2063 // Try to get the declaration of llvm.localescape. If it's not in the module,
2064 // we can exit early.
2065 if (!F.getParent()->getFunction("llvm.localescape")) return;
2066
2067 // Look for a call to llvm.localescape call in the entry block. It can't be in
2068 // any other block.
2069 for (Instruction &I : F.getEntryBlock()) {
2070 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2071 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2072 // We found a call. Mark all the allocas passed in as uninteresting.
2073 for (Value *Arg : II->arg_operands()) {
2074 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2075 assert(AI && AI->isStaticAlloca() &&
2076 "non-static alloca arg to localescape");
2077 ProcessedAllocas[AI] = false;
2078 }
2079 break;
2080 }
2081 }
2082}
2083
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002084bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002085 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002086 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002087 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002088 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002089
Etienne Bergeron78582b22016-09-15 15:45:05 +00002090 bool FunctionModified = false;
2091
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002092 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002093 // This function needs to be called even if the function body is not
2094 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002095 if (maybeInsertAsanInitAtFunctionEntry(F))
2096 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002097
2098 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002099 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002100
Etienne Bergeron752f8832016-09-14 17:18:37 +00002101 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2102
2103 initializeCallbacks(*F.getParent());
2104 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002105
Reid Kleckner2f907552015-07-21 17:40:14 +00002106 FunctionStateRAII CleanupObj(this);
2107
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002108 maybeInsertDynamicShadowAtFunctionEntry(F);
2109
Reid Kleckner2f907552015-07-21 17:40:14 +00002110 // We can't instrument allocas used with llvm.localescape. Only static allocas
2111 // can be passed to that intrinsic.
2112 markEscapedLocalAllocas(F);
2113
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002114 // We want to instrument every address only once per basic block (unless there
2115 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002116 SmallSet<Value *, 16> TempsToInstrument;
2117 SmallVector<Instruction *, 16> ToInstrument;
2118 SmallVector<Instruction *, 8> NoReturnCalls;
2119 SmallVector<BasicBlock *, 16> AllBlocks;
2120 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002121 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002122 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002123 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002124 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002125 const TargetLibraryInfo *TLI =
2126 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002127
2128 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002129 for (auto &BB : F) {
2130 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002131 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002132 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002133 for (auto &Inst : BB) {
2134 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002135 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002136 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002137 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002138 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002139 // If we have a mask, skip instrumentation if we've already
2140 // instrumented the full object. But don't add to TempsToInstrument
2141 // because we might get another load/store with a different mask.
2142 if (MaybeMask) {
2143 if (TempsToInstrument.count(Addr))
2144 continue; // We've seen this (whole) temp in the current BB.
2145 } else {
2146 if (!TempsToInstrument.insert(Addr).second)
2147 continue; // We've seen this temp in the current BB.
2148 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002149 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002150 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002151 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2152 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002153 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002154 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002155 // ok, take it.
2156 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002157 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002158 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002159 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002160 // A call inside BB.
2161 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002162 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002163 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002164 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2165 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002166 continue;
2167 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002168 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002169 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002170 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002171 }
2172 }
2173
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002174 bool UseCalls =
2175 CompileKernel ||
2176 (ClInstrumentationWithCallsThreshold >= 0 &&
2177 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002178 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002179 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
2180 /*RoundToAlign=*/true);
2181
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002182 // Instrument.
2183 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002184 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002185 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2186 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002187 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002188 instrumentMop(ObjSizeVis, Inst, UseCalls,
2189 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002190 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002191 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002192 }
2193 NumInstrumented++;
2194 }
2195
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002196 FunctionStackPoisoner FSP(F, *this);
2197 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002198
2199 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2200 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002201 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002202 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002203 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002204 }
2205
Alexey Samsonova02e6642014-05-29 18:40:48 +00002206 for (auto Inst : PointerComparisonsOrSubtracts) {
2207 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002208 NumInstrumented++;
2209 }
2210
Etienne Bergeron78582b22016-09-15 15:45:05 +00002211 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2212 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002213
Etienne Bergeron78582b22016-09-15 15:45:05 +00002214 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2215 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002216
Etienne Bergeron78582b22016-09-15 15:45:05 +00002217 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002218}
2219
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002220// Workaround for bug 11395: we don't want to instrument stack in functions
2221// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2222// FIXME: remove once the bug 11395 is fixed.
2223bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2224 if (LongSize != 32) return false;
2225 CallInst *CI = dyn_cast<CallInst>(I);
2226 if (!CI || !CI->isInlineAsm()) return false;
2227 if (CI->getNumArgOperands() <= 5) return false;
2228 // We have inline assembly with quite a few arguments.
2229 return true;
2230}
2231
2232void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2233 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002234 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2235 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002236 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2237 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2238 IntptrTy, nullptr));
2239 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002240 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2241 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002242 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002243 if (ASan.UseAfterScope) {
2244 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2245 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2246 IntptrTy, IntptrTy, nullptr));
2247 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2248 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2249 IntptrTy, IntptrTy, nullptr));
2250 }
2251
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002252 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2253 std::ostringstream Name;
2254 Name << kAsanSetShadowPrefix;
2255 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2256 AsanSetShadowFunc[Val] =
2257 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2258 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002259 }
2260
Yury Gribov98b18592015-05-28 07:51:49 +00002261 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2262 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2263 AsanAllocasUnpoisonFunc =
2264 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2265 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002266}
2267
Vitaly Buka793913c2016-08-29 18:17:21 +00002268void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2269 ArrayRef<uint8_t> ShadowBytes,
2270 size_t Begin, size_t End,
2271 IRBuilder<> &IRB,
2272 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002273 if (Begin >= End)
2274 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002275
2276 const size_t LargestStoreSizeInBytes =
2277 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2278
2279 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2280
2281 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002282 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2283 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2284 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002285 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002286 if (!ShadowMask[i]) {
2287 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002288 ++i;
2289 continue;
2290 }
2291
2292 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2293 // Fit store size into the range.
2294 while (StoreSizeInBytes > End - i)
2295 StoreSizeInBytes /= 2;
2296
2297 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002298 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002299 while (j <= StoreSizeInBytes / 2)
2300 StoreSizeInBytes /= 2;
2301 }
2302
2303 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002304 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2305 if (IsLittleEndian)
2306 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2307 else
2308 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002309 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002310
2311 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2312 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002313 IRB.CreateAlignedStore(
2314 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002315
2316 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002317 }
2318}
2319
Vitaly Buka793913c2016-08-29 18:17:21 +00002320void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2321 ArrayRef<uint8_t> ShadowBytes,
2322 IRBuilder<> &IRB, Value *ShadowBase) {
2323 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2324}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002325
Vitaly Buka793913c2016-08-29 18:17:21 +00002326void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2327 ArrayRef<uint8_t> ShadowBytes,
2328 size_t Begin, size_t End,
2329 IRBuilder<> &IRB, Value *ShadowBase) {
2330 assert(ShadowMask.size() == ShadowBytes.size());
2331 size_t Done = Begin;
2332 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2333 if (!ShadowMask[i]) {
2334 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002335 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002336 }
2337 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002338 if (!AsanSetShadowFunc[Val])
2339 continue;
2340
2341 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002342 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002343 }
2344
2345 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002346 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002347 IRB.CreateCall(AsanSetShadowFunc[Val],
2348 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2349 ConstantInt::get(IntptrTy, j - i)});
2350 Done = j;
2351 }
2352 }
2353
Vitaly Buka793913c2016-08-29 18:17:21 +00002354 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002355}
2356
Kostya Serebryany6805de52013-09-10 13:16:56 +00002357// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2358// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2359static int StackMallocSizeClass(uint64_t LocalStackSize) {
2360 assert(LocalStackSize <= kMaxStackMallocSize);
2361 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002362 for (int i = 0;; i++, MaxSize *= 2)
2363 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002364 llvm_unreachable("impossible LocalStackSize");
2365}
2366
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002367PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2368 Value *ValueIfTrue,
2369 Instruction *ThenTerm,
2370 Value *ValueIfFalse) {
2371 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2372 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2373 PHI->addIncoming(ValueIfFalse, CondBlock);
2374 BasicBlock *ThenBlock = ThenTerm->getParent();
2375 PHI->addIncoming(ValueIfTrue, ThenBlock);
2376 return PHI;
2377}
2378
2379Value *FunctionStackPoisoner::createAllocaForLayout(
2380 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2381 AllocaInst *Alloca;
2382 if (Dynamic) {
2383 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2384 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2385 "MyAlloca");
2386 } else {
2387 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2388 nullptr, "MyAlloca");
2389 assert(Alloca->isStaticAlloca());
2390 }
2391 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2392 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2393 Alloca->setAlignment(FrameAlignment);
2394 return IRB.CreatePointerCast(Alloca, IntptrTy);
2395}
2396
Yury Gribov98b18592015-05-28 07:51:49 +00002397void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2398 BasicBlock &FirstBB = *F.begin();
2399 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2400 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2401 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2402 DynamicAllocaLayout->setAlignment(32);
2403}
2404
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002405void FunctionStackPoisoner::processDynamicAllocas() {
2406 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2407 assert(DynamicAllocaPoisonCallVec.empty());
2408 return;
2409 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002410
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002411 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2412 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002413 assert(APC.InsBefore);
2414 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002415 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002416 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002417
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002418 IRBuilder<> IRB(APC.InsBefore);
2419 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002420 // Dynamic allocas will be unpoisoned unconditionally below in
2421 // unpoisonDynamicAllocas.
2422 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002423 }
2424
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002425 // Handle dynamic allocas.
2426 createDynamicAllocasInitStorage();
2427 for (auto &AI : DynamicAllocaVec)
2428 handleDynamicAllocaCall(AI);
2429 unpoisonDynamicAllocas();
2430}
Yury Gribov98b18592015-05-28 07:51:49 +00002431
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002432void FunctionStackPoisoner::processStaticAllocas() {
2433 if (AllocaVec.empty()) {
2434 assert(StaticAllocaPoisonCallVec.empty());
2435 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002436 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002437
Kostya Serebryany6805de52013-09-10 13:16:56 +00002438 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002439 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002440 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002441 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002442
2443 Instruction *InsBefore = AllocaVec[0];
2444 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002445 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002446
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002447 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2448 // debug info is broken, because only entry-block allocas are treated as
2449 // regular stack slots.
2450 auto InsBeforeB = InsBefore->getParent();
2451 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002452 for (auto *AI : StaticAllocasToMoveUp)
2453 if (AI->getParent() == InsBeforeB)
2454 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002455
Reid Kleckner2f907552015-07-21 17:40:14 +00002456 // If we have a call to llvm.localescape, keep it in the entry block.
2457 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2458
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002459 SmallVector<ASanStackVariableDescription, 16> SVD;
2460 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002461 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002462 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002463 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002464 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002465 AI->getAlignment(),
2466 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002467 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002468 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002469 SVD.push_back(D);
2470 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002471
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002472 // Minimal header size (left redzone) is 4 pointers,
2473 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2474 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002475 const ASanStackFrameLayout &L =
2476 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002477
Vitaly Buka5910a922016-10-18 23:29:52 +00002478 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2479 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2480 for (auto &Desc : SVD)
2481 AllocaToSVDMap[Desc.AI] = &Desc;
2482
2483 // Update SVD with information from lifetime intrinsics.
2484 for (const auto &APC : StaticAllocaPoisonCallVec) {
2485 assert(APC.InsBefore);
2486 assert(APC.AI);
2487 assert(ASan.isInterestingAlloca(*APC.AI));
2488 assert(APC.AI->isStaticAlloca());
2489
2490 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2491 Desc.LifetimeSize = Desc.Size;
2492 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2493 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2494 if (LifetimeLoc->getFile() == FnLoc->getFile())
2495 if (unsigned Line = LifetimeLoc->getLine())
2496 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2497 }
2498 }
2499 }
2500
2501 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2502 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002503 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002504 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2505 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002506 bool DoDynamicAlloca = ClDynamicAllocaStack;
2507 // Don't do dynamic alloca or stack malloc if:
2508 // 1) There is inline asm: too often it makes assumptions on which registers
2509 // are available.
2510 // 2) There is a returns_twice call (typically setjmp), which is
2511 // optimization-hostile, and doesn't play well with introduced indirect
2512 // register-relative calculation of local variable addresses.
2513 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2514 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002515
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002516 Value *StaticAlloca =
2517 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2518
2519 Value *FakeStack;
2520 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002521
2522 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002523 // void *FakeStack = __asan_option_detect_stack_use_after_return
2524 // ? __asan_stack_malloc_N(LocalStackSize)
2525 // : nullptr;
2526 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002527 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2528 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2529 Value *UseAfterReturnIsEnabled =
2530 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002531 Constant::getNullValue(IRB.getInt32Ty()));
2532 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002533 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002534 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002535 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002536 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2537 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2538 Value *FakeStackValue =
2539 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2540 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002541 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002542 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002543 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002544 ConstantInt::get(IntptrTy, 0));
2545
2546 Value *NoFakeStack =
2547 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2548 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2549 IRBIf.SetInsertPoint(Term);
2550 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2551 Value *AllocaValue =
2552 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2553 IRB.SetInsertPoint(InsBefore);
2554 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2555 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2556 } else {
2557 // void *FakeStack = nullptr;
2558 // void *LocalStackBase = alloca(LocalStackSize);
2559 FakeStack = ConstantInt::get(IntptrTy, 0);
2560 LocalStackBase =
2561 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002562 }
2563
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002564 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002565 for (const auto &Desc : SVD) {
2566 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002567 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002568 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002569 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002570 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002571 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002572 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002573
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002574 // The left-most redzone has enough space for at least 4 pointers.
2575 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002576 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2577 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2578 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002579 // Write the frame description constant to redzone[1].
2580 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002581 IRB.CreateAdd(LocalStackBase,
2582 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2583 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002584 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002585 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002586 /*AllowMerging*/ true);
2587 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002588 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002589 // Write the PC to redzone[2].
2590 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002591 IRB.CreateAdd(LocalStackBase,
2592 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2593 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002594 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002595
Vitaly Buka793913c2016-08-29 18:17:21 +00002596 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2597
2598 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002599 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002600 // As mask we must use most poisoned case: red zones and after scope.
2601 // As bytes we can use either the same or just red zones only.
2602 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2603
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002604 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002605 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2606
2607 // Poison static allocas near lifetime intrinsics.
2608 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002609 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002610 assert(Desc.Offset % L.Granularity == 0);
2611 size_t Begin = Desc.Offset / L.Granularity;
2612 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2613
2614 IRBuilder<> IRB(APC.InsBefore);
2615 copyToShadow(ShadowAfterScope,
2616 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2617 IRB, ShadowBase);
2618 }
2619 }
2620
2621 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002622 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002623
Kostya Serebryany530e2072013-12-23 14:15:08 +00002624 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002625 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002626 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002627 // Mark the current frame as retired.
2628 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2629 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002630 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002631 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002632 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002633 // // In use-after-return mode, poison the whole stack frame.
2634 // if StackMallocIdx <= 4
2635 // // For small sizes inline the whole thing:
2636 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002637 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002638 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002639 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002640 // else
2641 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002642 Value *Cmp =
2643 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002644 TerminatorInst *ThenTerm, *ElseTerm;
2645 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2646
2647 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002648 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002649 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002650 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2651 kAsanStackUseAfterReturnMagic);
2652 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2653 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002654 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002655 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002656 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2657 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2658 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2659 IRBPoison.CreateStore(
2660 Constant::getNullValue(IRBPoison.getInt8Ty()),
2661 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2662 } else {
2663 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002664 IRBPoison.CreateCall(
2665 AsanStackFreeFunc[StackMallocIdx],
2666 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002667 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002668
2669 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002670 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002671 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002672 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002673 }
2674 }
2675
Kostya Serebryany09959942012-10-19 06:20:53 +00002676 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002677 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002678}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002679
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002680void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002681 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002682 // For now just insert the call to ASan runtime.
2683 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2684 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002685 IRB.CreateCall(
2686 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2687 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002688}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002689
2690// Handling llvm.lifetime intrinsics for a given %alloca:
2691// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2692// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2693// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2694// could be poisoned by previous llvm.lifetime.end instruction, as the
2695// variable may go in and out of scope several times, e.g. in loops).
2696// (3) if we poisoned at least one %alloca in a function,
2697// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002698
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002699AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2700 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002701 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002702 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002703 // See if we've already calculated (or started to calculate) alloca for a
2704 // given value.
2705 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002706 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002707 // Store 0 while we're calculating alloca for value V to avoid
2708 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002709 AllocaForValue[V] = nullptr;
2710 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002711 if (CastInst *CI = dyn_cast<CastInst>(V))
2712 Res = findAllocaForValue(CI->getOperand(0));
2713 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002714 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002715 // Allow self-referencing phi-nodes.
2716 if (IncValue == PN) continue;
2717 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2718 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002719 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2720 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002721 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002722 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002723 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2724 Res = findAllocaForValue(EP->getPointerOperand());
2725 } else {
2726 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002727 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002728 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002729 return Res;
2730}
Yury Gribov55441bb2014-11-21 10:29:50 +00002731
Yury Gribov98b18592015-05-28 07:51:49 +00002732void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002733 IRBuilder<> IRB(AI);
2734
Yury Gribov55441bb2014-11-21 10:29:50 +00002735 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2736 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2737
2738 Value *Zero = Constant::getNullValue(IntptrTy);
2739 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2740 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002741
2742 // Since we need to extend alloca with additional memory to locate
2743 // redzones, and OldSize is number of allocated blocks with
2744 // ElementSize size, get allocated memory size in bytes by
2745 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002746 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002747 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002748 Value *OldSize =
2749 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2750 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002751
2752 // PartialSize = OldSize % 32
2753 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2754
2755 // Misalign = kAllocaRzSize - PartialSize;
2756 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2757
2758 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2759 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2760 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2761
2762 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2763 // Align is added to locate left redzone, PartialPadding for possible
2764 // partial redzone and kAllocaRzSize for right redzone respectively.
2765 Value *AdditionalChunkSize = IRB.CreateAdd(
2766 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2767
2768 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2769
2770 // Insert new alloca with new NewSize and Align params.
2771 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2772 NewAlloca->setAlignment(Align);
2773
2774 // NewAddress = Address + Align
2775 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2776 ConstantInt::get(IntptrTy, Align));
2777
Yury Gribov98b18592015-05-28 07:51:49 +00002778 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002779 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002780
2781 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2782 // for unpoisoning stuff.
2783 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2784
Yury Gribov55441bb2014-11-21 10:29:50 +00002785 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2786
Yury Gribov98b18592015-05-28 07:51:49 +00002787 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002788 AI->replaceAllUsesWith(NewAddressPtr);
2789
Yury Gribov98b18592015-05-28 07:51:49 +00002790 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002791 AI->eraseFromParent();
2792}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002793
2794// isSafeAccess returns true if Addr is always inbounds with respect to its
2795// base object. For example, it is a field access or an array access with
2796// constant inbounds index.
2797bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2798 Value *Addr, uint64_t TypeSize) const {
2799 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2800 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002801 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002802 int64_t Offset = SizeOffset.second.getSExtValue();
2803 // Three checks are required to ensure safety:
2804 // . Offset >= 0 (since the offset is given from the base ptr)
2805 // . Size >= Offset (unsigned)
2806 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002807 return Offset >= 0 && Size >= uint64_t(Offset) &&
2808 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002809}