blob: 53dd96e205c026c9ed07111aacf1eb4ac1616207 [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>
58#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000061
62using namespace llvm;
63
Chandler Carruth964daaa2014-04-22 02:55:47 +000064#define DEBUG_TYPE "asan"
65
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066static const uint64_t kDefaultShadowScale = 3;
67static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
68static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000069static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
70static const uint64_t kIOSShadowOffset64 = 0x120200000;
71static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
72static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000073static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000074static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000075static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000076static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000077static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000078static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000079static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000080static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
81static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000082static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron70684f92016-06-21 15:07:29 +000083// TODO(wwchrome): Experimental for asan Win64, may change.
84static const uint64_t kWindowsShadowOffset64 = 0x1ULL << 45; // 32TB.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000085
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000086static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087static const size_t kMaxStackMallocSize = 1 << 16; // 64K
88static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
89static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
90
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanModuleCtorName = "asan.module_ctor";
92static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000093static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000094static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000096static const char *const kAsanUnregisterGlobalsName =
97 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000098static const char *const kAsanRegisterImageGlobalsName =
99 "__asan_register_image_globals";
100static const char *const kAsanUnregisterImageGlobalsName =
101 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
103static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000104static const char *const kAsanInitName = "__asan_init";
105static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000106 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000107static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
108static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000109static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000110static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000111static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
112static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000113static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000114static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000115static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000116static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000117static const char *const kAsanPoisonStackMemoryName =
118 "__asan_poison_stack_memory";
119static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000120 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000121static const char *const kAsanGlobalsRegisteredFlagName =
122 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000123
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000124static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000125 "__asan_option_detect_stack_use_after_return";
126
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000127static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
128static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000129
Kostya Serebryany874dae62012-07-16 16:15:40 +0000130// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
131static const size_t kNumberOfAccessSizes = 5;
132
Yury Gribov55441bb2014-11-21 10:29:50 +0000133static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000134
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000135// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000136static cl::opt<bool> ClEnableKasan(
137 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
138 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000139static cl::opt<bool> ClRecover(
140 "asan-recover",
141 cl::desc("Enable recovery mode (continue-after-error)."),
142 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000143
144// This flag may need to be replaced with -f[no-]asan-reads.
145static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000146 cl::desc("instrument read instructions"),
147 cl::Hidden, cl::init(true));
148static cl::opt<bool> ClInstrumentWrites(
149 "asan-instrument-writes", cl::desc("instrument write instructions"),
150 cl::Hidden, cl::init(true));
151static cl::opt<bool> ClInstrumentAtomics(
152 "asan-instrument-atomics",
153 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
154 cl::init(true));
155static cl::opt<bool> ClAlwaysSlowPath(
156 "asan-always-slow-path",
157 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
158 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000159// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000160// in any given BB. Normally, this should be set to unlimited (INT_MAX),
161// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
162// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000163static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
164 "asan-max-ins-per-bb", cl::init(10000),
165 cl::desc("maximal number of instructions to instrument in any given BB"),
166 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000167// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000168static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
169 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000170static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
171 "asan-max-inline-poisoning-size",
172 cl::desc(
173 "Inline shadow poisoning for blocks up to the given size in bytes."),
174 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000175static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000176 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000177 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000178static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
179 cl::desc("Check stack-use-after-scope"),
180 cl::Hidden, cl::init(false));
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000181static cl::opt<bool> ClExperimentalPoisoning(
182 "asan-experimental-poisoning",
183 cl::desc("Enable experimental red zones and scope poisoning"), cl::Hidden,
184 cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185// This flag may need to be replaced with -f[no]asan-globals.
186static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000187 cl::desc("Handle global objects"), cl::Hidden,
188 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000189static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc("Handle C++ initializer order"),
191 cl::Hidden, cl::init(true));
192static cl::opt<bool> ClInvalidPointerPairs(
193 "asan-detect-invalid-pointer-pair",
194 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
195 cl::init(false));
196static cl::opt<unsigned> ClRealignStack(
197 "asan-realign-stack",
198 cl::desc("Realign stack to the value of this flag (power of two)"),
199 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000200static cl::opt<int> ClInstrumentationWithCallsThreshold(
201 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000202 cl::desc(
203 "If the function being instrumented contains more than "
204 "this number of memory accesses, use callbacks instead of "
205 "inline checks (-1 means never use callbacks)."),
206 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000207static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000208 "asan-memory-access-callback-prefix",
209 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
210 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000211static cl::opt<bool>
212 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
213 cl::desc("instrument dynamic allocas"),
214 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000215static cl::opt<bool> ClSkipPromotableAllocas(
216 "asan-skip-promotable-allocas",
217 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
218 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000219
220// These flags allow to change the shadow mapping.
221// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000222// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000223static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224 cl::desc("scale of asan shadow mapping"),
225 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000226static cl::opt<unsigned long long> ClMappingOffset(
227 "asan-mapping-offset",
228 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
229 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000230
231// Optimization flags. Not user visible, used mostly for testing
232// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000233static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
234 cl::Hidden, cl::init(true));
235static cl::opt<bool> ClOptSameTemp(
236 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
237 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000238static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000239 cl::desc("Don't instrument scalar globals"),
240 cl::Hidden, cl::init(true));
241static cl::opt<bool> ClOptStack(
242 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
243 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000244
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000245static cl::opt<bool> ClDynamicAllocaStack(
246 "asan-stack-dynamic-alloca",
247 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000248 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000249
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000250static cl::opt<uint32_t> ClForceExperiment(
251 "asan-force-experiment",
252 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
253 cl::init(0));
254
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000255static cl::opt<bool>
256 ClUsePrivateAliasForGlobals("asan-use-private-alias",
257 cl::desc("Use private aliases for global"
258 " variables"),
259 cl::Hidden, cl::init(false));
260
Ryan Govostese51401b2016-07-05 21:53:08 +0000261static cl::opt<bool>
262 ClUseMachOGlobalsSection("asan-globals-live-support",
263 cl::desc("Use linker features to support dead "
264 "code stripping of globals "
265 "(Mach-O only)"),
266 cl::Hidden, cl::init(false));
267
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000268// Debug flags.
269static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
270 cl::init(0));
271static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
272 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000273static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
274 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000275static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
276 cl::Hidden, cl::init(-1));
277static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
278 cl::Hidden, cl::init(-1));
279
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000280STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
281STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000282STATISTIC(NumOptimizedAccessesToGlobalVar,
283 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284STATISTIC(NumOptimizedAccessesToStackVar,
285 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000286
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000287namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000288/// Frontend-provided metadata for source location.
289struct LocationMetadata {
290 StringRef Filename;
291 int LineNo;
292 int ColumnNo;
293
294 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
295
296 bool empty() const { return Filename.empty(); }
297
298 void parse(MDNode *MDN) {
299 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000300 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
301 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000302 LineNo =
303 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
304 ColumnNo =
305 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000306 }
307};
308
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000309/// Frontend-provided metadata for global variables.
310class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000311 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000312 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000313 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000314 LocationMetadata SourceLoc;
315 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000316 bool IsDynInit;
317 bool IsBlacklisted;
318 };
319
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000320 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000321
Keno Fischere03fae42015-12-05 14:42:34 +0000322 void reset() {
323 inited_ = false;
324 Entries.clear();
325 }
326
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000327 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000328 assert(!inited_);
329 inited_ = true;
330 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000331 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000332 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000333 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000334 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000335 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000336 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000337 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000338 // We can already have an entry for GV if it was merged with another
339 // global.
340 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000341 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
342 E.SourceLoc.parse(Loc);
343 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
344 E.Name = Name->getString();
345 ConstantInt *IsDynInit =
346 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000347 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000348 ConstantInt *IsBlacklisted =
349 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000350 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000351 }
352 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000353
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000354 /// Returns metadata entry for a given global.
355 Entry get(GlobalVariable *G) const {
356 auto Pos = Entries.find(G);
357 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000358 }
359
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000360 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000361 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000362 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000363};
364
Alexey Samsonov1345d352013-01-16 13:23:28 +0000365/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000366/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000367struct ShadowMapping {
368 int Scale;
369 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000370 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000371};
372
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000373static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
374 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000375 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000376 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000377 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
378 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000379 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
380 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000381 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000382 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000383 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000384 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
385 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000386 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
387 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000388 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000389 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000390
391 ShadowMapping Mapping;
392
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000393 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000394 // Android is always PIE, which means that the beginning of the address
395 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000396 if (IsAndroid)
397 Mapping.Offset = 0;
398 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000399 Mapping.Offset = kMIPS32_ShadowOffset32;
400 else if (IsFreeBSD)
401 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000402 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000403 // If we're targeting iOS and x86, the binary is built for iOS simulator.
404 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000405 else if (IsWindows)
406 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000407 else
408 Mapping.Offset = kDefaultShadowOffset32;
409 } else { // LongSize == 64
410 if (IsPPC64)
411 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000412 else if (IsSystemZ)
413 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000414 else if (IsFreeBSD)
415 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000416 else if (IsLinux && IsX86_64) {
417 if (IsKasan)
418 Mapping.Offset = kLinuxKasan_ShadowOffset64;
419 else
420 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000421 } else if (IsWindows && IsX86_64) {
422 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000423 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000424 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000425 else if (IsIOS)
426 // If we're targeting iOS and x86, the binary is built for iOS simulator.
427 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000428 else if (IsAArch64)
429 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000430 else
431 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000432 }
433
434 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000435 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000436 Mapping.Scale = ClMappingScale;
437 }
438
Ryan Govostes3f37df02016-05-06 10:25:22 +0000439 if (ClMappingOffset.getNumOccurrences() > 0) {
440 Mapping.Offset = ClMappingOffset;
441 }
442
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000443 // OR-ing shadow offset if more efficient (at least on x86) if the offset
444 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000445 // offset is not necessary 1/8-th of the address space. On SystemZ,
446 // we could OR the constant in a single instruction, but it's more
447 // efficient to load it once and use indexed addressing.
448 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000449 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000450
Alexey Samsonov1345d352013-01-16 13:23:28 +0000451 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000452}
453
Alexey Samsonov1345d352013-01-16 13:23:28 +0000454static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000455 // Redzone used for stack and globals is at least 32 bytes.
456 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000457 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000458}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000459
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000460/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000461struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000462 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
463 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000464 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000465 Recover(Recover || ClRecover),
466 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000467 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
468 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000469 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000470 return "AddressSanitizerFunctionPass";
471 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000472 void getAnalysisUsage(AnalysisUsage &AU) const override {
473 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000474 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000475 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000476 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000477 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000478 if (AI.isArrayAllocation()) {
479 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000480 assert(CI && "non-constant array size");
481 ArraySize = CI->getZExtValue();
482 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000483 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000484 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000485 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000486 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000487 }
488 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000489 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000490
Anna Zaks8ed1d812015-02-27 03:12:36 +0000491 /// If it is an interesting memory access, return the PointerOperand
492 /// and set IsWrite/Alignment. Otherwise return nullptr.
493 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000494 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000495 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000496 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000497 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000498 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
499 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000500 Value *SizeArgument, bool UseCalls, uint32_t Exp);
501 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
502 uint32_t TypeSize, bool IsWrite,
503 Value *SizeArgument, bool UseCalls,
504 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000505 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
506 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000507 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000508 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000509 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000510 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000511 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000512 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000513 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000514 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000515 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000516 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000517 static char ID; // Pass identification, replacement for typeid
518
Yury Gribov3ae427d2014-12-01 08:47:58 +0000519 DominatorTree &getDominatorTree() const { return *DT; }
520
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000521 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000522 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000523
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000524 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000525 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000526 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
527 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000528
Reid Kleckner2f907552015-07-21 17:40:14 +0000529 /// Helper to cleanup per-function state.
530 struct FunctionStateRAII {
531 AddressSanitizer *Pass;
532 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
533 assert(Pass->ProcessedAllocas.empty() &&
534 "last pass forgot to clear cache");
535 }
536 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
537 };
538
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000539 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000540 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000541 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000542 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000543 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000544 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000545 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000546 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000547 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000548 Function *AsanCtorFunction = nullptr;
549 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000550 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000551 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000552 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
553 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
554 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
555 // This array is indexed by AccessIsWrite and Experiment.
556 Function *AsanErrorCallbackSized[2][2];
557 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000558 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000559 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000560 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000561 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000562
563 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000564};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000565
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000566class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000567 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000568 explicit AddressSanitizerModule(bool CompileKernel = false,
569 bool Recover = false)
570 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
571 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000572 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000573 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000574 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000575
Kostya Serebryany20a79972012-11-22 03:18:50 +0000576 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000577 void initializeCallbacks(Module &M);
578
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000579 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000580 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000581 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000582 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000583 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000584 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000585 return RedzoneSizeForScale(Mapping.Scale);
586 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000587
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000588 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000589 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000590 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000591 Type *IntptrTy;
592 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000593 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000594 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000595 Function *AsanPoisonGlobals;
596 Function *AsanUnpoisonGlobals;
597 Function *AsanRegisterGlobals;
598 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000599 Function *AsanRegisterImageGlobals;
600 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000601};
602
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000603// Stack poisoning does not play well with exception handling.
604// When an exception is thrown, we essentially bypass the code
605// that unpoisones the stack. This is why the run-time library has
606// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
607// stack in the interceptor. This however does not work inside the
608// actual function which catches the exception. Most likely because the
609// compiler hoists the load of the shadow value somewhere too high.
610// This causes asan to report a non-existing bug on 453.povray.
611// It sounds like an LLVM bug.
612struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
613 Function &F;
614 AddressSanitizer &ASan;
615 DIBuilder DIB;
616 LLVMContext *C;
617 Type *IntptrTy;
618 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000619 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000620
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000621 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000622 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000623 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000624 unsigned StackAlignment;
625
Kostya Serebryany6805de52013-09-10 13:16:56 +0000626 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000627 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000628 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000629 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000630 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000631
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000632 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
633 struct AllocaPoisonCall {
634 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000635 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000636 uint64_t Size;
637 bool DoPoison;
638 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000639 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
640 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000641
Yury Gribov98b18592015-05-28 07:51:49 +0000642 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
643 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
644 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000645 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000646
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000647 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000648 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000649 AllocaForValueMapTy AllocaForValue;
650
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000651 bool HasNonEmptyInlineAsm = false;
652 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000653 std::unique_ptr<CallInst> EmptyInlineAsm;
654
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000655 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000656 : F(F),
657 ASan(ASan),
658 DIB(*F.getParent(), /*AllowUnresolved*/ false),
659 C(ASan.C),
660 IntptrTy(ASan.IntptrTy),
661 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
662 Mapping(ASan.Mapping),
663 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000664 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000665
666 bool runOnFunction() {
667 if (!ClStack) return false;
668 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000669 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000670
Yury Gribov55441bb2014-11-21 10:29:50 +0000671 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000672
673 initializeCallbacks(*F.getParent());
674
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000675 processDynamicAllocas();
676 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000677
678 if (ClDebugStack) {
679 DEBUG(dbgs() << F);
680 }
681 return true;
682 }
683
Yury Gribov55441bb2014-11-21 10:29:50 +0000684 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000685 // poisoned red zones around all of them.
686 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000687 void processStaticAllocas();
688 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000689
Yury Gribov98b18592015-05-28 07:51:49 +0000690 void createDynamicAllocasInitStorage();
691
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000692 // ----------------------- Visitors.
693 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000694 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000696 /// \brief Collect all Resume instructions.
697 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
698
699 /// \brief Collect all CatchReturnInst instructions.
700 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
701
Yury Gribov98b18592015-05-28 07:51:49 +0000702 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
703 Value *SavedStack) {
704 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000705 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
706 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
707 // need to adjust extracted SP to compute the address of the most recent
708 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
709 // this purpose.
710 if (!isa<ReturnInst>(InstBefore)) {
711 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
712 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
713 {IntptrTy});
714
715 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
716
717 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
718 DynamicAreaOffset);
719 }
720
Yury Gribov781bce22015-05-28 08:03:28 +0000721 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000722 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000723 }
724
Yury Gribov55441bb2014-11-21 10:29:50 +0000725 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000726 void unpoisonDynamicAllocas() {
727 for (auto &Ret : RetVec)
728 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000729
Yury Gribov98b18592015-05-28 07:51:49 +0000730 for (auto &StackRestoreInst : StackRestoreVec)
731 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
732 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000733 }
734
Yury Gribov55441bb2014-11-21 10:29:50 +0000735 // Deploy and poison redzones around dynamic alloca call. To do this, we
736 // should replace this call with another one with changed parameters and
737 // replace all its uses with new address, so
738 // addr = alloca type, old_size, align
739 // is replaced by
740 // new_size = (old_size + additional_size) * sizeof(type)
741 // tmp = alloca i8, new_size, max(align, 32)
742 // addr = tmp + 32 (first 32 bytes are for the left redzone).
743 // Additional_size is added to make new memory allocation contain not only
744 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000745 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000746
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000747 /// \brief Collect Alloca instructions we want (and can) handle.
748 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000749 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000750 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000751 return;
752 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000753
754 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000755 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000756 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000757 else
758 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000759 }
760
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000761 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
762 /// errors.
763 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000764 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000765 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000766 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000767 if (!ASan.UseAfterScope)
768 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000769 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000770 return;
771 // Found lifetime intrinsic, add ASan instrumentation if necessary.
772 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
773 // If size argument is undefined, don't do anything.
774 if (Size->isMinusOne()) return;
775 // Check that size doesn't saturate uint64_t and can
776 // be stored in IntptrTy.
777 const uint64_t SizeValue = Size->getValue().getLimitedValue();
778 if (SizeValue == ~0ULL ||
779 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
780 return;
781 // Find alloca instruction that corresponds to llvm.lifetime argument.
782 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000783 if (!AI || !ASan.isInterestingAlloca(*AI))
784 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000785 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000786 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000787 if (AI->isStaticAlloca())
788 StaticAllocaPoisonCallVec.push_back(APC);
789 else if (ClInstrumentDynamicAllocas)
790 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000791 }
792
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000793 void visitCallSite(CallSite CS) {
794 Instruction *I = CS.getInstruction();
795 if (CallInst *CI = dyn_cast<CallInst>(I)) {
796 HasNonEmptyInlineAsm |=
797 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
798 HasReturnsTwiceCall |= CI->canReturnTwice();
799 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000800 }
801
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000802 // ---------------------- Helpers.
803 void initializeCallbacks(Module &M);
804
Yury Gribov3ae427d2014-12-01 08:47:58 +0000805 bool doesDominateAllExits(const Instruction *I) const {
806 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000807 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000808 }
809 return true;
810 }
811
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000812 /// Finds alloca where the value comes from.
813 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000814 void poisonStackFrameInline(ArrayRef<uint8_t> ShadowBytes, size_t Begin,
815 size_t End, IRBuilder<> &IRB, Value *ShadowBase,
816 bool DoPoison);
Vitaly Buka186280d2016-08-20 18:34:36 +0000817 void poisonStackFrame(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
818 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000819 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000820
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000821 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
822 bool Dynamic);
823 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
824 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000825};
826
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000827} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000828
829char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000830INITIALIZE_PASS_BEGIN(
831 AddressSanitizer, "asan",
832 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
833 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000834INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000835INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000836INITIALIZE_PASS_END(
837 AddressSanitizer, "asan",
838 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
839 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000840FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000841 bool Recover,
842 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000843 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000844 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000845}
846
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000847char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000848INITIALIZE_PASS(
849 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000850 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000851 "ModulePass",
852 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000853ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
854 bool Recover) {
855 assert(!CompileKernel || Recover);
856 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000857}
858
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000859static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000860 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000861 assert(Res < kNumberOfAccessSizes);
862 return Res;
863}
864
Bill Wendling58f8cef2013-08-06 22:52:42 +0000865// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000866static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
867 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000868 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000869 // We use private linkage for module-local strings. If they can be merged
870 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000871 GlobalVariable *GV =
872 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000873 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000874 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000875 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
876 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000877}
878
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000879/// \brief Create a global describing a source location.
880static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
881 LocationMetadata MD) {
882 Constant *LocData[] = {
883 createPrivateGlobalForString(M, MD.Filename, true),
884 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
885 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
886 };
887 auto LocStruct = ConstantStruct::getAnon(LocData);
888 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
889 GlobalValue::PrivateLinkage, LocStruct,
890 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000891 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000892 return GV;
893}
894
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000895/// \brief Check if \p G has been created by a trusted compiler pass.
896static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
897 // Do not instrument asan globals.
898 if (G->getName().startswith(kAsanGenPrefix) ||
899 G->getName().startswith(kSanCovGenPrefix) ||
900 G->getName().startswith(kODRGenPrefix))
901 return true;
902
903 // Do not instrument gcov counter arrays.
904 if (G->getName() == "__llvm_gcov_ctr")
905 return true;
906
907 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000908}
909
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000910Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
911 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000912 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000913 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000914 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000915 if (Mapping.OrShadowOffset)
916 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
917 else
918 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000919}
920
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000921// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000922void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
923 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000924 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000925 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000926 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000927 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
928 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
929 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000930 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000931 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000932 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000933 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
934 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
935 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000936 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000937 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000938}
939
Anna Zaks8ed1d812015-02-27 03:12:36 +0000940/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000941bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000942 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
943
944 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
945 return PreviouslySeenAllocaInfo->getSecond();
946
Yury Gribov98b18592015-05-28 07:51:49 +0000947 bool IsInteresting =
948 (AI.getAllocatedType()->isSized() &&
949 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000950 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +0000951 // We are only interested in allocas not promotable to registers.
952 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000953 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
954 // inalloca allocas are not treated as static, and we don't want
955 // dynamic alloca instrumentation for them as well.
956 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000957
958 ProcessedAllocas[&AI] = IsInteresting;
959 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000960}
961
962/// If I is an interesting memory access, return the PointerOperand
963/// and set IsWrite/Alignment. Otherwise return nullptr.
964Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
965 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000966 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000967 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000968 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000969 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000970
971 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000973 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000974 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000975 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000976 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000977 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000978 PtrOperand = LI->getPointerOperand();
979 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000980 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000981 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000982 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000983 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000984 PtrOperand = SI->getPointerOperand();
985 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000986 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000987 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000988 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000989 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000990 PtrOperand = RMW->getPointerOperand();
991 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000992 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000993 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000994 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000995 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000996 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000997 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000998
Anna Zaks644d9d32016-06-22 00:15:52 +0000999 // Do not instrument acesses from different address spaces; we cannot deal
1000 // with them.
1001 if (PtrOperand) {
1002 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1003 if (PtrTy->getPointerAddressSpace() != 0)
1004 return nullptr;
1005 }
1006
Anna Zaks8ed1d812015-02-27 03:12:36 +00001007 // Treat memory accesses to promotable allocas as non-interesting since they
1008 // will not cause memory violations. This greatly speeds up the instrumented
1009 // executable at -O0.
1010 if (ClSkipPromotableAllocas)
1011 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1012 return isInterestingAlloca(*AI) ? AI : nullptr;
1013
1014 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001015}
1016
Kostya Serebryany796f6552014-02-27 12:45:36 +00001017static bool isPointerOperand(Value *V) {
1018 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1019}
1020
1021// This is a rough heuristic; it may cause both false positives and
1022// false negatives. The proper implementation requires cooperation with
1023// the frontend.
1024static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1025 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001026 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001027 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001029 } else {
1030 return false;
1031 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001032 return isPointerOperand(I->getOperand(0)) &&
1033 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001034}
1035
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001036bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1037 // If a global variable does not have dynamic initialization we don't
1038 // have to instrument it. However, if a global does not have initializer
1039 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001040 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001041}
1042
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001043void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1044 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001045 IRBuilder<> IRB(I);
1046 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1047 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001048 for (Value *&i : Param) {
1049 if (i->getType()->isPointerTy())
1050 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001051 }
David Blaikieff6409d2015-05-18 22:13:54 +00001052 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001053}
1054
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001055void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001056 Instruction *I, bool UseCalls,
1057 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001058 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001059 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001060 uint64_t TypeSize = 0;
1061 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +00001062 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001063
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001064 // Optimization experiments.
1065 // The experiments can be used to evaluate potential optimizations that remove
1066 // instrumentation (assess false negatives). Instead of completely removing
1067 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1068 // experiments that want to remove instrumentation of this instruction).
1069 // If Exp is non-zero, this pass will emit special calls into runtime
1070 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1071 // make runtime terminate the program in a special way (with a different
1072 // exit status). Then you run the new compiler on a buggy corpus, collect
1073 // the special terminations (ideally, you don't see them at all -- no false
1074 // negatives) and make the decision on the optimization.
1075 uint32_t Exp = ClForceExperiment;
1076
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001077 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001078 // If initialization order checking is disabled, a simple access to a
1079 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001080 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001081 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001082 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1083 NumOptimizedAccessesToGlobalVar++;
1084 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001085 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001086 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001087
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001088 if (ClOpt && ClOptStack) {
1089 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001090 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001091 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1092 NumOptimizedAccessesToStackVar++;
1093 return;
1094 }
1095 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001096
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001097 if (IsWrite)
1098 NumInstrumentedWrites++;
1099 else
1100 NumInstrumentedReads++;
1101
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001102 unsigned Granularity = 1 << Mapping.Scale;
1103 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1104 // if the data is properly aligned.
1105 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1106 TypeSize == 128) &&
1107 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001108 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1109 Exp);
1110 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1111 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001112}
1113
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001114Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1115 Value *Addr, bool IsWrite,
1116 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001117 Value *SizeArgument,
1118 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001119 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001120 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1121 CallInst *Call = nullptr;
1122 if (SizeArgument) {
1123 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001124 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1125 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001126 else
David Blaikieff6409d2015-05-18 22:13:54 +00001127 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1128 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001129 } else {
1130 if (Exp == 0)
1131 Call =
1132 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1133 else
David Blaikieff6409d2015-05-18 22:13:54 +00001134 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1135 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001136 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001137
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001138 // We don't do Call->setDoesNotReturn() because the BB already has
1139 // UnreachableInst at the end.
1140 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001141 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001142 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001143}
1144
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001145Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001146 Value *ShadowValue,
1147 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001148 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001149 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001150 Value *LastAccessedByte =
1151 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001152 // (Addr & (Granularity - 1)) + size - 1
1153 if (TypeSize / 8 > 1)
1154 LastAccessedByte = IRB.CreateAdd(
1155 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1156 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001157 LastAccessedByte =
1158 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001159 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1160 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1161}
1162
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001163void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001164 Instruction *InsertBefore, Value *Addr,
1165 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001166 Value *SizeArgument, bool UseCalls,
1167 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001168 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001169 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001170 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1171
1172 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001173 if (Exp == 0)
1174 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1175 AddrLong);
1176 else
David Blaikieff6409d2015-05-18 22:13:54 +00001177 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1178 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001179 return;
1180 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001181
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001182 Type *ShadowTy =
1183 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001184 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1185 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1186 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001187 Value *ShadowValue =
1188 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001189
1190 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001191 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001192 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001193
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001194 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001195 // We use branch weights for the slow path check, to indicate that the slow
1196 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001197 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1198 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001199 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001200 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001201 IRB.SetInsertPoint(CheckTerm);
1202 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001203 if (Recover) {
1204 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1205 } else {
1206 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001207 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001208 CrashTerm = new UnreachableInst(*C, CrashBlock);
1209 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1210 ReplaceInstWithInst(CheckTerm, NewTerm);
1211 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001212 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001213 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001214 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001215
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001216 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001217 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001218 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001219}
1220
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001221// Instrument unusual size or unusual alignment.
1222// We can not do it with a single check, so we do 1-byte check for the first
1223// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1224// to report the actual access size.
1225void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1226 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1227 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1228 IRBuilder<> IRB(I);
1229 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1230 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1231 if (UseCalls) {
1232 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001233 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1234 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001235 else
David Blaikieff6409d2015-05-18 22:13:54 +00001236 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1237 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001238 } else {
1239 Value *LastByte = IRB.CreateIntToPtr(
1240 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1241 Addr->getType());
1242 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1243 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1244 }
1245}
1246
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001247void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1248 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001249 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001250 IRBuilder<> IRB(&GlobalInit.front(),
1251 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001252
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001253 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001254 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1255 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001256
1257 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001258 for (auto &BB : GlobalInit.getBasicBlockList())
1259 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001260 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001261}
1262
1263void AddressSanitizerModule::createInitializerPoisonCalls(
1264 Module &M, GlobalValue *ModuleName) {
1265 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1266
1267 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1268 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001269 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001270 ConstantStruct *CS = cast<ConstantStruct>(OP);
1271
1272 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001273 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001274 if (F->getName() == kAsanModuleCtorName) continue;
1275 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1276 // Don't instrument CTORs that will run before asan.module_ctor.
1277 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1278 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001279 }
1280 }
1281}
1282
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001283bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001284 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001285 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001286
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001287 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001288 if (!Ty->isSized()) return false;
1289 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001290 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001291 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001292 // Don't handle ODR linkage types and COMDATs since other modules may be built
1293 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001294 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1295 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1296 G->getLinkage() != GlobalVariable::InternalLinkage)
1297 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001298 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001299 // Two problems with thread-locals:
1300 // - The address of the main thread's copy can't be computed at link-time.
1301 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001302 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001303 // For now, just ignore this Global if the alignment is large.
1304 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001305
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001306 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001307 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001308
Anna Zaks11904602015-06-09 00:58:08 +00001309 // Globals from llvm.metadata aren't emitted, do not instrument them.
1310 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001311 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001312 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001313
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001314 // Do not instrument function pointers to initialization and termination
1315 // routines: dynamic linker will not properly handle redzones.
1316 if (Section.startswith(".preinit_array") ||
1317 Section.startswith(".init_array") ||
1318 Section.startswith(".fini_array")) {
1319 return false;
1320 }
1321
Anna Zaks11904602015-06-09 00:58:08 +00001322 // Callbacks put into the CRT initializer/terminator sections
1323 // should not be instrumented.
1324 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1325 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1326 if (Section.startswith(".CRT")) {
1327 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1328 return false;
1329 }
1330
Kuba Brecka1001bb52014-12-05 22:19:18 +00001331 if (TargetTriple.isOSBinFormatMachO()) {
1332 StringRef ParsedSegment, ParsedSection;
1333 unsigned TAA = 0, StubSize = 0;
1334 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001335 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1336 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001337 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001338
1339 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1340 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1341 // them.
1342 if (ParsedSegment == "__OBJC" ||
1343 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1344 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1345 return false;
1346 }
1347 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1348 // Constant CFString instances are compiled in the following way:
1349 // -- the string buffer is emitted into
1350 // __TEXT,__cstring,cstring_literals
1351 // -- the constant NSConstantString structure referencing that buffer
1352 // is placed into __DATA,__cfstring
1353 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1354 // Moreover, it causes the linker to crash on OS X 10.7
1355 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1356 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1357 return false;
1358 }
1359 // The linker merges the contents of cstring_literals and removes the
1360 // trailing zeroes.
1361 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1362 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1363 return false;
1364 }
1365 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001366 }
1367
1368 return true;
1369}
1370
Ryan Govostes653f9d02016-03-28 20:28:57 +00001371// On Mach-O platforms, we emit global metadata in a separate section of the
1372// binary in order to allow the linker to properly dead strip. This is only
1373// supported on recent versions of ld64.
1374bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001375 if (!ClUseMachOGlobalsSection)
1376 return false;
1377
Ryan Govostes653f9d02016-03-28 20:28:57 +00001378 if (!TargetTriple.isOSBinFormatMachO())
1379 return false;
1380
1381 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1382 return true;
1383 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001384 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001385 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1386 return true;
1387
1388 return false;
1389}
1390
Alexey Samsonov788381b2012-12-25 12:28:20 +00001391void AddressSanitizerModule::initializeCallbacks(Module &M) {
1392 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001393
Alexey Samsonov788381b2012-12-25 12:28:20 +00001394 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001395 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001396 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001397 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001398 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001399 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001400 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001401
Alexey Samsonov788381b2012-12-25 12:28:20 +00001402 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001403 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001404 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001405 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001406 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001407 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1408 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001409 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001410
1411 // Declare the functions that find globals in a shared object and then invoke
1412 // the (un)register function on them.
1413 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1414 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1415 IRB.getVoidTy(), IntptrTy, nullptr));
1416 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001417
Ryan Govostes653f9d02016-03-28 20:28:57 +00001418 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1419 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1420 IRB.getVoidTy(), IntptrTy, nullptr));
1421 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001422}
1423
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001424// This function replaces all global variables with new variables that have
1425// trailing redzones. It also creates a function that poisons
1426// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001427bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001428 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001429
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001430 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1431
Alexey Samsonova02e6642014-05-29 18:40:48 +00001432 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001433 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001434 }
1435
1436 size_t n = GlobalsToChange.size();
1437 if (n == 0) return false;
1438
1439 // A global is described by a structure
1440 // size_t beg;
1441 // size_t size;
1442 // size_t size_with_redzone;
1443 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001444 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001445 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001446 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001447 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001448 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001449 StructType *GlobalStructTy =
1450 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001451 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001452 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001453
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001454 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001455
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001456 // We shouldn't merge same module names, as this string serves as unique
1457 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001458 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001459 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001460
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001461 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001462 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001463 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001465
1466 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001467 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001468 // Create string holding the global name (use global name from metadata
1469 // if it's available, otherwise just write the name of global variable).
1470 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001471 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001472 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001473
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001474 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001475 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001476 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001477 // MinRZ <= RZ <= kMaxGlobalRedzone
1478 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001479 uint64_t RZ = std::max(
1480 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001481 uint64_t RightRedzoneSize = RZ;
1482 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001483 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001484 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001485 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1486
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001487 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001488 Constant *NewInitializer =
1489 ConstantStruct::get(NewTy, G->getInitializer(),
1490 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001491
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001492 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001493 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1494 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1495 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001496 GlobalVariable *NewGlobal =
1497 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1498 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001500 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001501
1502 Value *Indices2[2];
1503 Indices2[0] = IRB.getInt32(0);
1504 Indices2[1] = IRB.getInt32(0);
1505
1506 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001507 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001508 NewGlobal->takeName(G);
1509 G->eraseFromParent();
1510
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001511 Constant *SourceLoc;
1512 if (!MD.SourceLoc.empty()) {
1513 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1514 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1515 } else {
1516 SourceLoc = ConstantInt::get(IntptrTy, 0);
1517 }
1518
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001519 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1520 GlobalValue *InstrumentedGlobal = NewGlobal;
1521
1522 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1523 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1524 // Create local alias for NewGlobal to avoid crash on ODR between
1525 // instrumented and non-instrumented libraries.
1526 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1527 NameForGlobal + M.getName(), NewGlobal);
1528
1529 // With local aliases, we need to provide another externally visible
1530 // symbol __odr_asan_XXX to detect ODR violation.
1531 auto *ODRIndicatorSym =
1532 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1533 Constant::getNullValue(IRB.getInt8Ty()),
1534 kODRGenPrefix + NameForGlobal, nullptr,
1535 NewGlobal->getThreadLocalMode());
1536
1537 // Set meaningful attributes for indicator symbol.
1538 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1539 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1540 ODRIndicatorSym->setAlignment(1);
1541 ODRIndicator = ODRIndicatorSym;
1542 InstrumentedGlobal = GA;
1543 }
1544
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001545 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001546 GlobalStructTy,
1547 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001548 ConstantInt::get(IntptrTy, SizeInBytes),
1549 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1550 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001551 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001552 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1553 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001554
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001555 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001556
Kostya Serebryany20343352012-10-17 13:40:06 +00001557 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001558 }
1559
Ryan Govostes653f9d02016-03-28 20:28:57 +00001560
1561 GlobalVariable *AllGlobals = nullptr;
1562 GlobalVariable *RegisteredFlag = nullptr;
1563
1564 // On recent Mach-O platforms, we emit the global metadata in a way that
1565 // allows the linker to properly strip dead globals.
1566 if (ShouldUseMachOGlobalsSection()) {
1567 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1568 // to look up the loaded image that contains it. Second, we can store in it
1569 // whether registration has already occurred, to prevent duplicate
1570 // registration.
1571 //
1572 // Common linkage allows us to coalesce needles defined in each object
1573 // file so that there's only one per shared library.
1574 RegisteredFlag = new GlobalVariable(
1575 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1576 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1577
1578 // We also emit a structure which binds the liveness of the global
1579 // variable to the metadata struct.
1580 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1581
1582 for (size_t i = 0; i < n; i++) {
1583 GlobalVariable *Metadata = new GlobalVariable(
1584 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1585 Initializers[i], "");
1586 Metadata->setSection("__DATA,__asan_globals,regular");
1587 Metadata->setAlignment(1); // don't leave padding in between
1588
1589 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1590 Initializers[i]->getAggregateElement(0u),
1591 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1592 nullptr);
1593 GlobalVariable *Liveness = new GlobalVariable(
1594 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1595 LivenessBinder, "");
1596 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1597 }
1598 } else {
1599 // On all other platfoms, we just emit an array of global metadata
1600 // structures.
1601 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1602 AllGlobals = new GlobalVariable(
1603 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1604 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1605 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001606
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001607 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001608 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001609 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001610
Ryan Govostes653f9d02016-03-28 20:28:57 +00001611 // Create a call to register the globals with the runtime.
1612 if (ShouldUseMachOGlobalsSection()) {
1613 IRB.CreateCall(AsanRegisterImageGlobals,
1614 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1615 } else {
1616 IRB.CreateCall(AsanRegisterGlobals,
1617 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1618 ConstantInt::get(IntptrTy, n)});
1619 }
1620
1621 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001622 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001623 Function *AsanDtorFunction =
1624 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1625 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001626 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1627 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001628
1629 if (ShouldUseMachOGlobalsSection()) {
1630 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1631 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1632 } else {
1633 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1634 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1635 ConstantInt::get(IntptrTy, n)});
1636 }
1637
Alexey Samsonov1f647502014-05-29 01:10:14 +00001638 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001639
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001640 DEBUG(dbgs() << M);
1641 return true;
1642}
1643
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001644bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001645 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001646 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001647 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001648 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001649 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001650 initializeCallbacks(M);
1651
1652 bool Changed = false;
1653
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001654 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1655 if (ClGlobals && !CompileKernel) {
1656 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1657 assert(CtorFunc);
1658 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1659 Changed |= InstrumentGlobals(IRB, M);
1660 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001661
1662 return Changed;
1663}
1664
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001665void AddressSanitizer::initializeCallbacks(Module &M) {
1666 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001667 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001668 // IsWrite, TypeSize and Exp are encoded in the function name.
1669 for (int Exp = 0; Exp < 2; Exp++) {
1670 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1671 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1672 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001673 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001674 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001675 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001676 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001677 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001678 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001679 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1680 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001681 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001682 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001683 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1684 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1685 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001686 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001687 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001688 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001689 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001690 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001691 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001692 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001693 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1694 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001695 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001696 }
1697 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001698
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001699 const std::string MemIntrinCallbackPrefix =
1700 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001701 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001702 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001703 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001704 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001705 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001706 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001707 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001708 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001709 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001710
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001711 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001712 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001713
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001714 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001715 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001716 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001717 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001718 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1719 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1720 StringRef(""), StringRef(""),
1721 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001722}
1723
1724// virtual
1725bool AddressSanitizer::doInitialization(Module &M) {
1726 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001727
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001728 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001729
1730 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001731 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001732 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001733 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001734
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001735 if (!CompileKernel) {
1736 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001737 createSanitizerCtorAndInitFunctions(
1738 M, kAsanModuleCtorName, kAsanInitName,
1739 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001740 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1741 }
1742 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001743 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001744}
1745
Keno Fischere03fae42015-12-05 14:42:34 +00001746bool AddressSanitizer::doFinalization(Module &M) {
1747 GlobalsMD.reset();
1748 return false;
1749}
1750
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001751bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1752 // For each NSObject descendant having a +load method, this method is invoked
1753 // by the ObjC runtime before any of the static constructors is called.
1754 // Therefore we need to instrument such methods with a call to __asan_init
1755 // at the beginning in order to initialize our runtime before any access to
1756 // the shadow memory.
1757 // We cannot just ignore these methods, because they may call other
1758 // instrumented functions.
1759 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001760 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001761 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001762 return true;
1763 }
1764 return false;
1765}
1766
Reid Kleckner2f907552015-07-21 17:40:14 +00001767void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1768 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1769 // to it as uninteresting. This assumes we haven't started processing allocas
1770 // yet. This check is done up front because iterating the use list in
1771 // isInterestingAlloca would be algorithmically slower.
1772 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1773
1774 // Try to get the declaration of llvm.localescape. If it's not in the module,
1775 // we can exit early.
1776 if (!F.getParent()->getFunction("llvm.localescape")) return;
1777
1778 // Look for a call to llvm.localescape call in the entry block. It can't be in
1779 // any other block.
1780 for (Instruction &I : F.getEntryBlock()) {
1781 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1782 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1783 // We found a call. Mark all the allocas passed in as uninteresting.
1784 for (Value *Arg : II->arg_operands()) {
1785 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1786 assert(AI && AI->isStaticAlloca() &&
1787 "non-static alloca arg to localescape");
1788 ProcessedAllocas[AI] = false;
1789 }
1790 break;
1791 }
1792 }
1793}
1794
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001795bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001796 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001797 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001798 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001799 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001800
Yury Gribov3ae427d2014-12-01 08:47:58 +00001801 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1802
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001803 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001804 maybeInsertAsanInitAtFunctionEntry(F);
1805
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001806 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001807
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001808 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001809
Reid Kleckner2f907552015-07-21 17:40:14 +00001810 FunctionStateRAII CleanupObj(this);
1811
1812 // We can't instrument allocas used with llvm.localescape. Only static allocas
1813 // can be passed to that intrinsic.
1814 markEscapedLocalAllocas(F);
1815
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001816 // We want to instrument every address only once per basic block (unless there
1817 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001818 SmallSet<Value *, 16> TempsToInstrument;
1819 SmallVector<Instruction *, 16> ToInstrument;
1820 SmallVector<Instruction *, 8> NoReturnCalls;
1821 SmallVector<BasicBlock *, 16> AllBlocks;
1822 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001823 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001824 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001825 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001826 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001827 const TargetLibraryInfo *TLI =
1828 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001829
1830 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001831 for (auto &BB : F) {
1832 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001833 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001834 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001835 for (auto &Inst : BB) {
1836 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001837 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1838 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001839 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001840 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001841 continue; // We've seen this temp in the current BB.
1842 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001843 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001844 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1845 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001846 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001847 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001848 // ok, take it.
1849 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001850 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001851 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001852 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001853 // A call inside BB.
1854 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001855 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001856 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00001857 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
1858 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001859 continue;
1860 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001861 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001862 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001863 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001864 }
1865 }
1866
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001867 bool UseCalls =
1868 CompileKernel ||
1869 (ClInstrumentationWithCallsThreshold >= 0 &&
1870 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001871 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001872 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1873 /*RoundToAlign=*/true);
1874
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001875 // Instrument.
1876 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001877 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001878 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1879 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001880 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001881 instrumentMop(ObjSizeVis, Inst, UseCalls,
1882 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001883 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001884 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001885 }
1886 NumInstrumented++;
1887 }
1888
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001889 FunctionStackPoisoner FSP(F, *this);
1890 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001891
1892 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1893 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001894 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001895 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001896 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001897 }
1898
Alexey Samsonova02e6642014-05-29 18:40:48 +00001899 for (auto Inst : PointerComparisonsOrSubtracts) {
1900 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001901 NumInstrumented++;
1902 }
1903
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001904 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001905
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001906 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1907
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001908 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001909}
1910
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001911// Workaround for bug 11395: we don't want to instrument stack in functions
1912// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1913// FIXME: remove once the bug 11395 is fixed.
1914bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1915 if (LongSize != 32) return false;
1916 CallInst *CI = dyn_cast<CallInst>(I);
1917 if (!CI || !CI->isInlineAsm()) return false;
1918 if (CI->getNumArgOperands() <= 5) return false;
1919 // We have inline assembly with quite a few arguments.
1920 return true;
1921}
1922
1923void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1924 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001925 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1926 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001927 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1928 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1929 IntptrTy, nullptr));
1930 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001931 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1932 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001933 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00001934 if (ASan.UseAfterScope) {
1935 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1936 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1937 IntptrTy, IntptrTy, nullptr));
1938 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
1939 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1940 IntptrTy, IntptrTy, nullptr));
1941 }
1942
Vitaly Buka3455b9b2016-08-20 18:34:39 +00001943 if (ClExperimentalPoisoning) {
1944 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
1945 std::ostringstream Name;
1946 Name << kAsanSetShadowPrefix;
1947 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
1948 AsanSetShadowFunc[Val] =
1949 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1950 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1951 }
1952 }
1953
Yury Gribov98b18592015-05-28 07:51:49 +00001954 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1955 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1956 AsanAllocasUnpoisonFunc =
1957 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1958 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001959}
1960
Vitaly Buka186280d2016-08-20 18:34:36 +00001961// If DoPoison is true function copies ShadowBytes into shadow memory.
1962// If DoPoison is false function sets 0s into shadow memory.
1963// Function assumes that if ShadowBytes[i] is 0, then corresponding shadow
1964// memory is constant for duration of the function and it contains 0s. So we
1965// will try to minimize writes into corresponding addresses of the real shadow
1966// memory.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00001967void FunctionStackPoisoner::poisonStackFrameInline(
1968 ArrayRef<uint8_t> ShadowBytes, size_t Begin, size_t End, IRBuilder<> &IRB,
1969 Value *ShadowBase, bool DoPoison) {
1970 if (Begin >= End)
1971 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00001972
1973 const size_t LargestStoreSizeInBytes =
1974 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
1975
1976 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
1977
1978 // Poison given range in shadow using larges store size with out leading and
1979 // trailing zeros. Zeros never change, so they need neither poisoning nor
1980 // up-poisoning, but we don't mind if some of them get into a middle of a
1981 // store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00001982 for (size_t i = Begin; i < End;) {
Vitaly Buka186280d2016-08-20 18:34:36 +00001983 if (!ShadowBytes[i]) {
1984 ++i;
1985 continue;
1986 }
1987
1988 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
1989 // Fit store size into the range.
1990 while (StoreSizeInBytes > End - i)
1991 StoreSizeInBytes /= 2;
1992
1993 // Minimize store size by trimming trailing zeros.
1994 for (size_t j = StoreSizeInBytes - 1; j && !ShadowBytes[i + j]; --j) {
1995 while (j <= StoreSizeInBytes / 2)
1996 StoreSizeInBytes /= 2;
1997 }
1998
1999 uint64_t Val = 0;
2000 if (DoPoison) {
2001 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2002 if (IsLittleEndian)
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00002003 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2004 else
2005 Val = (Val << 8) | ShadowBytes[i + j];
2006 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002007 assert(Val); // Impossible because ShadowBytes[i] != 0
2008 } else {
2009 Val = 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002010 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002011
2012 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2013 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002014 IRB.CreateAlignedStore(
2015 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002016
2017 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002018 }
2019}
2020
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002021void FunctionStackPoisoner::poisonStackFrame(ArrayRef<uint8_t> ShadowBytes,
2022 IRBuilder<> &IRB,
2023 Value *ShadowBase, bool DoPoison) {
2024 auto ValueToWrite = [&](size_t i) {
2025 if (DoPoison)
2026 return ShadowBytes[i];
2027 return static_cast<uint8_t>(0);
2028 };
2029
2030 const size_t End = ShadowBytes.size();
2031 size_t Done = 0;
2032 for (size_t i = 0, j = 1; i < End; i = j++) {
2033 if (!ShadowBytes[i])
2034 continue;
2035 uint8_t Val = ValueToWrite(i);
2036 if (!AsanSetShadowFunc[Val])
2037 continue;
2038
2039 // Skip same values.
2040 for (; j < End && ShadowBytes[j] && Val == ValueToWrite(j); ++j) {
2041 }
2042
2043 if (j - i >= ClMaxInlinePoisoningSize) {
2044 poisonStackFrameInline(ShadowBytes, Done, i, IRB, ShadowBase, DoPoison);
2045 IRB.CreateCall(AsanSetShadowFunc[Val],
2046 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2047 ConstantInt::get(IntptrTy, j - i)});
2048 Done = j;
2049 }
2050 }
2051
2052 poisonStackFrameInline(ShadowBytes, Done, End, IRB, ShadowBase, DoPoison);
2053}
2054
Kostya Serebryany6805de52013-09-10 13:16:56 +00002055// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2056// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2057static int StackMallocSizeClass(uint64_t LocalStackSize) {
2058 assert(LocalStackSize <= kMaxStackMallocSize);
2059 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002060 for (int i = 0;; i++, MaxSize *= 2)
2061 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002062 llvm_unreachable("impossible LocalStackSize");
2063}
2064
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002065PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2066 Value *ValueIfTrue,
2067 Instruction *ThenTerm,
2068 Value *ValueIfFalse) {
2069 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2070 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2071 PHI->addIncoming(ValueIfFalse, CondBlock);
2072 BasicBlock *ThenBlock = ThenTerm->getParent();
2073 PHI->addIncoming(ValueIfTrue, ThenBlock);
2074 return PHI;
2075}
2076
2077Value *FunctionStackPoisoner::createAllocaForLayout(
2078 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2079 AllocaInst *Alloca;
2080 if (Dynamic) {
2081 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2082 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2083 "MyAlloca");
2084 } else {
2085 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2086 nullptr, "MyAlloca");
2087 assert(Alloca->isStaticAlloca());
2088 }
2089 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2090 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2091 Alloca->setAlignment(FrameAlignment);
2092 return IRB.CreatePointerCast(Alloca, IntptrTy);
2093}
2094
Yury Gribov98b18592015-05-28 07:51:49 +00002095void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2096 BasicBlock &FirstBB = *F.begin();
2097 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2098 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2099 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2100 DynamicAllocaLayout->setAlignment(32);
2101}
2102
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002103void FunctionStackPoisoner::processDynamicAllocas() {
2104 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2105 assert(DynamicAllocaPoisonCallVec.empty());
2106 return;
2107 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002108
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002109 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2110 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002111 assert(APC.InsBefore);
2112 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002113 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002114 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002115
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002116 IRBuilder<> IRB(APC.InsBefore);
2117 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002118 // Dynamic allocas will be unpoisoned unconditionally below in
2119 // unpoisonDynamicAllocas.
2120 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002121 }
2122
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002123 // Handle dynamic allocas.
2124 createDynamicAllocasInitStorage();
2125 for (auto &AI : DynamicAllocaVec)
2126 handleDynamicAllocaCall(AI);
2127 unpoisonDynamicAllocas();
2128}
Yury Gribov98b18592015-05-28 07:51:49 +00002129
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002130void FunctionStackPoisoner::processStaticAllocas() {
2131 if (AllocaVec.empty()) {
2132 assert(StaticAllocaPoisonCallVec.empty());
2133 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002134 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002135
Kostya Serebryany6805de52013-09-10 13:16:56 +00002136 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002137 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002138 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002139 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002140
2141 Instruction *InsBefore = AllocaVec[0];
2142 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002143 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002144
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002145 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2146 // debug info is broken, because only entry-block allocas are treated as
2147 // regular stack slots.
2148 auto InsBeforeB = InsBefore->getParent();
2149 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002150 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
2151 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002152 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2153 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002154
Reid Kleckner2f907552015-07-21 17:40:14 +00002155 // If we have a call to llvm.localescape, keep it in the entry block.
2156 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2157
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002158 // Insert poison calls for lifetime intrinsics for static allocas.
2159 for (const auto &APC : StaticAllocaPoisonCallVec) {
2160 assert(APC.InsBefore);
2161 assert(APC.AI);
2162 assert(ASan.isInterestingAlloca(*APC.AI));
2163 assert(APC.AI->isStaticAlloca());
2164
2165 IRBuilder<> IRB(APC.InsBefore);
2166 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2167 }
2168
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002169 SmallVector<ASanStackVariableDescription, 16> SVD;
2170 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002171 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002172 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002173 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002174 0,
2175 AI->getAlignment(),
2176 AI,
2177 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002178 SVD.push_back(D);
2179 }
2180 // Minimal header size (left redzone) is 4 pointers,
2181 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2182 size_t MinHeaderSize = ASan.LongSize / 2;
2183 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002184 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002185 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2186 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002187 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2188 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002189 bool DoDynamicAlloca = ClDynamicAllocaStack;
2190 // Don't do dynamic alloca or stack malloc if:
2191 // 1) There is inline asm: too often it makes assumptions on which registers
2192 // are available.
2193 // 2) There is a returns_twice call (typically setjmp), which is
2194 // optimization-hostile, and doesn't play well with introduced indirect
2195 // register-relative calculation of local variable addresses.
2196 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2197 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002198
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002199 Value *StaticAlloca =
2200 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2201
2202 Value *FakeStack;
2203 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002204
2205 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002206 // void *FakeStack = __asan_option_detect_stack_use_after_return
2207 // ? __asan_stack_malloc_N(LocalStackSize)
2208 // : nullptr;
2209 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002210 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2211 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2212 Value *UseAfterReturnIsEnabled =
2213 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002214 Constant::getNullValue(IRB.getInt32Ty()));
2215 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002216 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002217 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002218 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002219 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2220 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2221 Value *FakeStackValue =
2222 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2223 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002224 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002225 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002226 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002227 ConstantInt::get(IntptrTy, 0));
2228
2229 Value *NoFakeStack =
2230 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2231 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2232 IRBIf.SetInsertPoint(Term);
2233 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2234 Value *AllocaValue =
2235 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2236 IRB.SetInsertPoint(InsBefore);
2237 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2238 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2239 } else {
2240 // void *FakeStack = nullptr;
2241 // void *LocalStackBase = alloca(LocalStackSize);
2242 FakeStack = ConstantInt::get(IntptrTy, 0);
2243 LocalStackBase =
2244 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002245 }
2246
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002247 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002248 for (const auto &Desc : SVD) {
2249 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002250 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002251 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002252 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002253 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002254 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002255 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002256
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002257 // The left-most redzone has enough space for at least 4 pointers.
2258 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002259 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2260 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2261 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002262 // Write the frame description constant to redzone[1].
2263 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002264 IRB.CreateAdd(LocalStackBase,
2265 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2266 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002267 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002268 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002269 /*AllowMerging*/ true);
2270 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002271 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002272 // Write the PC to redzone[2].
2273 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002274 IRB.CreateAdd(LocalStackBase,
2275 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2276 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002277 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002278
2279 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002280 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka186280d2016-08-20 18:34:36 +00002281 poisonStackFrame(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002282
Vitaly Buka79b75d32016-06-09 23:05:35 +00002283 auto UnpoisonStack = [&](IRBuilder<> &IRB) {
Vitaly Buka1ce73ef2016-08-16 16:24:10 +00002284 // Do this always as poisonAlloca can be disabled with
2285 // detect_stack_use_after_scope=0.
Vitaly Buka186280d2016-08-20 18:34:36 +00002286 poisonStackFrame(L.ShadowBytes, IRB, ShadowBase, false);
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002287 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002288 // If we poisoned some allocas in llvm.lifetime analysis,
2289 // unpoison whole stack frame now.
2290 poisonAlloca(LocalStackBase, LocalStackSize, IRB, false);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002291 }
2292 };
2293
Vitaly Buka186280d2016-08-20 18:34:36 +00002294 SmallVector<uint8_t, 64> ShadowBytesAfterReturn;
2295
Kostya Serebryany530e2072013-12-23 14:15:08 +00002296 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002297 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002298 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002299 // Mark the current frame as retired.
2300 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2301 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002302 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002303 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002304 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002305 // // In use-after-return mode, poison the whole stack frame.
2306 // if StackMallocIdx <= 4
2307 // // For small sizes inline the whole thing:
2308 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002309 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002310 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002311 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002312 // else
2313 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002314 Value *Cmp =
2315 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002316 TerminatorInst *ThenTerm, *ElseTerm;
2317 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2318
2319 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002320 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002321 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka186280d2016-08-20 18:34:36 +00002322 ShadowBytesAfterReturn.resize(ClassSize >> Mapping.Scale,
2323 kAsanStackUseAfterReturnMagic);
2324 poisonStackFrame(ShadowBytesAfterReturn, IRBPoison, ShadowBase, true);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002325 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002326 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002327 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2328 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2329 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2330 IRBPoison.CreateStore(
2331 Constant::getNullValue(IRBPoison.getInt8Ty()),
2332 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2333 } else {
2334 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002335 IRBPoison.CreateCall(
2336 AsanStackFreeFunc[StackMallocIdx],
2337 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002338 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002339
2340 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002341 UnpoisonStack(IRBElse);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002342 } else {
Vitaly Buka79b75d32016-06-09 23:05:35 +00002343 UnpoisonStack(IRBRet);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002344 }
2345 }
2346
Kostya Serebryany09959942012-10-19 06:20:53 +00002347 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002348 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002349}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002350
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002351void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002352 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002353 // For now just insert the call to ASan runtime.
2354 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2355 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002356 IRB.CreateCall(
2357 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2358 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002359}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002360
2361// Handling llvm.lifetime intrinsics for a given %alloca:
2362// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2363// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2364// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2365// could be poisoned by previous llvm.lifetime.end instruction, as the
2366// variable may go in and out of scope several times, e.g. in loops).
2367// (3) if we poisoned at least one %alloca in a function,
2368// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002369
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002370AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2371 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2372 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002373 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002374 // See if we've already calculated (or started to calculate) alloca for a
2375 // given value.
2376 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002377 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002378 // Store 0 while we're calculating alloca for value V to avoid
2379 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002380 AllocaForValue[V] = nullptr;
2381 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002382 if (CastInst *CI = dyn_cast<CastInst>(V))
2383 Res = findAllocaForValue(CI->getOperand(0));
2384 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002385 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002386 // Allow self-referencing phi-nodes.
2387 if (IncValue == PN) continue;
2388 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2389 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002390 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2391 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002392 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002393 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002394 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2395 Res = findAllocaForValue(EP->getPointerOperand());
2396 } else {
2397 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002398 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002399 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002400 return Res;
2401}
Yury Gribov55441bb2014-11-21 10:29:50 +00002402
Yury Gribov98b18592015-05-28 07:51:49 +00002403void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002404 IRBuilder<> IRB(AI);
2405
Yury Gribov55441bb2014-11-21 10:29:50 +00002406 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2407 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2408
2409 Value *Zero = Constant::getNullValue(IntptrTy);
2410 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2411 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002412
2413 // Since we need to extend alloca with additional memory to locate
2414 // redzones, and OldSize is number of allocated blocks with
2415 // ElementSize size, get allocated memory size in bytes by
2416 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002417 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002418 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002419 Value *OldSize =
2420 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2421 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002422
2423 // PartialSize = OldSize % 32
2424 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2425
2426 // Misalign = kAllocaRzSize - PartialSize;
2427 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2428
2429 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2430 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2431 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2432
2433 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2434 // Align is added to locate left redzone, PartialPadding for possible
2435 // partial redzone and kAllocaRzSize for right redzone respectively.
2436 Value *AdditionalChunkSize = IRB.CreateAdd(
2437 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2438
2439 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2440
2441 // Insert new alloca with new NewSize and Align params.
2442 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2443 NewAlloca->setAlignment(Align);
2444
2445 // NewAddress = Address + Align
2446 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2447 ConstantInt::get(IntptrTy, Align));
2448
Yury Gribov98b18592015-05-28 07:51:49 +00002449 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002450 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002451
2452 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2453 // for unpoisoning stuff.
2454 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2455
Yury Gribov55441bb2014-11-21 10:29:50 +00002456 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2457
Yury Gribov98b18592015-05-28 07:51:49 +00002458 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002459 AI->replaceAllUsesWith(NewAddressPtr);
2460
Yury Gribov98b18592015-05-28 07:51:49 +00002461 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002462 AI->eraseFromParent();
2463}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002464
2465// isSafeAccess returns true if Addr is always inbounds with respect to its
2466// base object. For example, it is a field access or an array access with
2467// constant inbounds index.
2468bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2469 Value *Addr, uint64_t TypeSize) const {
2470 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2471 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002472 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002473 int64_t Offset = SizeOffset.second.getSExtValue();
2474 // Three checks are required to ensure safety:
2475 // . Offset >= 0 (since the offset is given from the base ptr)
2476 // . Size >= Offset (unsigned)
2477 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002478 return Offset >= 0 && Size >= uint64_t(Offset) &&
2479 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002480}