blob: c20ad6d5b944fd6cdffb349c3a4e63394b312370 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000057#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000058#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000059#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000061#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000062
63using namespace llvm;
64
Chandler Carruth964daaa2014-04-22 02:55:47 +000065#define DEBUG_TYPE "asan"
66
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowScale = 3;
68static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000070static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000071static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000072static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000074static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000075static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000076static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000077static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000078static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000079static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000080static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000081static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +000083static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000084static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000085// The shadow memory space is dynamically allocated.
86static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000088static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000089static const size_t kMaxStackMallocSize = 1 << 16; // 64K
90static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
91static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
92
Craig Topperd3a34f82013-07-16 01:17:10 +000093static const char *const kAsanModuleCtorName = "asan.module_ctor";
94static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000095static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000098static const char *const kAsanUnregisterGlobalsName =
99 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000100static const char *const kAsanRegisterImageGlobalsName =
101 "__asan_register_image_globals";
102static const char *const kAsanUnregisterImageGlobalsName =
103 "__asan_unregister_image_globals";
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000104static const char *const kAsanRegisterElfGlobalsName =
105 "__asan_register_elf_globals";
106static const char *const kAsanUnregisterElfGlobalsName =
107 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000108static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
109static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000110static const char *const kAsanInitName = "__asan_init";
111static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000112 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000113static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
114static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000115static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000116static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000117static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
118static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000119static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000120static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000121static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000122static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000123static const char *const kAsanPoisonStackMemoryName =
124 "__asan_poison_stack_memory";
125static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000126 "__asan_unpoison_stack_memory";
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000127
128// ASan version script has __asan_* wildcard. Triple underscore prevents a
129// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000130static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000131 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000132
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000133static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000134 "__asan_option_detect_stack_use_after_return";
135
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000136static const char *const kAsanShadowMemoryDynamicAddress =
137 "__asan_shadow_memory_dynamic_address";
138
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000139static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
140static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000141
Kostya Serebryany874dae62012-07-16 16:15:40 +0000142// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
143static const size_t kNumberOfAccessSizes = 5;
144
Yury Gribov55441bb2014-11-21 10:29:50 +0000145static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000146
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000147// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000148static cl::opt<bool> ClEnableKasan(
149 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
150 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000151static cl::opt<bool> ClRecover(
152 "asan-recover",
153 cl::desc("Enable recovery mode (continue-after-error)."),
154 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000155
156// This flag may need to be replaced with -f[no-]asan-reads.
157static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000158 cl::desc("instrument read instructions"),
159 cl::Hidden, cl::init(true));
160static cl::opt<bool> ClInstrumentWrites(
161 "asan-instrument-writes", cl::desc("instrument write instructions"),
162 cl::Hidden, cl::init(true));
163static cl::opt<bool> ClInstrumentAtomics(
164 "asan-instrument-atomics",
165 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
166 cl::init(true));
167static cl::opt<bool> ClAlwaysSlowPath(
168 "asan-always-slow-path",
169 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
170 cl::init(false));
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000171static cl::opt<bool> ClForceDynamicShadow(
172 "asan-force-dynamic-shadow",
173 cl::desc("Load shadow address into a local variable for each function"),
174 cl::Hidden, cl::init(false));
175
Kostya Serebryany874dae62012-07-16 16:15:40 +0000176// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000177// in any given BB. Normally, this should be set to unlimited (INT_MAX),
178// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
179// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000180static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
181 "asan-max-ins-per-bb", cl::init(10000),
182 cl::desc("maximal number of instructions to instrument in any given BB"),
183 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000184// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000185static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
186 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000187static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
188 "asan-max-inline-poisoning-size",
189 cl::desc(
190 "Inline shadow poisoning for blocks up to the given size in bytes."),
191 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000192static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000193 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000194 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000195static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
196 cl::desc("Check stack-use-after-scope"),
197 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000198// This flag may need to be replaced with -f[no]asan-globals.
199static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200 cl::desc("Handle global objects"), cl::Hidden,
201 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000202static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203 cl::desc("Handle C++ initializer order"),
204 cl::Hidden, cl::init(true));
205static cl::opt<bool> ClInvalidPointerPairs(
206 "asan-detect-invalid-pointer-pair",
207 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
208 cl::init(false));
209static cl::opt<unsigned> ClRealignStack(
210 "asan-realign-stack",
211 cl::desc("Realign stack to the value of this flag (power of two)"),
212 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000213static cl::opt<int> ClInstrumentationWithCallsThreshold(
214 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000215 cl::desc(
216 "If the function being instrumented contains more than "
217 "this number of memory accesses, use callbacks instead of "
218 "inline checks (-1 means never use callbacks)."),
219 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000220static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000221 "asan-memory-access-callback-prefix",
222 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
223 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000224static cl::opt<bool>
225 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
226 cl::desc("instrument dynamic allocas"),
227 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000228static cl::opt<bool> ClSkipPromotableAllocas(
229 "asan-skip-promotable-allocas",
230 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
231 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000232
233// These flags allow to change the shadow mapping.
234// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000235// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000236static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000237 cl::desc("scale of asan shadow mapping"),
238 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000239static cl::opt<unsigned long long> ClMappingOffset(
240 "asan-mapping-offset",
241 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
242 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000243
244// Optimization flags. Not user visible, used mostly for testing
245// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000246static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
247 cl::Hidden, cl::init(true));
248static cl::opt<bool> ClOptSameTemp(
249 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
250 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000251static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000252 cl::desc("Don't instrument scalar globals"),
253 cl::Hidden, cl::init(true));
254static cl::opt<bool> ClOptStack(
255 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
256 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000257
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000258static cl::opt<bool> ClDynamicAllocaStack(
259 "asan-stack-dynamic-alloca",
260 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000261 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000262
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000263static cl::opt<uint32_t> ClForceExperiment(
264 "asan-force-experiment",
265 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
266 cl::init(0));
267
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000268static cl::opt<bool>
269 ClUsePrivateAliasForGlobals("asan-use-private-alias",
270 cl::desc("Use private aliases for global"
271 " variables"),
272 cl::Hidden, cl::init(false));
273
Ryan Govostese51401b2016-07-05 21:53:08 +0000274static cl::opt<bool>
275 ClUseMachOGlobalsSection("asan-globals-live-support",
276 cl::desc("Use linker features to support dead "
277 "code stripping of globals "
278 "(Mach-O only)"),
Anna Zaks9cd5ed12016-11-17 16:55:40 +0000279 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000280
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000281// Debug flags.
282static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
283 cl::init(0));
284static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
285 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000286static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
287 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000288static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
289 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000290static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000291 cl::Hidden, cl::init(-1));
292
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000293STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
294STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000295STATISTIC(NumOptimizedAccessesToGlobalVar,
296 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000297STATISTIC(NumOptimizedAccessesToStackVar,
298 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000299
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000300namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000301/// Frontend-provided metadata for source location.
302struct LocationMetadata {
303 StringRef Filename;
304 int LineNo;
305 int ColumnNo;
306
307 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
308
309 bool empty() const { return Filename.empty(); }
310
311 void parse(MDNode *MDN) {
312 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000313 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
314 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000315 LineNo =
316 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
317 ColumnNo =
318 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000319 }
320};
321
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000322/// Frontend-provided metadata for global variables.
323class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000324 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000326 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000327 LocationMetadata SourceLoc;
328 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000329 bool IsDynInit;
330 bool IsBlacklisted;
331 };
332
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000333 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000334
Keno Fischere03fae42015-12-05 14:42:34 +0000335 void reset() {
336 inited_ = false;
337 Entries.clear();
338 }
339
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000340 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000341 assert(!inited_);
342 inited_ = true;
343 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000344 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000345 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000346 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000347 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000348 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000349 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000350 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000351 // We can already have an entry for GV if it was merged with another
352 // global.
353 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000354 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
355 E.SourceLoc.parse(Loc);
356 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
357 E.Name = Name->getString();
358 ConstantInt *IsDynInit =
359 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000360 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000361 ConstantInt *IsBlacklisted =
362 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000363 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000364 }
365 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000366
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000367 /// Returns metadata entry for a given global.
368 Entry get(GlobalVariable *G) const {
369 auto Pos = Entries.find(G);
370 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000371 }
372
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000373 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000374 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000375 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000376};
377
Alexey Samsonov1345d352013-01-16 13:23:28 +0000378/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000379/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000380struct ShadowMapping {
381 int Scale;
382 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000383 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000384};
385
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000386static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
387 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000388 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000389 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000390 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000391 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000392 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000393 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
394 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000395 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000396 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000397 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000398 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
399 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000400 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
401 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000402 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000403 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000404 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000405
406 ShadowMapping Mapping;
407
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000408 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000409 // Android is always PIE, which means that the beginning of the address
410 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000411 if (IsAndroid)
412 Mapping.Offset = 0;
413 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000414 Mapping.Offset = kMIPS32_ShadowOffset32;
415 else if (IsFreeBSD)
416 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000417 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000418 // If we're targeting iOS and x86, the binary is built for iOS simulator.
419 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000420 else if (IsWindows)
421 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000422 else
423 Mapping.Offset = kDefaultShadowOffset32;
424 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000425 // Fuchsia is always PIE, which means that the beginning of the address
426 // space is always available.
427 if (IsFuchsia)
428 Mapping.Offset = 0;
429 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000430 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000431 else if (IsSystemZ)
432 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000433 else if (IsFreeBSD)
434 Mapping.Offset = kFreeBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000435 else if (IsPS4CPU)
436 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000437 else if (IsLinux && IsX86_64) {
438 if (IsKasan)
439 Mapping.Offset = kLinuxKasan_ShadowOffset64;
440 else
441 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000442 } else if (IsWindows && IsX86_64) {
443 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000444 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000445 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000446 else if (IsIOS)
447 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000448 // We are using dynamic shadow offset on the 64-bit devices.
449 Mapping.Offset =
450 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000451 else if (IsAArch64)
452 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000453 else
454 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000455 }
456
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000457 if (ClForceDynamicShadow) {
458 Mapping.Offset = kDynamicShadowSentinel;
459 }
460
Alexey Samsonov1345d352013-01-16 13:23:28 +0000461 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000462 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000463 Mapping.Scale = ClMappingScale;
464 }
465
Ryan Govostes3f37df02016-05-06 10:25:22 +0000466 if (ClMappingOffset.getNumOccurrences() > 0) {
467 Mapping.Offset = ClMappingOffset;
468 }
469
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000470 // OR-ing shadow offset if more efficient (at least on x86) if the offset
471 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000472 // offset is not necessary 1/8-th of the address space. On SystemZ,
473 // we could OR the constant in a single instruction, but it's more
474 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000475 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
476 !(Mapping.Offset & (Mapping.Offset - 1)) &&
477 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000478
Alexey Samsonov1345d352013-01-16 13:23:28 +0000479 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000480}
481
Alexey Samsonov1345d352013-01-16 13:23:28 +0000482static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000483 // Redzone used for stack and globals is at least 32 bytes.
484 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000485 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000486}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000487
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000488/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000489struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000490 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
491 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000492 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000493 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000494 UseAfterScope(UseAfterScope || ClUseAfterScope),
495 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000496 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
497 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000498 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000499 return "AddressSanitizerFunctionPass";
500 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000501 void getAnalysisUsage(AnalysisUsage &AU) const override {
502 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000503 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000504 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000505 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000506 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000507 if (AI.isArrayAllocation()) {
508 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000509 assert(CI && "non-constant array size");
510 ArraySize = CI->getZExtValue();
511 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000512 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000513 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000514 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000515 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000516 }
517 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000518 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000519
Anna Zaks8ed1d812015-02-27 03:12:36 +0000520 /// If it is an interesting memory access, return the PointerOperand
521 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000522 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
523 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000524 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000525 uint64_t *TypeSize, unsigned *Alignment,
526 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000527 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000528 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000529 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000530 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
531 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000532 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000533 void instrumentUnusualSizeOrAlignment(Instruction *I,
534 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000535 uint32_t TypeSize, bool IsWrite,
536 Value *SizeArgument, bool UseCalls,
537 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000538 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
539 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000540 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000541 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000542 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000543 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000544 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000545 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000546 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000547 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000548 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000549 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000550 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000551 static char ID; // Pass identification, replacement for typeid
552
Yury Gribov3ae427d2014-12-01 08:47:58 +0000553 DominatorTree &getDominatorTree() const { return *DT; }
554
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000555 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000556 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000557
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000558 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000559 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000560 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
561 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000562
Reid Kleckner2f907552015-07-21 17:40:14 +0000563 /// Helper to cleanup per-function state.
564 struct FunctionStateRAII {
565 AddressSanitizer *Pass;
566 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
567 assert(Pass->ProcessedAllocas.empty() &&
568 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000569 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000570 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000571 ~FunctionStateRAII() {
572 Pass->LocalDynamicShadow = nullptr;
573 Pass->ProcessedAllocas.clear();
574 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000575 };
576
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000577 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000578 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000579 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000580 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000581 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000582 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000583 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000584 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000585 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000586 Function *AsanCtorFunction = nullptr;
587 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000588 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000589 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000590 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
591 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
592 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
593 // This array is indexed by AccessIsWrite and Experiment.
594 Function *AsanErrorCallbackSized[2][2];
595 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000596 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000597 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000598 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000599 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000600 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000601
602 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000603};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000604
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000605class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000606 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000607 explicit AddressSanitizerModule(bool CompileKernel = false,
608 bool Recover = false)
609 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
610 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000611 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000612 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000613 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000614
Mehdi Amini117296c2016-10-01 02:56:57 +0000615private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000616 void initializeCallbacks(Module &M);
617
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000618 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000619 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
620 ArrayRef<GlobalVariable *> ExtendedGlobals,
621 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000622 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
623 ArrayRef<GlobalVariable *> ExtendedGlobals,
624 ArrayRef<Constant *> MetadataInitializers,
625 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000626 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
627 ArrayRef<GlobalVariable *> ExtendedGlobals,
628 ArrayRef<Constant *> MetadataInitializers);
629 void
630 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
631 ArrayRef<GlobalVariable *> ExtendedGlobals,
632 ArrayRef<Constant *> MetadataInitializers);
633
634 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
635 StringRef OriginalName);
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000636 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
637 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000638 IRBuilder<> CreateAsanModuleDtor(Module &M);
639
Kostya Serebryany20a79972012-11-22 03:18:50 +0000640 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000641 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000642 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000643 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000644 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000645 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000646 return RedzoneSizeForScale(Mapping.Scale);
647 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000648
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000649 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000650 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000651 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000652 Type *IntptrTy;
653 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000654 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000655 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000656 Function *AsanPoisonGlobals;
657 Function *AsanUnpoisonGlobals;
658 Function *AsanRegisterGlobals;
659 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000660 Function *AsanRegisterImageGlobals;
661 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +0000662 Function *AsanRegisterElfGlobals;
663 Function *AsanUnregisterElfGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000664};
665
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000666// Stack poisoning does not play well with exception handling.
667// When an exception is thrown, we essentially bypass the code
668// that unpoisones the stack. This is why the run-time library has
669// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
670// stack in the interceptor. This however does not work inside the
671// actual function which catches the exception. Most likely because the
672// compiler hoists the load of the shadow value somewhere too high.
673// This causes asan to report a non-existing bug on 453.povray.
674// It sounds like an LLVM bug.
675struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
676 Function &F;
677 AddressSanitizer &ASan;
678 DIBuilder DIB;
679 LLVMContext *C;
680 Type *IntptrTy;
681 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000682 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000683
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000684 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000685 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000686 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000687 unsigned StackAlignment;
688
Kostya Serebryany6805de52013-09-10 13:16:56 +0000689 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000690 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000691 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000692 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000693 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000694
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000695 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
696 struct AllocaPoisonCall {
697 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000698 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000699 uint64_t Size;
700 bool DoPoison;
701 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000702 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
703 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000704
Yury Gribov98b18592015-05-28 07:51:49 +0000705 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
706 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
707 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000708 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000709
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000710 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000711 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000712 AllocaForValueMapTy AllocaForValue;
713
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000714 bool HasNonEmptyInlineAsm = false;
715 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000716 std::unique_ptr<CallInst> EmptyInlineAsm;
717
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000718 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000719 : F(F),
720 ASan(ASan),
721 DIB(*F.getParent(), /*AllowUnresolved*/ false),
722 C(ASan.C),
723 IntptrTy(ASan.IntptrTy),
724 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
725 Mapping(ASan.Mapping),
726 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000727 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000728
729 bool runOnFunction() {
730 if (!ClStack) return false;
731 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000732 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000733
Yury Gribov55441bb2014-11-21 10:29:50 +0000734 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000735
736 initializeCallbacks(*F.getParent());
737
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000738 processDynamicAllocas();
739 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000740
741 if (ClDebugStack) {
742 DEBUG(dbgs() << F);
743 }
744 return true;
745 }
746
Yury Gribov55441bb2014-11-21 10:29:50 +0000747 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000748 // poisoned red zones around all of them.
749 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000750 void processStaticAllocas();
751 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000752
Yury Gribov98b18592015-05-28 07:51:49 +0000753 void createDynamicAllocasInitStorage();
754
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000755 // ----------------------- Visitors.
756 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000757 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000758
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000759 /// \brief Collect all Resume instructions.
760 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
761
762 /// \brief Collect all CatchReturnInst instructions.
763 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
764
Yury Gribov98b18592015-05-28 07:51:49 +0000765 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
766 Value *SavedStack) {
767 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000768 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
769 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
770 // need to adjust extracted SP to compute the address of the most recent
771 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
772 // this purpose.
773 if (!isa<ReturnInst>(InstBefore)) {
774 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
775 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
776 {IntptrTy});
777
778 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
779
780 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
781 DynamicAreaOffset);
782 }
783
Yury Gribov781bce22015-05-28 08:03:28 +0000784 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000785 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000786 }
787
Yury Gribov55441bb2014-11-21 10:29:50 +0000788 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000789 void unpoisonDynamicAllocas() {
790 for (auto &Ret : RetVec)
791 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000792
Yury Gribov98b18592015-05-28 07:51:49 +0000793 for (auto &StackRestoreInst : StackRestoreVec)
794 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
795 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000796 }
797
Yury Gribov55441bb2014-11-21 10:29:50 +0000798 // Deploy and poison redzones around dynamic alloca call. To do this, we
799 // should replace this call with another one with changed parameters and
800 // replace all its uses with new address, so
801 // addr = alloca type, old_size, align
802 // is replaced by
803 // new_size = (old_size + additional_size) * sizeof(type)
804 // tmp = alloca i8, new_size, max(align, 32)
805 // addr = tmp + 32 (first 32 bytes are for the left redzone).
806 // Additional_size is added to make new memory allocation contain not only
807 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000808 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000809
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000810 /// \brief Collect Alloca instructions we want (and can) handle.
811 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000812 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000813 if (AI.isStaticAlloca()) {
814 // Skip over allocas that are present *before* the first instrumented
815 // alloca, we don't want to move those around.
816 if (AllocaVec.empty())
817 return;
818
819 StaticAllocasToMoveUp.push_back(&AI);
820 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000821 return;
822 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000823
824 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000825 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000826 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000827 else
828 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000829 }
830
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000831 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
832 /// errors.
833 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000834 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000835 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000836 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000837 if (!ASan.UseAfterScope)
838 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000839 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000840 return;
841 // Found lifetime intrinsic, add ASan instrumentation if necessary.
842 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
843 // If size argument is undefined, don't do anything.
844 if (Size->isMinusOne()) return;
845 // Check that size doesn't saturate uint64_t and can
846 // be stored in IntptrTy.
847 const uint64_t SizeValue = Size->getValue().getLimitedValue();
848 if (SizeValue == ~0ULL ||
849 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
850 return;
851 // Find alloca instruction that corresponds to llvm.lifetime argument.
852 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000853 if (!AI || !ASan.isInterestingAlloca(*AI))
854 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000855 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000856 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000857 if (AI->isStaticAlloca())
858 StaticAllocaPoisonCallVec.push_back(APC);
859 else if (ClInstrumentDynamicAllocas)
860 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000861 }
862
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000863 void visitCallSite(CallSite CS) {
864 Instruction *I = CS.getInstruction();
865 if (CallInst *CI = dyn_cast<CallInst>(I)) {
866 HasNonEmptyInlineAsm |=
867 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
868 HasReturnsTwiceCall |= CI->canReturnTwice();
869 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000870 }
871
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000872 // ---------------------- Helpers.
873 void initializeCallbacks(Module &M);
874
Yury Gribov3ae427d2014-12-01 08:47:58 +0000875 bool doesDominateAllExits(const Instruction *I) const {
876 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000877 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000878 }
879 return true;
880 }
881
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000882 /// Finds alloca where the value comes from.
883 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000884
885 // Copies bytes from ShadowBytes into shadow memory for indexes where
886 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
887 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
888 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
889 IRBuilder<> &IRB, Value *ShadowBase);
890 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
891 size_t Begin, size_t End, IRBuilder<> &IRB,
892 Value *ShadowBase);
893 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
894 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
895 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
896
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000897 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000898
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000899 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
900 bool Dynamic);
901 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
902 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000903};
904
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000905} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000906
907char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000908INITIALIZE_PASS_BEGIN(
909 AddressSanitizer, "asan",
910 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
911 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000912INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000913INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000914INITIALIZE_PASS_END(
915 AddressSanitizer, "asan",
916 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
917 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000918FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000919 bool Recover,
920 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000921 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000922 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000923}
924
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000925char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000926INITIALIZE_PASS(
927 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000928 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000929 "ModulePass",
930 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000931ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
932 bool Recover) {
933 assert(!CompileKernel || Recover);
934 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000935}
936
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000937static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000938 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000939 assert(Res < kNumberOfAccessSizes);
940 return Res;
941}
942
Bill Wendling58f8cef2013-08-06 22:52:42 +0000943// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000944static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
945 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000946 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000947 // We use private linkage for module-local strings. If they can be merged
948 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000949 GlobalVariable *GV =
950 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000951 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000952 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000953 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
954 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000955}
956
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000957/// \brief Create a global describing a source location.
958static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
959 LocationMetadata MD) {
960 Constant *LocData[] = {
961 createPrivateGlobalForString(M, MD.Filename, true),
962 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
963 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
964 };
965 auto LocStruct = ConstantStruct::getAnon(LocData);
966 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
967 GlobalValue::PrivateLinkage, LocStruct,
968 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000969 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000970 return GV;
971}
972
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000973/// \brief Check if \p G has been created by a trusted compiler pass.
974static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
975 // Do not instrument asan globals.
976 if (G->getName().startswith(kAsanGenPrefix) ||
977 G->getName().startswith(kSanCovGenPrefix) ||
978 G->getName().startswith(kODRGenPrefix))
979 return true;
980
981 // Do not instrument gcov counter arrays.
982 if (G->getName() == "__llvm_gcov_ctr")
983 return true;
984
985 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000986}
987
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000988Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
989 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000990 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000991 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000992 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000993 Value *ShadowBase;
994 if (LocalDynamicShadow)
995 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +0000996 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000997 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
998 if (Mapping.OrShadowOffset)
999 return IRB.CreateOr(Shadow, ShadowBase);
1000 else
1001 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001002}
1003
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001004// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001005void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1006 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001007 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001008 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001009 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001010 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1011 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1012 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001013 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001014 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001015 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001016 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1017 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1018 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001019 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001020 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001021}
1022
Anna Zaks8ed1d812015-02-27 03:12:36 +00001023/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001024bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001025 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1026
1027 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1028 return PreviouslySeenAllocaInfo->getSecond();
1029
Yury Gribov98b18592015-05-28 07:51:49 +00001030 bool IsInteresting =
1031 (AI.getAllocatedType()->isSized() &&
1032 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001033 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001034 // We are only interested in allocas not promotable to registers.
1035 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001036 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1037 // inalloca allocas are not treated as static, and we don't want
1038 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001039 !AI.isUsedWithInAlloca() &&
1040 // swifterror allocas are register promoted by ISel
1041 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001042
1043 ProcessedAllocas[&AI] = IsInteresting;
1044 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001045}
1046
Anna Zaks8ed1d812015-02-27 03:12:36 +00001047Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1048 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001049 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001050 unsigned *Alignment,
1051 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001052 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001053 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001054
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001055 // Do not instrument the load fetching the dynamic shadow address.
1056 if (LocalDynamicShadow == I)
1057 return nullptr;
1058
Anna Zaks8ed1d812015-02-27 03:12:36 +00001059 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001060 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001061 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001062 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001063 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001064 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001065 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001066 PtrOperand = LI->getPointerOperand();
1067 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001068 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001069 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001070 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001071 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001072 PtrOperand = SI->getPointerOperand();
1073 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001074 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001075 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001076 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001077 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001078 PtrOperand = RMW->getPointerOperand();
1079 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001080 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001081 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001082 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001083 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001084 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001085 } else if (auto CI = dyn_cast<CallInst>(I)) {
1086 auto *F = dyn_cast<Function>(CI->getCalledValue());
1087 if (F && (F->getName().startswith("llvm.masked.load.") ||
1088 F->getName().startswith("llvm.masked.store."))) {
1089 unsigned OpOffset = 0;
1090 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001091 if (!ClInstrumentWrites)
1092 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001093 // Masked store has an initial operand for the value.
1094 OpOffset = 1;
1095 *IsWrite = true;
1096 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001097 if (!ClInstrumentReads)
1098 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001099 *IsWrite = false;
1100 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001101
1102 auto BasePtr = CI->getOperand(0 + OpOffset);
1103 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1104 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1105 if (auto AlignmentConstant =
1106 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1107 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1108 else
1109 *Alignment = 1; // No alignment guarantees. We probably got Undef
1110 if (MaybeMask)
1111 *MaybeMask = CI->getOperand(2 + OpOffset);
1112 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001113 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001114 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001115
Anna Zaks644d9d32016-06-22 00:15:52 +00001116 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001117 // Do not instrument acesses from different address spaces; we cannot deal
1118 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001119 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1120 if (PtrTy->getPointerAddressSpace() != 0)
1121 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001122
1123 // Ignore swifterror addresses.
1124 // swifterror memory addresses are mem2reg promoted by instruction
1125 // selection. As such they cannot have regular uses like an instrumentation
1126 // function and it makes no sense to track them as memory.
1127 if (PtrOperand->isSwiftError())
1128 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001129 }
1130
Anna Zaks8ed1d812015-02-27 03:12:36 +00001131 // Treat memory accesses to promotable allocas as non-interesting since they
1132 // will not cause memory violations. This greatly speeds up the instrumented
1133 // executable at -O0.
1134 if (ClSkipPromotableAllocas)
1135 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1136 return isInterestingAlloca(*AI) ? AI : nullptr;
1137
1138 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001139}
1140
Kostya Serebryany796f6552014-02-27 12:45:36 +00001141static bool isPointerOperand(Value *V) {
1142 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1143}
1144
1145// This is a rough heuristic; it may cause both false positives and
1146// false negatives. The proper implementation requires cooperation with
1147// the frontend.
1148static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1149 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001150 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001151 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001152 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001153 } else {
1154 return false;
1155 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001156 return isPointerOperand(I->getOperand(0)) &&
1157 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001158}
1159
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001160bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1161 // If a global variable does not have dynamic initialization we don't
1162 // have to instrument it. However, if a global does not have initializer
1163 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001164 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001165}
1166
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001167void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1168 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001169 IRBuilder<> IRB(I);
1170 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1171 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001172 for (Value *&i : Param) {
1173 if (i->getType()->isPointerTy())
1174 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001175 }
David Blaikieff6409d2015-05-18 22:13:54 +00001176 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001177}
1178
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001179static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001180 Instruction *InsertBefore, Value *Addr,
1181 unsigned Alignment, unsigned Granularity,
1182 uint32_t TypeSize, bool IsWrite,
1183 Value *SizeArgument, bool UseCalls,
1184 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001185 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1186 // if the data is properly aligned.
1187 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1188 TypeSize == 128) &&
1189 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001190 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1191 nullptr, UseCalls, Exp);
1192 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1193 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001194}
1195
1196static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1197 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001198 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001199 Value *Addr, unsigned Alignment,
1200 unsigned Granularity, uint32_t TypeSize,
1201 bool IsWrite, Value *SizeArgument,
1202 bool UseCalls, uint32_t Exp) {
1203 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1204 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1205 unsigned Num = VTy->getVectorNumElements();
1206 auto Zero = ConstantInt::get(IntptrTy, 0);
1207 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001208 Value *InstrumentedAddress = nullptr;
1209 Instruction *InsertBefore = I;
1210 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1211 // dyn_cast as we might get UndefValue
1212 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1213 if (Masked->isNullValue())
1214 // Mask is constant false, so no instrumentation needed.
1215 continue;
1216 // If we have a true or undef value, fall through to doInstrumentAddress
1217 // with InsertBefore == I
1218 }
1219 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001220 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001221 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1222 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1223 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001224 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001225
1226 IRBuilder<> IRB(InsertBefore);
1227 InstrumentedAddress =
1228 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1229 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1230 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1231 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001232 }
1233}
1234
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001235void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001236 Instruction *I, bool UseCalls,
1237 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001238 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001239 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001240 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001241 Value *MaybeMask = nullptr;
1242 Value *Addr =
1243 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001244 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001245
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001246 // Optimization experiments.
1247 // The experiments can be used to evaluate potential optimizations that remove
1248 // instrumentation (assess false negatives). Instead of completely removing
1249 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1250 // experiments that want to remove instrumentation of this instruction).
1251 // If Exp is non-zero, this pass will emit special calls into runtime
1252 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1253 // make runtime terminate the program in a special way (with a different
1254 // exit status). Then you run the new compiler on a buggy corpus, collect
1255 // the special terminations (ideally, you don't see them at all -- no false
1256 // negatives) and make the decision on the optimization.
1257 uint32_t Exp = ClForceExperiment;
1258
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001259 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001260 // If initialization order checking is disabled, a simple access to a
1261 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001262 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001263 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001264 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1265 NumOptimizedAccessesToGlobalVar++;
1266 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001267 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001268 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001269
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001270 if (ClOpt && ClOptStack) {
1271 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001272 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001273 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1274 NumOptimizedAccessesToStackVar++;
1275 return;
1276 }
1277 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001278
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001279 if (IsWrite)
1280 NumInstrumentedWrites++;
1281 else
1282 NumInstrumentedReads++;
1283
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001284 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001285 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001286 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1287 Alignment, Granularity, TypeSize, IsWrite,
1288 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001289 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001290 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001291 IsWrite, nullptr, UseCalls, Exp);
1292 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001293}
1294
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001295Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1296 Value *Addr, bool IsWrite,
1297 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001298 Value *SizeArgument,
1299 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001300 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001301 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1302 CallInst *Call = nullptr;
1303 if (SizeArgument) {
1304 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001305 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1306 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001307 else
David Blaikieff6409d2015-05-18 22:13:54 +00001308 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1309 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001310 } else {
1311 if (Exp == 0)
1312 Call =
1313 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1314 else
David Blaikieff6409d2015-05-18 22:13:54 +00001315 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1316 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001317 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001318
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001319 // We don't do Call->setDoesNotReturn() because the BB already has
1320 // UnreachableInst at the end.
1321 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001322 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001323 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001324}
1325
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001326Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001327 Value *ShadowValue,
1328 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001329 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001330 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001331 Value *LastAccessedByte =
1332 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001333 // (Addr & (Granularity - 1)) + size - 1
1334 if (TypeSize / 8 > 1)
1335 LastAccessedByte = IRB.CreateAdd(
1336 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1337 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001338 LastAccessedByte =
1339 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001340 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1341 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1342}
1343
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001344void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001345 Instruction *InsertBefore, Value *Addr,
1346 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001347 Value *SizeArgument, bool UseCalls,
1348 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001349 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001350 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001351 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1352
1353 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001354 if (Exp == 0)
1355 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1356 AddrLong);
1357 else
David Blaikieff6409d2015-05-18 22:13:54 +00001358 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1359 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001360 return;
1361 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001362
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001363 Type *ShadowTy =
1364 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001365 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1366 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1367 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001368 Value *ShadowValue =
1369 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001370
1371 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001372 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001373 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001374
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001375 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001376 // We use branch weights for the slow path check, to indicate that the slow
1377 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001378 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1379 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001380 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001381 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001382 IRB.SetInsertPoint(CheckTerm);
1383 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001384 if (Recover) {
1385 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1386 } else {
1387 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001388 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001389 CrashTerm = new UnreachableInst(*C, CrashBlock);
1390 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1391 ReplaceInstWithInst(CheckTerm, NewTerm);
1392 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001393 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001394 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001395 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001396
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001397 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001398 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001399 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001400}
1401
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001402// Instrument unusual size or unusual alignment.
1403// We can not do it with a single check, so we do 1-byte check for the first
1404// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1405// to report the actual access size.
1406void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001407 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1408 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1409 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001410 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1411 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1412 if (UseCalls) {
1413 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001414 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1415 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001416 else
David Blaikieff6409d2015-05-18 22:13:54 +00001417 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1418 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001419 } else {
1420 Value *LastByte = IRB.CreateIntToPtr(
1421 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1422 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001423 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1424 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001425 }
1426}
1427
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001428void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1429 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001430 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001431 IRBuilder<> IRB(&GlobalInit.front(),
1432 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001433
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001434 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001435 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1436 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001437
1438 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001439 for (auto &BB : GlobalInit.getBasicBlockList())
1440 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001441 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001442}
1443
1444void AddressSanitizerModule::createInitializerPoisonCalls(
1445 Module &M, GlobalValue *ModuleName) {
1446 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1447
1448 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1449 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001450 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001451 ConstantStruct *CS = cast<ConstantStruct>(OP);
1452
1453 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001454 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001455 if (F->getName() == kAsanModuleCtorName) continue;
1456 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1457 // Don't instrument CTORs that will run before asan.module_ctor.
1458 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1459 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001460 }
1461 }
1462}
1463
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001464bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001465 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001466 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001467
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001468 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001469 if (!Ty->isSized()) return false;
1470 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001471 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001472 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001473 // Don't handle ODR linkage types and COMDATs since other modules may be built
1474 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001475 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1476 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1477 G->getLinkage() != GlobalVariable::InternalLinkage)
1478 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001479 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001480 // Two problems with thread-locals:
1481 // - The address of the main thread's copy can't be computed at link-time.
1482 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001483 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001484 // For now, just ignore this Global if the alignment is large.
1485 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001486
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001487 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001488 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001489
Anna Zaks11904602015-06-09 00:58:08 +00001490 // Globals from llvm.metadata aren't emitted, do not instrument them.
1491 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001492 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001493 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001494
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001495 // Do not instrument function pointers to initialization and termination
1496 // routines: dynamic linker will not properly handle redzones.
1497 if (Section.startswith(".preinit_array") ||
1498 Section.startswith(".init_array") ||
1499 Section.startswith(".fini_array")) {
1500 return false;
1501 }
1502
Anna Zaks11904602015-06-09 00:58:08 +00001503 // Callbacks put into the CRT initializer/terminator sections
1504 // should not be instrumented.
1505 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1506 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1507 if (Section.startswith(".CRT")) {
1508 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1509 return false;
1510 }
1511
Kuba Brecka1001bb52014-12-05 22:19:18 +00001512 if (TargetTriple.isOSBinFormatMachO()) {
1513 StringRef ParsedSegment, ParsedSection;
1514 unsigned TAA = 0, StubSize = 0;
1515 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001516 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1517 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001518 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001519
1520 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1521 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1522 // them.
1523 if (ParsedSegment == "__OBJC" ||
1524 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1525 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1526 return false;
1527 }
1528 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1529 // Constant CFString instances are compiled in the following way:
1530 // -- the string buffer is emitted into
1531 // __TEXT,__cstring,cstring_literals
1532 // -- the constant NSConstantString structure referencing that buffer
1533 // is placed into __DATA,__cfstring
1534 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1535 // Moreover, it causes the linker to crash on OS X 10.7
1536 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1537 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1538 return false;
1539 }
1540 // The linker merges the contents of cstring_literals and removes the
1541 // trailing zeroes.
1542 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1543 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1544 return false;
1545 }
1546 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001547 }
1548
1549 return true;
1550}
1551
Ryan Govostes653f9d02016-03-28 20:28:57 +00001552// On Mach-O platforms, we emit global metadata in a separate section of the
1553// binary in order to allow the linker to properly dead strip. This is only
1554// supported on recent versions of ld64.
1555bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
Ryan Govostese51401b2016-07-05 21:53:08 +00001556 if (!ClUseMachOGlobalsSection)
1557 return false;
1558
Ryan Govostes653f9d02016-03-28 20:28:57 +00001559 if (!TargetTriple.isOSBinFormatMachO())
1560 return false;
1561
1562 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1563 return true;
1564 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001565 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001566 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1567 return true;
1568
1569 return false;
1570}
1571
Reid Kleckner01660a32016-11-21 20:40:37 +00001572StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1573 switch (TargetTriple.getObjectFormat()) {
1574 case Triple::COFF: return ".ASAN$GL";
1575 case Triple::ELF: return "asan_globals";
1576 case Triple::MachO: return "__DATA,__asan_globals,regular";
1577 default: break;
1578 }
1579 llvm_unreachable("unsupported object format");
1580}
1581
Alexey Samsonov788381b2012-12-25 12:28:20 +00001582void AddressSanitizerModule::initializeCallbacks(Module &M) {
1583 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001584
Alexey Samsonov788381b2012-12-25 12:28:20 +00001585 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001586 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001587 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001588 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001589 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001590 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001591 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001592
Alexey Samsonov788381b2012-12-25 12:28:20 +00001593 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001594 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001595 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001596 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001597 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001598 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1599 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001600 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001601
1602 // Declare the functions that find globals in a shared object and then invoke
1603 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001604 AsanRegisterImageGlobals =
1605 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1606 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001607 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001608
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001609 AsanUnregisterImageGlobals =
1610 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1611 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001612 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00001613
1614 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1615 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1616 IntptrTy, IntptrTy, IntptrTy, nullptr));
1617 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1618
1619 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1620 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1621 IntptrTy, IntptrTy, IntptrTy, nullptr));
1622 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001623}
1624
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001625// Put the metadata and the instrumented global in the same group. This ensures
1626// that the metadata is discarded if the instrumented global is discarded.
1627void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00001628 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001629 Module &M = *G->getParent();
1630 Comdat *C = G->getComdat();
1631 if (!C) {
1632 if (!G->hasName()) {
1633 // If G is unnamed, it must be internal. Give it an artificial name
1634 // so we can put it in a comdat.
1635 assert(G->hasLocalLinkage());
1636 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1637 }
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00001638
1639 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1640 std::string Name = G->getName();
1641 Name += InternalSuffix;
1642 C = M.getOrInsertComdat(Name);
1643 } else {
1644 C = M.getOrInsertComdat(G->getName());
1645 }
1646
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001647 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1648 if (TargetTriple.isOSBinFormatCOFF())
1649 C->setSelectionKind(Comdat::NoDuplicates);
1650 G->setComdat(C);
1651 }
1652
1653 assert(G->hasComdat());
1654 Metadata->setComdat(G->getComdat());
1655}
1656
1657// Create a separate metadata global and put it in the appropriate ASan
1658// global registration section.
1659GlobalVariable *
1660AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1661 StringRef OriginalName) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001662 GlobalVariable *Metadata =
1663 new GlobalVariable(M, Initializer->getType(), false,
1664 GlobalVariable::InternalLinkage, Initializer,
1665 Twine("__asan_global_") +
1666 GlobalValue::getRealLinkageName(OriginalName));
1667 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001668 return Metadata;
1669}
1670
1671IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
1672 Function *AsanDtorFunction =
1673 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1674 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1675 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1676 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1677
1678 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1679}
1680
1681void AddressSanitizerModule::InstrumentGlobalsCOFF(
1682 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1683 ArrayRef<Constant *> MetadataInitializers) {
1684 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001685 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001686
1687 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001688 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001689 GlobalVariable *G = ExtendedGlobals[i];
1690 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001691 CreateMetadataGlobal(M, Initializer, G->getName());
1692
1693 // The MSVC linker always inserts padding when linking incrementally. We
1694 // cope with that by aligning each struct to its size, which must be a power
1695 // of two.
1696 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1697 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1698 "global metadata will not be padded appropriately");
1699 Metadata->setAlignment(SizeOfGlobalStruct);
1700
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00001701 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001702 }
1703}
1704
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00001705void AddressSanitizerModule::InstrumentGlobalsELF(
1706 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1707 ArrayRef<Constant *> MetadataInitializers,
1708 const std::string &UniqueModuleId) {
1709 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1710
1711 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1712 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1713 GlobalVariable *G = ExtendedGlobals[i];
1714 GlobalVariable *Metadata =
1715 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1716 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1717 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1718 MetadataGlobals[i] = Metadata;
1719
1720 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1721 }
1722
1723 // Update llvm.compiler.used, adding the new metadata globals. This is
1724 // needed so that during LTO these variables stay alive.
1725 if (!MetadataGlobals.empty())
1726 appendToCompilerUsed(M, MetadataGlobals);
1727
1728 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1729 // to look up the loaded image that contains it. Second, we can store in it
1730 // whether registration has already occurred, to prevent duplicate
1731 // registration.
1732 //
1733 // Common linkage ensures that there is only one global per shared library.
1734 GlobalVariable *RegisteredFlag = new GlobalVariable(
1735 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1736 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1737 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1738
1739 // Create start and stop symbols.
1740 GlobalVariable *StartELFMetadata = new GlobalVariable(
1741 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1742 "__start_" + getGlobalMetadataSection());
1743 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1744 GlobalVariable *StopELFMetadata = new GlobalVariable(
1745 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1746 "__stop_" + getGlobalMetadataSection());
1747 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1748
1749 // Create a call to register the globals with the runtime.
1750 IRB.CreateCall(AsanRegisterElfGlobals,
1751 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1752 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1753 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1754
1755 // We also need to unregister globals at the end, e.g., when a shared library
1756 // gets closed.
1757 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1758 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1759 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1760 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1761 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1762}
1763
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001764void AddressSanitizerModule::InstrumentGlobalsMachO(
1765 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1766 ArrayRef<Constant *> MetadataInitializers) {
1767 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1768
1769 // On recent Mach-O platforms, use a structure which binds the liveness of
1770 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1771 // created to be added to llvm.compiler.used
1772 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1773 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1774
1775 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1776 Constant *Initializer = MetadataInitializers[i];
1777 GlobalVariable *G = ExtendedGlobals[i];
1778 GlobalVariable *Metadata =
1779 CreateMetadataGlobal(M, Initializer, G->getName());
1780
1781 // On recent Mach-O platforms, we emit the global metadata in a way that
1782 // allows the linker to properly strip dead globals.
1783 auto LivenessBinder = ConstantStruct::get(
1784 LivenessTy, Initializer->getAggregateElement(0u),
1785 ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1786 GlobalVariable *Liveness = new GlobalVariable(
1787 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1788 Twine("__asan_binder_") + G->getName());
1789 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1790 LivenessGlobals[i] = Liveness;
1791 }
1792
1793 // Update llvm.compiler.used, adding the new liveness globals. This is
1794 // needed so that during LTO these variables stay alive. The alternative
1795 // would be to have the linker handling the LTO symbols, but libLTO
1796 // current API does not expose access to the section for each symbol.
1797 if (!LivenessGlobals.empty())
1798 appendToCompilerUsed(M, LivenessGlobals);
1799
1800 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1801 // to look up the loaded image that contains it. Second, we can store in it
1802 // whether registration has already occurred, to prevent duplicate
1803 // registration.
1804 //
1805 // common linkage ensures that there is only one global per shared library.
1806 GlobalVariable *RegisteredFlag = new GlobalVariable(
1807 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1808 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1809 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1810
1811 IRB.CreateCall(AsanRegisterImageGlobals,
1812 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1813
1814 // We also need to unregister globals at the end, e.g., when a shared library
1815 // gets closed.
1816 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1817 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1818 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1819}
1820
1821void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1822 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1823 ArrayRef<Constant *> MetadataInitializers) {
1824 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1825 unsigned N = ExtendedGlobals.size();
1826 assert(N > 0);
1827
1828 // On platforms that don't have a custom metadata section, we emit an array
1829 // of global metadata structures.
1830 ArrayType *ArrayOfGlobalStructTy =
1831 ArrayType::get(MetadataInitializers[0]->getType(), N);
1832 auto AllGlobals = new GlobalVariable(
1833 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1834 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1835
1836 IRB.CreateCall(AsanRegisterGlobals,
1837 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1838 ConstantInt::get(IntptrTy, N)});
1839
1840 // We also need to unregister globals at the end, e.g., when a shared library
1841 // gets closed.
1842 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1843 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1844 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1845 ConstantInt::get(IntptrTy, N)});
1846}
1847
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001848// This function replaces all global variables with new variables that have
1849// trailing redzones. It also creates a function that poisons
1850// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001851bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001852 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001853
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001854 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1855
Alexey Samsonova02e6642014-05-29 18:40:48 +00001856 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001857 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001858 }
1859
1860 size_t n = GlobalsToChange.size();
1861 if (n == 0) return false;
1862
Reid Kleckner78565832016-11-29 01:32:21 +00001863 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001864
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001865 // A global is described by a structure
1866 // size_t beg;
1867 // size_t size;
1868 // size_t size_with_redzone;
1869 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001870 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001871 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001872 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001873 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001874 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001875 StructType *GlobalStructTy =
1876 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001877 IntptrTy, IntptrTy, IntptrTy, nullptr);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001878 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1879 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001880
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001881 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001882
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001883 // We shouldn't merge same module names, as this string serves as unique
1884 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001885 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001886 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001887
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001888 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001889 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001890 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001891
1892 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001893 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001894 // Create string holding the global name (use global name from metadata
1895 // if it's available, otherwise just write the name of global variable).
1896 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001897 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001898 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001899
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001900 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001901 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001902 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001903 // MinRZ <= RZ <= kMaxGlobalRedzone
1904 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001905 uint64_t RZ = std::max(
1906 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001907 uint64_t RightRedzoneSize = RZ;
1908 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001909 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001910 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001911 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1912
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001913 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001914 Constant *NewInitializer =
1915 ConstantStruct::get(NewTy, G->getInitializer(),
1916 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001917
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001918 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001919 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1920 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1921 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001922 GlobalVariable *NewGlobal =
1923 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1924 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001925 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001926 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001927
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001928 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1929 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1930 G->isConstant()) {
1931 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1932 if (Seq && Seq->isCString())
1933 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1934 }
1935
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001936 // Transfer the debug info. The payload starts at offset zero so we can
1937 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001938 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001939 G->getDebugInfo(GVs);
1940 for (auto *GV : GVs)
1941 NewGlobal->addDebugInfo(GV);
1942
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001943 Value *Indices2[2];
1944 Indices2[0] = IRB.getInt32(0);
1945 Indices2[1] = IRB.getInt32(0);
1946
1947 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001948 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001949 NewGlobal->takeName(G);
1950 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001951 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001952
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001953 Constant *SourceLoc;
1954 if (!MD.SourceLoc.empty()) {
1955 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1956 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1957 } else {
1958 SourceLoc = ConstantInt::get(IntptrTy, 0);
1959 }
1960
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001961 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1962 GlobalValue *InstrumentedGlobal = NewGlobal;
1963
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001964 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00001965 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1966 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001967 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1968 // Create local alias for NewGlobal to avoid crash on ODR between
1969 // instrumented and non-instrumented libraries.
1970 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1971 NameForGlobal + M.getName(), NewGlobal);
1972
1973 // With local aliases, we need to provide another externally visible
1974 // symbol __odr_asan_XXX to detect ODR violation.
1975 auto *ODRIndicatorSym =
1976 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1977 Constant::getNullValue(IRB.getInt8Ty()),
1978 kODRGenPrefix + NameForGlobal, nullptr,
1979 NewGlobal->getThreadLocalMode());
1980
1981 // Set meaningful attributes for indicator symbol.
1982 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1983 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1984 ODRIndicatorSym->setAlignment(1);
1985 ODRIndicator = ODRIndicatorSym;
1986 InstrumentedGlobal = GA;
1987 }
1988
Reid Kleckner01660a32016-11-21 20:40:37 +00001989 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001990 GlobalStructTy,
1991 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001992 ConstantInt::get(IntptrTy, SizeInBytes),
1993 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1994 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001995 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001996 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1997 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001998
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001999 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002000
Kostya Serebryany20343352012-10-17 13:40:06 +00002001 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002002
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002003 Initializers[i] = Initializer;
2004 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002005
Evgeniy Stepanovc5aa6b92017-03-17 22:17:29 +00002006 std::string ELFUniqueModuleId =
2007 TargetTriple.isOSBinFormatELF() ? getUniqueModuleId(&M) : "";
2008
2009 if (!ELFUniqueModuleId.empty()) {
2010 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2011 } else if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002012 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
2013 } else if (ShouldUseMachOGlobalsSection()) {
2014 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2015 } else {
2016 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002017 }
2018
Reid Kleckner01660a32016-11-21 20:40:37 +00002019 // Create calls for poisoning before initializers run and unpoisoning after.
2020 if (HasDynamicallyInitializedGlobals)
2021 createInitializerPoisonCalls(M, ModuleName);
2022
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002023 DEBUG(dbgs() << M);
2024 return true;
2025}
2026
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002027bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002028 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002029 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002030 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002031 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002032 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002033 initializeCallbacks(M);
2034
2035 bool Changed = false;
2036
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002037 // TODO(glider): temporarily disabled globals instrumentation for KASan.
2038 if (ClGlobals && !CompileKernel) {
2039 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
2040 assert(CtorFunc);
2041 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
2042 Changed |= InstrumentGlobals(IRB, M);
2043 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002044
2045 return Changed;
2046}
2047
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002048void AddressSanitizer::initializeCallbacks(Module &M) {
2049 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002050 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002051 // IsWrite, TypeSize and Exp are encoded in the function name.
2052 for (int Exp = 0; Exp < 2; Exp++) {
2053 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2054 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2055 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002056 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002057 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00002058 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002059 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002060 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00002061 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002062 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
2063 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002064 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002065 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002066 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
2067 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2068 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002069 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002070 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002071 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00002072 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002073 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002074 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002075 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002076 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2077 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002078 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002079 }
2080 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002081
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002082 const std::string MemIntrinCallbackPrefix =
2083 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002084 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002085 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002086 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002087 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002088 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002089 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002090 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002091 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002092 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002093
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002094 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002095 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002096
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002097 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002098 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002099 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00002100 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002101 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2102 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2103 StringRef(""), StringRef(""),
2104 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002105}
2106
2107// virtual
2108bool AddressSanitizer::doInitialization(Module &M) {
2109 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00002110
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002111 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002112
2113 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002114 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002115 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002116 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002117
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002118 if (!CompileKernel) {
2119 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00002120 createSanitizerCtorAndInitFunctions(
2121 M, kAsanModuleCtorName, kAsanInitName,
2122 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002123 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2124 }
2125 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002126 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002127}
2128
Keno Fischere03fae42015-12-05 14:42:34 +00002129bool AddressSanitizer::doFinalization(Module &M) {
2130 GlobalsMD.reset();
2131 return false;
2132}
2133
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002134bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2135 // For each NSObject descendant having a +load method, this method is invoked
2136 // by the ObjC runtime before any of the static constructors is called.
2137 // Therefore we need to instrument such methods with a call to __asan_init
2138 // at the beginning in order to initialize our runtime before any access to
2139 // the shadow memory.
2140 // We cannot just ignore these methods, because they may call other
2141 // instrumented functions.
2142 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002143 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002144 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002145 return true;
2146 }
2147 return false;
2148}
2149
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002150void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2151 // Generate code only when dynamic addressing is needed.
2152 if (Mapping.Offset != kDynamicShadowSentinel)
2153 return;
2154
2155 IRBuilder<> IRB(&F.front().front());
2156 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2157 kAsanShadowMemoryDynamicAddress, IntptrTy);
2158 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2159}
2160
Reid Kleckner2f907552015-07-21 17:40:14 +00002161void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2162 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2163 // to it as uninteresting. This assumes we haven't started processing allocas
2164 // yet. This check is done up front because iterating the use list in
2165 // isInterestingAlloca would be algorithmically slower.
2166 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2167
2168 // Try to get the declaration of llvm.localescape. If it's not in the module,
2169 // we can exit early.
2170 if (!F.getParent()->getFunction("llvm.localescape")) return;
2171
2172 // Look for a call to llvm.localescape call in the entry block. It can't be in
2173 // any other block.
2174 for (Instruction &I : F.getEntryBlock()) {
2175 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2176 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2177 // We found a call. Mark all the allocas passed in as uninteresting.
2178 for (Value *Arg : II->arg_operands()) {
2179 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2180 assert(AI && AI->isStaticAlloca() &&
2181 "non-static alloca arg to localescape");
2182 ProcessedAllocas[AI] = false;
2183 }
2184 break;
2185 }
2186 }
2187}
2188
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002189bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002190 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002191 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002192 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002193 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002194
Etienne Bergeron78582b22016-09-15 15:45:05 +00002195 bool FunctionModified = false;
2196
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002197 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002198 // This function needs to be called even if the function body is not
2199 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002200 if (maybeInsertAsanInitAtFunctionEntry(F))
2201 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002202
2203 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002204 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002205
Etienne Bergeron752f8832016-09-14 17:18:37 +00002206 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2207
2208 initializeCallbacks(*F.getParent());
2209 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002210
Reid Kleckner2f907552015-07-21 17:40:14 +00002211 FunctionStateRAII CleanupObj(this);
2212
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002213 maybeInsertDynamicShadowAtFunctionEntry(F);
2214
Reid Kleckner2f907552015-07-21 17:40:14 +00002215 // We can't instrument allocas used with llvm.localescape. Only static allocas
2216 // can be passed to that intrinsic.
2217 markEscapedLocalAllocas(F);
2218
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002219 // We want to instrument every address only once per basic block (unless there
2220 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002221 SmallSet<Value *, 16> TempsToInstrument;
2222 SmallVector<Instruction *, 16> ToInstrument;
2223 SmallVector<Instruction *, 8> NoReturnCalls;
2224 SmallVector<BasicBlock *, 16> AllBlocks;
2225 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002226 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002227 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002228 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002229 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002230 const TargetLibraryInfo *TLI =
2231 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002232
2233 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002234 for (auto &BB : F) {
2235 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002236 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002237 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002238 for (auto &Inst : BB) {
2239 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002240 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002241 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002242 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002243 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002244 // If we have a mask, skip instrumentation if we've already
2245 // instrumented the full object. But don't add to TempsToInstrument
2246 // because we might get another load/store with a different mask.
2247 if (MaybeMask) {
2248 if (TempsToInstrument.count(Addr))
2249 continue; // We've seen this (whole) temp in the current BB.
2250 } else {
2251 if (!TempsToInstrument.insert(Addr).second)
2252 continue; // We've seen this temp in the current BB.
2253 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002254 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002255 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002256 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2257 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002258 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002259 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002260 // ok, take it.
2261 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002262 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002263 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002264 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002265 // A call inside BB.
2266 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002267 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002268 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002269 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2270 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002271 continue;
2272 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002273 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002274 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002275 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002276 }
2277 }
2278
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002279 bool UseCalls =
2280 CompileKernel ||
2281 (ClInstrumentationWithCallsThreshold >= 0 &&
2282 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002283 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002284 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
2285 /*RoundToAlign=*/true);
2286
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002287 // Instrument.
2288 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002289 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002290 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2291 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002292 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002293 instrumentMop(ObjSizeVis, Inst, UseCalls,
2294 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002295 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002296 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002297 }
2298 NumInstrumented++;
2299 }
2300
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002301 FunctionStackPoisoner FSP(F, *this);
2302 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002303
2304 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2305 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002306 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002307 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002308 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002309 }
2310
Alexey Samsonova02e6642014-05-29 18:40:48 +00002311 for (auto Inst : PointerComparisonsOrSubtracts) {
2312 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002313 NumInstrumented++;
2314 }
2315
Etienne Bergeron78582b22016-09-15 15:45:05 +00002316 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2317 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002318
Etienne Bergeron78582b22016-09-15 15:45:05 +00002319 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2320 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002321
Etienne Bergeron78582b22016-09-15 15:45:05 +00002322 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002323}
2324
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002325// Workaround for bug 11395: we don't want to instrument stack in functions
2326// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2327// FIXME: remove once the bug 11395 is fixed.
2328bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2329 if (LongSize != 32) return false;
2330 CallInst *CI = dyn_cast<CallInst>(I);
2331 if (!CI || !CI->isInlineAsm()) return false;
2332 if (CI->getNumArgOperands() <= 5) return false;
2333 // We have inline assembly with quite a few arguments.
2334 return true;
2335}
2336
2337void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2338 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002339 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2340 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002341 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2342 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2343 IntptrTy, nullptr));
2344 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002345 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2346 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002347 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002348 if (ASan.UseAfterScope) {
2349 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2350 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2351 IntptrTy, IntptrTy, nullptr));
2352 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2353 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2354 IntptrTy, IntptrTy, nullptr));
2355 }
2356
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002357 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2358 std::ostringstream Name;
2359 Name << kAsanSetShadowPrefix;
2360 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2361 AsanSetShadowFunc[Val] =
2362 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2363 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002364 }
2365
Yury Gribov98b18592015-05-28 07:51:49 +00002366 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2367 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2368 AsanAllocasUnpoisonFunc =
2369 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2370 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002371}
2372
Vitaly Buka793913c2016-08-29 18:17:21 +00002373void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2374 ArrayRef<uint8_t> ShadowBytes,
2375 size_t Begin, size_t End,
2376 IRBuilder<> &IRB,
2377 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002378 if (Begin >= End)
2379 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002380
2381 const size_t LargestStoreSizeInBytes =
2382 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2383
2384 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2385
2386 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002387 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2388 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2389 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002390 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002391 if (!ShadowMask[i]) {
2392 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002393 ++i;
2394 continue;
2395 }
2396
2397 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2398 // Fit store size into the range.
2399 while (StoreSizeInBytes > End - i)
2400 StoreSizeInBytes /= 2;
2401
2402 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002403 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002404 while (j <= StoreSizeInBytes / 2)
2405 StoreSizeInBytes /= 2;
2406 }
2407
2408 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002409 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2410 if (IsLittleEndian)
2411 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2412 else
2413 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002414 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002415
2416 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2417 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002418 IRB.CreateAlignedStore(
2419 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002420
2421 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002422 }
2423}
2424
Vitaly Buka793913c2016-08-29 18:17:21 +00002425void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2426 ArrayRef<uint8_t> ShadowBytes,
2427 IRBuilder<> &IRB, Value *ShadowBase) {
2428 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2429}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002430
Vitaly Buka793913c2016-08-29 18:17:21 +00002431void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2432 ArrayRef<uint8_t> ShadowBytes,
2433 size_t Begin, size_t End,
2434 IRBuilder<> &IRB, Value *ShadowBase) {
2435 assert(ShadowMask.size() == ShadowBytes.size());
2436 size_t Done = Begin;
2437 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2438 if (!ShadowMask[i]) {
2439 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002440 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002441 }
2442 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002443 if (!AsanSetShadowFunc[Val])
2444 continue;
2445
2446 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002447 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002448 }
2449
2450 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002451 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002452 IRB.CreateCall(AsanSetShadowFunc[Val],
2453 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2454 ConstantInt::get(IntptrTy, j - i)});
2455 Done = j;
2456 }
2457 }
2458
Vitaly Buka793913c2016-08-29 18:17:21 +00002459 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002460}
2461
Kostya Serebryany6805de52013-09-10 13:16:56 +00002462// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2463// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2464static int StackMallocSizeClass(uint64_t LocalStackSize) {
2465 assert(LocalStackSize <= kMaxStackMallocSize);
2466 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002467 for (int i = 0;; i++, MaxSize *= 2)
2468 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002469 llvm_unreachable("impossible LocalStackSize");
2470}
2471
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002472PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2473 Value *ValueIfTrue,
2474 Instruction *ThenTerm,
2475 Value *ValueIfFalse) {
2476 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2477 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2478 PHI->addIncoming(ValueIfFalse, CondBlock);
2479 BasicBlock *ThenBlock = ThenTerm->getParent();
2480 PHI->addIncoming(ValueIfTrue, ThenBlock);
2481 return PHI;
2482}
2483
2484Value *FunctionStackPoisoner::createAllocaForLayout(
2485 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2486 AllocaInst *Alloca;
2487 if (Dynamic) {
2488 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2489 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2490 "MyAlloca");
2491 } else {
2492 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2493 nullptr, "MyAlloca");
2494 assert(Alloca->isStaticAlloca());
2495 }
2496 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2497 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2498 Alloca->setAlignment(FrameAlignment);
2499 return IRB.CreatePointerCast(Alloca, IntptrTy);
2500}
2501
Yury Gribov98b18592015-05-28 07:51:49 +00002502void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2503 BasicBlock &FirstBB = *F.begin();
2504 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2505 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2506 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2507 DynamicAllocaLayout->setAlignment(32);
2508}
2509
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002510void FunctionStackPoisoner::processDynamicAllocas() {
2511 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2512 assert(DynamicAllocaPoisonCallVec.empty());
2513 return;
2514 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002515
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002516 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2517 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002518 assert(APC.InsBefore);
2519 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002520 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002521 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002522
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002523 IRBuilder<> IRB(APC.InsBefore);
2524 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002525 // Dynamic allocas will be unpoisoned unconditionally below in
2526 // unpoisonDynamicAllocas.
2527 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002528 }
2529
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002530 // Handle dynamic allocas.
2531 createDynamicAllocasInitStorage();
2532 for (auto &AI : DynamicAllocaVec)
2533 handleDynamicAllocaCall(AI);
2534 unpoisonDynamicAllocas();
2535}
Yury Gribov98b18592015-05-28 07:51:49 +00002536
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002537void FunctionStackPoisoner::processStaticAllocas() {
2538 if (AllocaVec.empty()) {
2539 assert(StaticAllocaPoisonCallVec.empty());
2540 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002541 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002542
Kostya Serebryany6805de52013-09-10 13:16:56 +00002543 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002544 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002545 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002546 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002547
2548 Instruction *InsBefore = AllocaVec[0];
2549 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002550 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002551
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002552 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2553 // debug info is broken, because only entry-block allocas are treated as
2554 // regular stack slots.
2555 auto InsBeforeB = InsBefore->getParent();
2556 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002557 for (auto *AI : StaticAllocasToMoveUp)
2558 if (AI->getParent() == InsBeforeB)
2559 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002560
Reid Kleckner2f907552015-07-21 17:40:14 +00002561 // If we have a call to llvm.localescape, keep it in the entry block.
2562 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2563
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002564 SmallVector<ASanStackVariableDescription, 16> SVD;
2565 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002566 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002567 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002568 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002569 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002570 AI->getAlignment(),
2571 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002572 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002573 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002574 SVD.push_back(D);
2575 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002576
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002577 // Minimal header size (left redzone) is 4 pointers,
2578 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2579 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002580 const ASanStackFrameLayout &L =
2581 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002582
Vitaly Buka5910a922016-10-18 23:29:52 +00002583 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2584 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2585 for (auto &Desc : SVD)
2586 AllocaToSVDMap[Desc.AI] = &Desc;
2587
2588 // Update SVD with information from lifetime intrinsics.
2589 for (const auto &APC : StaticAllocaPoisonCallVec) {
2590 assert(APC.InsBefore);
2591 assert(APC.AI);
2592 assert(ASan.isInterestingAlloca(*APC.AI));
2593 assert(APC.AI->isStaticAlloca());
2594
2595 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2596 Desc.LifetimeSize = Desc.Size;
2597 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2598 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2599 if (LifetimeLoc->getFile() == FnLoc->getFile())
2600 if (unsigned Line = LifetimeLoc->getLine())
2601 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2602 }
2603 }
2604 }
2605
2606 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2607 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002608 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002609 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2610 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002611 bool DoDynamicAlloca = ClDynamicAllocaStack;
2612 // Don't do dynamic alloca or stack malloc if:
2613 // 1) There is inline asm: too often it makes assumptions on which registers
2614 // are available.
2615 // 2) There is a returns_twice call (typically setjmp), which is
2616 // optimization-hostile, and doesn't play well with introduced indirect
2617 // register-relative calculation of local variable addresses.
2618 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2619 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002620
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002621 Value *StaticAlloca =
2622 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2623
2624 Value *FakeStack;
2625 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002626
2627 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002628 // void *FakeStack = __asan_option_detect_stack_use_after_return
2629 // ? __asan_stack_malloc_N(LocalStackSize)
2630 // : nullptr;
2631 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002632 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2633 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2634 Value *UseAfterReturnIsEnabled =
2635 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002636 Constant::getNullValue(IRB.getInt32Ty()));
2637 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002638 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002639 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002640 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002641 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2642 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2643 Value *FakeStackValue =
2644 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2645 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002646 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002647 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002648 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002649 ConstantInt::get(IntptrTy, 0));
2650
2651 Value *NoFakeStack =
2652 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2653 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2654 IRBIf.SetInsertPoint(Term);
2655 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2656 Value *AllocaValue =
2657 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2658 IRB.SetInsertPoint(InsBefore);
2659 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2660 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2661 } else {
2662 // void *FakeStack = nullptr;
2663 // void *LocalStackBase = alloca(LocalStackSize);
2664 FakeStack = ConstantInt::get(IntptrTy, 0);
2665 LocalStackBase =
2666 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002667 }
2668
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002669 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002670 for (const auto &Desc : SVD) {
2671 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002672 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002673 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002674 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002675 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002676 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002677 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002678
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002679 // The left-most redzone has enough space for at least 4 pointers.
2680 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002681 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2682 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2683 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002684 // Write the frame description constant to redzone[1].
2685 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002686 IRB.CreateAdd(LocalStackBase,
2687 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2688 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002689 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002690 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002691 /*AllowMerging*/ true);
2692 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002693 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002694 // Write the PC to redzone[2].
2695 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002696 IRB.CreateAdd(LocalStackBase,
2697 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2698 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002699 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002700
Vitaly Buka793913c2016-08-29 18:17:21 +00002701 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2702
2703 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002704 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002705 // As mask we must use most poisoned case: red zones and after scope.
2706 // As bytes we can use either the same or just red zones only.
2707 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2708
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002709 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002710 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2711
2712 // Poison static allocas near lifetime intrinsics.
2713 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002714 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002715 assert(Desc.Offset % L.Granularity == 0);
2716 size_t Begin = Desc.Offset / L.Granularity;
2717 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2718
2719 IRBuilder<> IRB(APC.InsBefore);
2720 copyToShadow(ShadowAfterScope,
2721 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2722 IRB, ShadowBase);
2723 }
2724 }
2725
2726 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002727 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002728
Kostya Serebryany530e2072013-12-23 14:15:08 +00002729 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002730 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002731 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002732 // Mark the current frame as retired.
2733 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2734 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002735 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002736 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002737 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002738 // // In use-after-return mode, poison the whole stack frame.
2739 // if StackMallocIdx <= 4
2740 // // For small sizes inline the whole thing:
2741 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002742 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002743 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002744 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002745 // else
2746 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002747 Value *Cmp =
2748 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002749 TerminatorInst *ThenTerm, *ElseTerm;
2750 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2751
2752 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002753 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002754 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002755 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2756 kAsanStackUseAfterReturnMagic);
2757 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2758 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002759 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002760 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002761 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2762 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2763 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2764 IRBPoison.CreateStore(
2765 Constant::getNullValue(IRBPoison.getInt8Ty()),
2766 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2767 } else {
2768 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002769 IRBPoison.CreateCall(
2770 AsanStackFreeFunc[StackMallocIdx],
2771 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002772 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002773
2774 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002775 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002776 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002777 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002778 }
2779 }
2780
Kostya Serebryany09959942012-10-19 06:20:53 +00002781 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002782 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002783}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002784
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002785void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002786 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002787 // For now just insert the call to ASan runtime.
2788 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2789 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002790 IRB.CreateCall(
2791 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2792 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002793}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002794
2795// Handling llvm.lifetime intrinsics for a given %alloca:
2796// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2797// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2798// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2799// could be poisoned by previous llvm.lifetime.end instruction, as the
2800// variable may go in and out of scope several times, e.g. in loops).
2801// (3) if we poisoned at least one %alloca in a function,
2802// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002803
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002804AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2805 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002806 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002807 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002808 // See if we've already calculated (or started to calculate) alloca for a
2809 // given value.
2810 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002811 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002812 // Store 0 while we're calculating alloca for value V to avoid
2813 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002814 AllocaForValue[V] = nullptr;
2815 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002816 if (CastInst *CI = dyn_cast<CastInst>(V))
2817 Res = findAllocaForValue(CI->getOperand(0));
2818 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002819 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002820 // Allow self-referencing phi-nodes.
2821 if (IncValue == PN) continue;
2822 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2823 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002824 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2825 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002826 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002827 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002828 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2829 Res = findAllocaForValue(EP->getPointerOperand());
2830 } else {
2831 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002832 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002833 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002834 return Res;
2835}
Yury Gribov55441bb2014-11-21 10:29:50 +00002836
Yury Gribov98b18592015-05-28 07:51:49 +00002837void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002838 IRBuilder<> IRB(AI);
2839
Yury Gribov55441bb2014-11-21 10:29:50 +00002840 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2841 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2842
2843 Value *Zero = Constant::getNullValue(IntptrTy);
2844 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2845 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002846
2847 // Since we need to extend alloca with additional memory to locate
2848 // redzones, and OldSize is number of allocated blocks with
2849 // ElementSize size, get allocated memory size in bytes by
2850 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002851 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002852 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002853 Value *OldSize =
2854 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2855 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002856
2857 // PartialSize = OldSize % 32
2858 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2859
2860 // Misalign = kAllocaRzSize - PartialSize;
2861 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2862
2863 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2864 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2865 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2866
2867 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2868 // Align is added to locate left redzone, PartialPadding for possible
2869 // partial redzone and kAllocaRzSize for right redzone respectively.
2870 Value *AdditionalChunkSize = IRB.CreateAdd(
2871 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2872
2873 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2874
2875 // Insert new alloca with new NewSize and Align params.
2876 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2877 NewAlloca->setAlignment(Align);
2878
2879 // NewAddress = Address + Align
2880 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2881 ConstantInt::get(IntptrTy, Align));
2882
Yury Gribov98b18592015-05-28 07:51:49 +00002883 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002884 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002885
2886 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2887 // for unpoisoning stuff.
2888 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2889
Yury Gribov55441bb2014-11-21 10:29:50 +00002890 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2891
Yury Gribov98b18592015-05-28 07:51:49 +00002892 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002893 AI->replaceAllUsesWith(NewAddressPtr);
2894
Yury Gribov98b18592015-05-28 07:51:49 +00002895 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002896 AI->eraseFromParent();
2897}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002898
2899// isSafeAccess returns true if Addr is always inbounds with respect to its
2900// base object. For example, it is a field access or an array access with
2901// constant inbounds index.
2902bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2903 Value *Addr, uint64_t TypeSize) const {
2904 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2905 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002906 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002907 int64_t Offset = SizeOffset.second.getSExtValue();
2908 // Three checks are required to ensure safety:
2909 // . Offset >= 0 (since the offset is given from the base ptr)
2910 // . Size >= Offset (unsigned)
2911 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002912 return Offset >= 0 && Size >= uint64_t(Offset) &&
2913 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002914}