blob: d718046adf7415e0d63b14bc42aff8db9b1f2142 [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 Stepanov964f4662017-04-27 20:27:27 +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 Stepanov964f4662017-04-27 20:27:27 +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 Stepanov964f4662017-04-27 20:27:27 +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>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000275 ClUseGlobalsGC("asan-globals-live-support",
276 cl::desc("Use linker features to support dead "
277 "code stripping of globals"),
278 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000279
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000280// This is on by default even though there is a bug in gold:
281// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
282static cl::opt<bool>
283 ClWithComdat("asan-with-comdat",
284 cl::desc("Place ASan constructors in comdat sections"),
285 cl::Hidden, cl::init(true));
286
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000287// Debug flags.
288static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
289 cl::init(0));
290static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
291 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000292static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
293 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000294static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
295 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000296static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000297 cl::Hidden, cl::init(-1));
298
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000299STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
300STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000301STATISTIC(NumOptimizedAccessesToGlobalVar,
302 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000303STATISTIC(NumOptimizedAccessesToStackVar,
304 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000305
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000306namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000307/// Frontend-provided metadata for source location.
308struct LocationMetadata {
309 StringRef Filename;
310 int LineNo;
311 int ColumnNo;
312
313 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
314
315 bool empty() const { return Filename.empty(); }
316
317 void parse(MDNode *MDN) {
318 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000319 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
320 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000321 LineNo =
322 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
323 ColumnNo =
324 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000325 }
326};
327
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000328/// Frontend-provided metadata for global variables.
329class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000330 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000331 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000332 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000333 LocationMetadata SourceLoc;
334 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000335 bool IsDynInit;
336 bool IsBlacklisted;
337 };
338
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000339 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000340
Keno Fischere03fae42015-12-05 14:42:34 +0000341 void reset() {
342 inited_ = false;
343 Entries.clear();
344 }
345
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000346 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000347 assert(!inited_);
348 inited_ = true;
349 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000350 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000351 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000352 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000353 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000354 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000355 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000356 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000357 // We can already have an entry for GV if it was merged with another
358 // global.
359 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000360 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
361 E.SourceLoc.parse(Loc);
362 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
363 E.Name = Name->getString();
364 ConstantInt *IsDynInit =
365 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000366 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000367 ConstantInt *IsBlacklisted =
368 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000369 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000370 }
371 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000372
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000373 /// Returns metadata entry for a given global.
374 Entry get(GlobalVariable *G) const {
375 auto Pos = Entries.find(G);
376 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000377 }
378
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000379 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000380 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000381 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000382};
383
Alexey Samsonov1345d352013-01-16 13:23:28 +0000384/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000385/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000386struct ShadowMapping {
387 int Scale;
388 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000389 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000390};
391
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000392static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
393 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000394 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000395 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000396 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000397 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000398 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000399 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
400 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000401 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000402 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000403 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000404 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
405 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000406 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
407 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000408 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000409 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000410 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000411
412 ShadowMapping Mapping;
413
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000414 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000415 // Android is always PIE, which means that the beginning of the address
416 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000417 if (IsAndroid)
418 Mapping.Offset = 0;
419 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000420 Mapping.Offset = kMIPS32_ShadowOffset32;
421 else if (IsFreeBSD)
422 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000423 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000424 // If we're targeting iOS and x86, the binary is built for iOS simulator.
425 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000426 else if (IsWindows)
427 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000428 else
429 Mapping.Offset = kDefaultShadowOffset32;
430 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000431 // Fuchsia is always PIE, which means that the beginning of the address
432 // space is always available.
433 if (IsFuchsia)
434 Mapping.Offset = 0;
435 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000436 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000437 else if (IsSystemZ)
438 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000439 else if (IsFreeBSD)
440 Mapping.Offset = kFreeBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000441 else if (IsPS4CPU)
442 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000443 else if (IsLinux && IsX86_64) {
444 if (IsKasan)
445 Mapping.Offset = kLinuxKasan_ShadowOffset64;
446 else
447 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000448 } else if (IsWindows && IsX86_64) {
449 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000450 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000451 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000452 else if (IsIOS)
453 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000454 // We are using dynamic shadow offset on the 64-bit devices.
455 Mapping.Offset =
456 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000457 else if (IsAArch64)
458 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000459 else
460 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000461 }
462
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000463 if (ClForceDynamicShadow) {
464 Mapping.Offset = kDynamicShadowSentinel;
465 }
466
Alexey Samsonov1345d352013-01-16 13:23:28 +0000467 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000468 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000469 Mapping.Scale = ClMappingScale;
470 }
471
Ryan Govostes3f37df02016-05-06 10:25:22 +0000472 if (ClMappingOffset.getNumOccurrences() > 0) {
473 Mapping.Offset = ClMappingOffset;
474 }
475
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000476 // OR-ing shadow offset if more efficient (at least on x86) if the offset
477 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000478 // offset is not necessary 1/8-th of the address space. On SystemZ,
479 // we could OR the constant in a single instruction, but it's more
480 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000481 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
482 !(Mapping.Offset & (Mapping.Offset - 1)) &&
483 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000484
Alexey Samsonov1345d352013-01-16 13:23:28 +0000485 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000486}
487
Alexey Samsonov1345d352013-01-16 13:23:28 +0000488static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000489 // Redzone used for stack and globals is at least 32 bytes.
490 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000491 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000492}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000493
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000494/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000495struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000496 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
497 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000498 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000499 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000500 UseAfterScope(UseAfterScope || ClUseAfterScope),
501 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000502 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
503 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000504 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000505 return "AddressSanitizerFunctionPass";
506 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000507 void getAnalysisUsage(AnalysisUsage &AU) const override {
508 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000509 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000510 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000511 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000512 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000513 if (AI.isArrayAllocation()) {
514 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000515 assert(CI && "non-constant array size");
516 ArraySize = CI->getZExtValue();
517 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000518 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000519 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000520 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000521 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000522 }
523 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000524 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000525
Anna Zaks8ed1d812015-02-27 03:12:36 +0000526 /// If it is an interesting memory access, return the PointerOperand
527 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000528 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
529 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000530 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000531 uint64_t *TypeSize, unsigned *Alignment,
532 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000533 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000534 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000535 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000536 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
537 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000538 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000539 void instrumentUnusualSizeOrAlignment(Instruction *I,
540 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000541 uint32_t TypeSize, bool IsWrite,
542 Value *SizeArgument, bool UseCalls,
543 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000544 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
545 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000546 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000547 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000548 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000549 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000550 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000551 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000552 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000553 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000554 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000555 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000556 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000557 static char ID; // Pass identification, replacement for typeid
558
Yury Gribov3ae427d2014-12-01 08:47:58 +0000559 DominatorTree &getDominatorTree() const { return *DT; }
560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000561 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000562 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000563
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000564 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000565 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000566 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
567 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000568
Reid Kleckner2f907552015-07-21 17:40:14 +0000569 /// Helper to cleanup per-function state.
570 struct FunctionStateRAII {
571 AddressSanitizer *Pass;
572 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
573 assert(Pass->ProcessedAllocas.empty() &&
574 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000575 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000576 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000577 ~FunctionStateRAII() {
578 Pass->LocalDynamicShadow = nullptr;
579 Pass->ProcessedAllocas.clear();
580 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000581 };
582
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000583 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000584 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000585 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000586 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000587 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000588 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000589 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000590 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000591 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000592 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000593 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000594 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
595 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
596 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
597 // This array is indexed by AccessIsWrite and Experiment.
598 Function *AsanErrorCallbackSized[2][2];
599 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000600 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000601 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000602 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000603 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000604 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000605
606 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000607};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000608
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000609class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000610public:
Yury Gribovd7731982015-11-11 10:36:49 +0000611 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000612 bool Recover = false,
613 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000614 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000615 Recover(Recover || ClRecover),
616 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000617 bool runOnModule(Module &M) override;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000618 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000619 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000620
Mehdi Amini117296c2016-10-01 02:56:57 +0000621private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000622 void initializeCallbacks(Module &M);
623
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000624 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000625 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
626 ArrayRef<GlobalVariable *> ExtendedGlobals,
627 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000628 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
629 ArrayRef<GlobalVariable *> ExtendedGlobals,
630 ArrayRef<Constant *> MetadataInitializers,
631 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000632 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
633 ArrayRef<GlobalVariable *> ExtendedGlobals,
634 ArrayRef<Constant *> MetadataInitializers);
635 void
636 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
637 ArrayRef<GlobalVariable *> ExtendedGlobals,
638 ArrayRef<Constant *> MetadataInitializers);
639
640 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
641 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000642 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
643 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000644 IRBuilder<> CreateAsanModuleDtor(Module &M);
645
Kostya Serebryany20a79972012-11-22 03:18:50 +0000646 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000647 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000648 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000649 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000650 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000651 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000652 return RedzoneSizeForScale(Mapping.Scale);
653 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000654
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000655 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000656 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000657 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000658 bool UseGlobalsGC;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000659 Type *IntptrTy;
660 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000661 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000662 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000663 Function *AsanPoisonGlobals;
664 Function *AsanUnpoisonGlobals;
665 Function *AsanRegisterGlobals;
666 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000667 Function *AsanRegisterImageGlobals;
668 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000669 Function *AsanRegisterElfGlobals;
670 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000671
672 Function *AsanCtorFunction = nullptr;
673 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000674};
675
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000676// Stack poisoning does not play well with exception handling.
677// When an exception is thrown, we essentially bypass the code
678// that unpoisones the stack. This is why the run-time library has
679// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
680// stack in the interceptor. This however does not work inside the
681// actual function which catches the exception. Most likely because the
682// compiler hoists the load of the shadow value somewhere too high.
683// This causes asan to report a non-existing bug on 453.povray.
684// It sounds like an LLVM bug.
685struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
686 Function &F;
687 AddressSanitizer &ASan;
688 DIBuilder DIB;
689 LLVMContext *C;
690 Type *IntptrTy;
691 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000692 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000693
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000694 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000695 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000696 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000697 unsigned StackAlignment;
698
Kostya Serebryany6805de52013-09-10 13:16:56 +0000699 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000700 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000701 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000702 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000703 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000704
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000705 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
706 struct AllocaPoisonCall {
707 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000708 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000709 uint64_t Size;
710 bool DoPoison;
711 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000712 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
713 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000714
Yury Gribov98b18592015-05-28 07:51:49 +0000715 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
716 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
717 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000718 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000719
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000720 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000721 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000722 AllocaForValueMapTy AllocaForValue;
723
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000724 bool HasNonEmptyInlineAsm = false;
725 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000726 std::unique_ptr<CallInst> EmptyInlineAsm;
727
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000728 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000729 : F(F),
730 ASan(ASan),
731 DIB(*F.getParent(), /*AllowUnresolved*/ false),
732 C(ASan.C),
733 IntptrTy(ASan.IntptrTy),
734 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
735 Mapping(ASan.Mapping),
736 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000737 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000738
739 bool runOnFunction() {
740 if (!ClStack) return false;
741 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000742 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000743
Yury Gribov55441bb2014-11-21 10:29:50 +0000744 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000745
746 initializeCallbacks(*F.getParent());
747
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000748 processDynamicAllocas();
749 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000750
751 if (ClDebugStack) {
752 DEBUG(dbgs() << F);
753 }
754 return true;
755 }
756
Yury Gribov55441bb2014-11-21 10:29:50 +0000757 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000758 // poisoned red zones around all of them.
759 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000760 void processStaticAllocas();
761 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000762
Yury Gribov98b18592015-05-28 07:51:49 +0000763 void createDynamicAllocasInitStorage();
764
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000765 // ----------------------- Visitors.
766 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000767 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000768
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000769 /// \brief Collect all Resume instructions.
770 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
771
772 /// \brief Collect all CatchReturnInst instructions.
773 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
774
Yury Gribov98b18592015-05-28 07:51:49 +0000775 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
776 Value *SavedStack) {
777 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000778 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
779 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
780 // need to adjust extracted SP to compute the address of the most recent
781 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
782 // this purpose.
783 if (!isa<ReturnInst>(InstBefore)) {
784 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
785 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
786 {IntptrTy});
787
788 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
789
790 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
791 DynamicAreaOffset);
792 }
793
Yury Gribov781bce22015-05-28 08:03:28 +0000794 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000795 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000796 }
797
Yury Gribov55441bb2014-11-21 10:29:50 +0000798 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000799 void unpoisonDynamicAllocas() {
800 for (auto &Ret : RetVec)
801 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000802
Yury Gribov98b18592015-05-28 07:51:49 +0000803 for (auto &StackRestoreInst : StackRestoreVec)
804 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
805 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000806 }
807
Yury Gribov55441bb2014-11-21 10:29:50 +0000808 // Deploy and poison redzones around dynamic alloca call. To do this, we
809 // should replace this call with another one with changed parameters and
810 // replace all its uses with new address, so
811 // addr = alloca type, old_size, align
812 // is replaced by
813 // new_size = (old_size + additional_size) * sizeof(type)
814 // tmp = alloca i8, new_size, max(align, 32)
815 // addr = tmp + 32 (first 32 bytes are for the left redzone).
816 // Additional_size is added to make new memory allocation contain not only
817 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000818 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000819
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000820 /// \brief Collect Alloca instructions we want (and can) handle.
821 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000822 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000823 if (AI.isStaticAlloca()) {
824 // Skip over allocas that are present *before* the first instrumented
825 // alloca, we don't want to move those around.
826 if (AllocaVec.empty())
827 return;
828
829 StaticAllocasToMoveUp.push_back(&AI);
830 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000831 return;
832 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000833
834 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000835 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000836 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000837 else
838 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000839 }
840
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000841 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
842 /// errors.
843 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000844 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000845 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000846 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000847 if (!ASan.UseAfterScope)
848 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000849 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000850 return;
851 // Found lifetime intrinsic, add ASan instrumentation if necessary.
852 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
853 // If size argument is undefined, don't do anything.
854 if (Size->isMinusOne()) return;
855 // Check that size doesn't saturate uint64_t and can
856 // be stored in IntptrTy.
857 const uint64_t SizeValue = Size->getValue().getLimitedValue();
858 if (SizeValue == ~0ULL ||
859 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
860 return;
861 // Find alloca instruction that corresponds to llvm.lifetime argument.
862 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000863 if (!AI || !ASan.isInterestingAlloca(*AI))
864 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000865 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000866 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000867 if (AI->isStaticAlloca())
868 StaticAllocaPoisonCallVec.push_back(APC);
869 else if (ClInstrumentDynamicAllocas)
870 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000871 }
872
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000873 void visitCallSite(CallSite CS) {
874 Instruction *I = CS.getInstruction();
875 if (CallInst *CI = dyn_cast<CallInst>(I)) {
876 HasNonEmptyInlineAsm |=
877 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
878 HasReturnsTwiceCall |= CI->canReturnTwice();
879 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000880 }
881
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000882 // ---------------------- Helpers.
883 void initializeCallbacks(Module &M);
884
Yury Gribov3ae427d2014-12-01 08:47:58 +0000885 bool doesDominateAllExits(const Instruction *I) const {
886 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000887 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000888 }
889 return true;
890 }
891
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000892 /// Finds alloca where the value comes from.
893 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000894
895 // Copies bytes from ShadowBytes into shadow memory for indexes where
896 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
897 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
898 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
899 IRBuilder<> &IRB, Value *ShadowBase);
900 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
901 size_t Begin, size_t End, IRBuilder<> &IRB,
902 Value *ShadowBase);
903 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
904 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
905 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
906
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000907 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000908
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000909 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
910 bool Dynamic);
911 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
912 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000913};
914
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000915} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000916
917char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000918INITIALIZE_PASS_BEGIN(
919 AddressSanitizer, "asan",
920 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
921 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000922INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000923INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000924INITIALIZE_PASS_END(
925 AddressSanitizer, "asan",
926 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
927 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000928FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000929 bool Recover,
930 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000931 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000932 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000933}
934
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000935char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000936INITIALIZE_PASS(
937 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000938 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000939 "ModulePass",
940 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000941ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000942 bool Recover,
943 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +0000944 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000945 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000946}
947
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000948static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000949 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000950 assert(Res < kNumberOfAccessSizes);
951 return Res;
952}
953
Bill Wendling58f8cef2013-08-06 22:52:42 +0000954// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000955static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
956 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000957 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000958 // We use private linkage for module-local strings. If they can be merged
959 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000960 GlobalVariable *GV =
961 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000962 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000963 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000964 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
965 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000966}
967
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000968/// \brief Create a global describing a source location.
969static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
970 LocationMetadata MD) {
971 Constant *LocData[] = {
972 createPrivateGlobalForString(M, MD.Filename, true),
973 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
974 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
975 };
976 auto LocStruct = ConstantStruct::getAnon(LocData);
977 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
978 GlobalValue::PrivateLinkage, LocStruct,
979 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000980 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000981 return GV;
982}
983
Vedant Kumarf5ac6d42016-06-22 17:30:58 +0000984/// \brief Check if \p G has been created by a trusted compiler pass.
985static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
986 // Do not instrument asan globals.
987 if (G->getName().startswith(kAsanGenPrefix) ||
988 G->getName().startswith(kSanCovGenPrefix) ||
989 G->getName().startswith(kODRGenPrefix))
990 return true;
991
992 // Do not instrument gcov counter arrays.
993 if (G->getName() == "__llvm_gcov_ctr")
994 return true;
995
996 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000997}
998
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000999Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1000 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001001 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001002 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001003 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001004 Value *ShadowBase;
1005 if (LocalDynamicShadow)
1006 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001007 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001008 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1009 if (Mapping.OrShadowOffset)
1010 return IRB.CreateOr(Shadow, ShadowBase);
1011 else
1012 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001013}
1014
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001015// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001016void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1017 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001018 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001019 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001020 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001021 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1022 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1023 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001024 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001025 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001026 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001027 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1028 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1029 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001030 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001031 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001032}
1033
Anna Zaks8ed1d812015-02-27 03:12:36 +00001034/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001035bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001036 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1037
1038 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1039 return PreviouslySeenAllocaInfo->getSecond();
1040
Yury Gribov98b18592015-05-28 07:51:49 +00001041 bool IsInteresting =
1042 (AI.getAllocatedType()->isSized() &&
1043 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001044 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001045 // We are only interested in allocas not promotable to registers.
1046 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001047 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1048 // inalloca allocas are not treated as static, and we don't want
1049 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001050 !AI.isUsedWithInAlloca() &&
1051 // swifterror allocas are register promoted by ISel
1052 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001053
1054 ProcessedAllocas[&AI] = IsInteresting;
1055 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001056}
1057
Anna Zaks8ed1d812015-02-27 03:12:36 +00001058Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1059 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001060 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001061 unsigned *Alignment,
1062 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001063 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001064 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001065
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001066 // Do not instrument the load fetching the dynamic shadow address.
1067 if (LocalDynamicShadow == I)
1068 return nullptr;
1069
Anna Zaks8ed1d812015-02-27 03:12:36 +00001070 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001071 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001072 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001073 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001074 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001075 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001076 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001077 PtrOperand = LI->getPointerOperand();
1078 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001079 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001080 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001081 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001082 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001083 PtrOperand = SI->getPointerOperand();
1084 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001085 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001086 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001087 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001088 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001089 PtrOperand = RMW->getPointerOperand();
1090 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001091 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001092 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001093 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001094 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001095 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001096 } else if (auto CI = dyn_cast<CallInst>(I)) {
1097 auto *F = dyn_cast<Function>(CI->getCalledValue());
1098 if (F && (F->getName().startswith("llvm.masked.load.") ||
1099 F->getName().startswith("llvm.masked.store."))) {
1100 unsigned OpOffset = 0;
1101 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001102 if (!ClInstrumentWrites)
1103 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001104 // Masked store has an initial operand for the value.
1105 OpOffset = 1;
1106 *IsWrite = true;
1107 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001108 if (!ClInstrumentReads)
1109 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001110 *IsWrite = false;
1111 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001112
1113 auto BasePtr = CI->getOperand(0 + OpOffset);
1114 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1115 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1116 if (auto AlignmentConstant =
1117 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1118 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1119 else
1120 *Alignment = 1; // No alignment guarantees. We probably got Undef
1121 if (MaybeMask)
1122 *MaybeMask = CI->getOperand(2 + OpOffset);
1123 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001124 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001125 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001126
Anna Zaks644d9d32016-06-22 00:15:52 +00001127 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001128 // Do not instrument acesses from different address spaces; we cannot deal
1129 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001130 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1131 if (PtrTy->getPointerAddressSpace() != 0)
1132 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001133
1134 // Ignore swifterror addresses.
1135 // swifterror memory addresses are mem2reg promoted by instruction
1136 // selection. As such they cannot have regular uses like an instrumentation
1137 // function and it makes no sense to track them as memory.
1138 if (PtrOperand->isSwiftError())
1139 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001140 }
1141
Anna Zaks8ed1d812015-02-27 03:12:36 +00001142 // Treat memory accesses to promotable allocas as non-interesting since they
1143 // will not cause memory violations. This greatly speeds up the instrumented
1144 // executable at -O0.
1145 if (ClSkipPromotableAllocas)
1146 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1147 return isInterestingAlloca(*AI) ? AI : nullptr;
1148
1149 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001150}
1151
Kostya Serebryany796f6552014-02-27 12:45:36 +00001152static bool isPointerOperand(Value *V) {
1153 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1154}
1155
1156// This is a rough heuristic; it may cause both false positives and
1157// false negatives. The proper implementation requires cooperation with
1158// the frontend.
1159static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1160 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001161 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001162 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001163 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001164 } else {
1165 return false;
1166 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001167 return isPointerOperand(I->getOperand(0)) &&
1168 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001169}
1170
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001171bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1172 // If a global variable does not have dynamic initialization we don't
1173 // have to instrument it. However, if a global does not have initializer
1174 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001175 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001176}
1177
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001178void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1179 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001180 IRBuilder<> IRB(I);
1181 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1182 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001183 for (Value *&i : Param) {
1184 if (i->getType()->isPointerTy())
1185 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001186 }
David Blaikieff6409d2015-05-18 22:13:54 +00001187 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001188}
1189
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001190static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001191 Instruction *InsertBefore, Value *Addr,
1192 unsigned Alignment, unsigned Granularity,
1193 uint32_t TypeSize, bool IsWrite,
1194 Value *SizeArgument, bool UseCalls,
1195 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001196 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1197 // if the data is properly aligned.
1198 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1199 TypeSize == 128) &&
1200 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001201 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1202 nullptr, UseCalls, Exp);
1203 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1204 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001205}
1206
1207static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1208 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001209 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001210 Value *Addr, unsigned Alignment,
1211 unsigned Granularity, uint32_t TypeSize,
1212 bool IsWrite, Value *SizeArgument,
1213 bool UseCalls, uint32_t Exp) {
1214 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1215 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1216 unsigned Num = VTy->getVectorNumElements();
1217 auto Zero = ConstantInt::get(IntptrTy, 0);
1218 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001219 Value *InstrumentedAddress = nullptr;
1220 Instruction *InsertBefore = I;
1221 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1222 // dyn_cast as we might get UndefValue
1223 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1224 if (Masked->isNullValue())
1225 // Mask is constant false, so no instrumentation needed.
1226 continue;
1227 // If we have a true or undef value, fall through to doInstrumentAddress
1228 // with InsertBefore == I
1229 }
1230 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001231 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001232 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1233 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1234 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001235 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001236
1237 IRBuilder<> IRB(InsertBefore);
1238 InstrumentedAddress =
1239 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1240 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1241 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1242 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001243 }
1244}
1245
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001246void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001247 Instruction *I, bool UseCalls,
1248 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001249 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001250 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001251 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001252 Value *MaybeMask = nullptr;
1253 Value *Addr =
1254 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001255 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001256
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001257 // Optimization experiments.
1258 // The experiments can be used to evaluate potential optimizations that remove
1259 // instrumentation (assess false negatives). Instead of completely removing
1260 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1261 // experiments that want to remove instrumentation of this instruction).
1262 // If Exp is non-zero, this pass will emit special calls into runtime
1263 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1264 // make runtime terminate the program in a special way (with a different
1265 // exit status). Then you run the new compiler on a buggy corpus, collect
1266 // the special terminations (ideally, you don't see them at all -- no false
1267 // negatives) and make the decision on the optimization.
1268 uint32_t Exp = ClForceExperiment;
1269
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001270 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001271 // If initialization order checking is disabled, a simple access to a
1272 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001274 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001275 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1276 NumOptimizedAccessesToGlobalVar++;
1277 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001278 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001279 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001280
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001281 if (ClOpt && ClOptStack) {
1282 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001283 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001284 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1285 NumOptimizedAccessesToStackVar++;
1286 return;
1287 }
1288 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001289
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001290 if (IsWrite)
1291 NumInstrumentedWrites++;
1292 else
1293 NumInstrumentedReads++;
1294
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001295 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001296 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001297 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1298 Alignment, Granularity, TypeSize, IsWrite,
1299 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001300 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001301 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001302 IsWrite, nullptr, UseCalls, Exp);
1303 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001304}
1305
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001306Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1307 Value *Addr, bool IsWrite,
1308 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001309 Value *SizeArgument,
1310 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001311 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001312 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1313 CallInst *Call = nullptr;
1314 if (SizeArgument) {
1315 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001316 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1317 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001318 else
David Blaikieff6409d2015-05-18 22:13:54 +00001319 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1320 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001321 } else {
1322 if (Exp == 0)
1323 Call =
1324 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1325 else
David Blaikieff6409d2015-05-18 22:13:54 +00001326 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1327 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001328 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001329
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001330 // We don't do Call->setDoesNotReturn() because the BB already has
1331 // UnreachableInst at the end.
1332 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001333 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001334 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001335}
1336
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001337Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001338 Value *ShadowValue,
1339 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001340 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001341 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001342 Value *LastAccessedByte =
1343 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001344 // (Addr & (Granularity - 1)) + size - 1
1345 if (TypeSize / 8 > 1)
1346 LastAccessedByte = IRB.CreateAdd(
1347 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1348 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001349 LastAccessedByte =
1350 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001351 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1352 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1353}
1354
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001355void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001356 Instruction *InsertBefore, Value *Addr,
1357 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001358 Value *SizeArgument, bool UseCalls,
1359 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001360 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001361 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001362 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1363
1364 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001365 if (Exp == 0)
1366 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1367 AddrLong);
1368 else
David Blaikieff6409d2015-05-18 22:13:54 +00001369 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1370 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001371 return;
1372 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001373
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001374 Type *ShadowTy =
1375 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001376 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1377 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1378 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001379 Value *ShadowValue =
1380 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001381
1382 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001383 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001384 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001385
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001386 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001387 // We use branch weights for the slow path check, to indicate that the slow
1388 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001389 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1390 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001391 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001392 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001393 IRB.SetInsertPoint(CheckTerm);
1394 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001395 if (Recover) {
1396 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1397 } else {
1398 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001399 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001400 CrashTerm = new UnreachableInst(*C, CrashBlock);
1401 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1402 ReplaceInstWithInst(CheckTerm, NewTerm);
1403 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001404 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001405 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001406 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001407
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001408 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001409 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001410 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001411}
1412
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001413// Instrument unusual size or unusual alignment.
1414// We can not do it with a single check, so we do 1-byte check for the first
1415// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1416// to report the actual access size.
1417void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001418 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1419 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1420 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001421 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1422 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1423 if (UseCalls) {
1424 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001425 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1426 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001427 else
David Blaikieff6409d2015-05-18 22:13:54 +00001428 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1429 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001430 } else {
1431 Value *LastByte = IRB.CreateIntToPtr(
1432 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1433 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001434 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1435 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001436 }
1437}
1438
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001439void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1440 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001441 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001442 IRBuilder<> IRB(&GlobalInit.front(),
1443 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001444
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001445 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001446 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1447 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001448
1449 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001450 for (auto &BB : GlobalInit.getBasicBlockList())
1451 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001452 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001453}
1454
1455void AddressSanitizerModule::createInitializerPoisonCalls(
1456 Module &M, GlobalValue *ModuleName) {
1457 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001458 if (!GV)
1459 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001460
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001461 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1462 if (!CA)
1463 return;
1464
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001465 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001466 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001467 ConstantStruct *CS = cast<ConstantStruct>(OP);
1468
1469 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001470 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001471 if (F->getName() == kAsanModuleCtorName) continue;
1472 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1473 // Don't instrument CTORs that will run before asan.module_ctor.
1474 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1475 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001476 }
1477 }
1478}
1479
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001480bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001481 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001482 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001483
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001484 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001485 if (!Ty->isSized()) return false;
1486 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001487 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001488 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001489 // Don't handle ODR linkage types and COMDATs since other modules may be built
1490 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001491 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1492 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1493 G->getLinkage() != GlobalVariable::InternalLinkage)
1494 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001495 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001496 // Two problems with thread-locals:
1497 // - The address of the main thread's copy can't be computed at link-time.
1498 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001499 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001500 // For now, just ignore this Global if the alignment is large.
1501 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001502
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001503 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001504 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001505
Anna Zaks11904602015-06-09 00:58:08 +00001506 // Globals from llvm.metadata aren't emitted, do not instrument them.
1507 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001508 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001509 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001510
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001511 // Do not instrument function pointers to initialization and termination
1512 // routines: dynamic linker will not properly handle redzones.
1513 if (Section.startswith(".preinit_array") ||
1514 Section.startswith(".init_array") ||
1515 Section.startswith(".fini_array")) {
1516 return false;
1517 }
1518
Anna Zaks11904602015-06-09 00:58:08 +00001519 // Callbacks put into the CRT initializer/terminator sections
1520 // should not be instrumented.
1521 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1522 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1523 if (Section.startswith(".CRT")) {
1524 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1525 return false;
1526 }
1527
Kuba Brecka1001bb52014-12-05 22:19:18 +00001528 if (TargetTriple.isOSBinFormatMachO()) {
1529 StringRef ParsedSegment, ParsedSection;
1530 unsigned TAA = 0, StubSize = 0;
1531 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001532 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1533 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001534 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001535
1536 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1537 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1538 // them.
1539 if (ParsedSegment == "__OBJC" ||
1540 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1541 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1542 return false;
1543 }
1544 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1545 // Constant CFString instances are compiled in the following way:
1546 // -- the string buffer is emitted into
1547 // __TEXT,__cstring,cstring_literals
1548 // -- the constant NSConstantString structure referencing that buffer
1549 // is placed into __DATA,__cfstring
1550 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1551 // Moreover, it causes the linker to crash on OS X 10.7
1552 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1553 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1554 return false;
1555 }
1556 // The linker merges the contents of cstring_literals and removes the
1557 // trailing zeroes.
1558 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1559 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1560 return false;
1561 }
1562 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001563 }
1564
1565 return true;
1566}
1567
Ryan Govostes653f9d02016-03-28 20:28:57 +00001568// On Mach-O platforms, we emit global metadata in a separate section of the
1569// binary in order to allow the linker to properly dead strip. This is only
1570// supported on recent versions of ld64.
1571bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1572 if (!TargetTriple.isOSBinFormatMachO())
1573 return false;
1574
1575 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1576 return true;
1577 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001578 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001579 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1580 return true;
1581
1582 return false;
1583}
1584
Reid Kleckner01660a32016-11-21 20:40:37 +00001585StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1586 switch (TargetTriple.getObjectFormat()) {
1587 case Triple::COFF: return ".ASAN$GL";
1588 case Triple::ELF: return "asan_globals";
1589 case Triple::MachO: return "__DATA,__asan_globals,regular";
1590 default: break;
1591 }
1592 llvm_unreachable("unsupported object format");
1593}
1594
Alexey Samsonov788381b2012-12-25 12:28:20 +00001595void AddressSanitizerModule::initializeCallbacks(Module &M) {
1596 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001597
Alexey Samsonov788381b2012-12-25 12:28:20 +00001598 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001599 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001600 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001601 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001602 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001603 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001604 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001605
Alexey Samsonov788381b2012-12-25 12:28:20 +00001606 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001607 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001608 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001609 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001610 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1611 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001612 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001613 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001614
1615 // Declare the functions that find globals in a shared object and then invoke
1616 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001617 AsanRegisterImageGlobals =
1618 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001619 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001620 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001621
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001622 AsanUnregisterImageGlobals =
1623 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001624 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001625 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001626
1627 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1628 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1629 IntptrTy, IntptrTy, IntptrTy));
1630 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1631
1632 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1633 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1634 IntptrTy, IntptrTy, IntptrTy));
1635 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001636}
1637
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001638// Put the metadata and the instrumented global in the same group. This ensures
1639// that the metadata is discarded if the instrumented global is discarded.
1640void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001641 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001642 Module &M = *G->getParent();
1643 Comdat *C = G->getComdat();
1644 if (!C) {
1645 if (!G->hasName()) {
1646 // If G is unnamed, it must be internal. Give it an artificial name
1647 // so we can put it in a comdat.
1648 assert(G->hasLocalLinkage());
1649 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1650 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001651
1652 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1653 std::string Name = G->getName();
1654 Name += InternalSuffix;
1655 C = M.getOrInsertComdat(Name);
1656 } else {
1657 C = M.getOrInsertComdat(G->getName());
1658 }
1659
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001660 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1661 if (TargetTriple.isOSBinFormatCOFF())
1662 C->setSelectionKind(Comdat::NoDuplicates);
1663 G->setComdat(C);
1664 }
1665
1666 assert(G->hasComdat());
1667 Metadata->setComdat(G->getComdat());
1668}
1669
1670// Create a separate metadata global and put it in the appropriate ASan
1671// global registration section.
1672GlobalVariable *
1673AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1674 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001675 auto Linkage = TargetTriple.isOSBinFormatMachO()
1676 ? GlobalVariable::InternalLinkage
1677 : GlobalVariable::PrivateLinkage;
1678 GlobalVariable *Metadata = new GlobalVariable(
1679 M, Initializer->getType(), false, Linkage, Initializer,
1680 Twine("__asan_global_") + GlobalValue::getRealLinkageName(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001681 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001682 return Metadata;
1683}
1684
1685IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001686 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001687 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1688 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1689 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001690
1691 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1692}
1693
1694void AddressSanitizerModule::InstrumentGlobalsCOFF(
1695 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1696 ArrayRef<Constant *> MetadataInitializers) {
1697 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001698 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001699
1700 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001701 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001702 GlobalVariable *G = ExtendedGlobals[i];
1703 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001704 CreateMetadataGlobal(M, Initializer, G->getName());
1705
1706 // The MSVC linker always inserts padding when linking incrementally. We
1707 // cope with that by aligning each struct to its size, which must be a power
1708 // of two.
1709 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1710 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1711 "global metadata will not be padded appropriately");
1712 Metadata->setAlignment(SizeOfGlobalStruct);
1713
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001714 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001715 }
1716}
1717
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001718void AddressSanitizerModule::InstrumentGlobalsELF(
1719 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1720 ArrayRef<Constant *> MetadataInitializers,
1721 const std::string &UniqueModuleId) {
1722 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1723
1724 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1725 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1726 GlobalVariable *G = ExtendedGlobals[i];
1727 GlobalVariable *Metadata =
1728 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1729 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1730 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1731 MetadataGlobals[i] = Metadata;
1732
1733 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1734 }
1735
1736 // Update llvm.compiler.used, adding the new metadata globals. This is
1737 // needed so that during LTO these variables stay alive.
1738 if (!MetadataGlobals.empty())
1739 appendToCompilerUsed(M, MetadataGlobals);
1740
1741 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1742 // to look up the loaded image that contains it. Second, we can store in it
1743 // whether registration has already occurred, to prevent duplicate
1744 // registration.
1745 //
1746 // Common linkage ensures that there is only one global per shared library.
1747 GlobalVariable *RegisteredFlag = new GlobalVariable(
1748 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1749 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1750 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1751
1752 // Create start and stop symbols.
1753 GlobalVariable *StartELFMetadata = new GlobalVariable(
1754 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1755 "__start_" + getGlobalMetadataSection());
1756 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1757 GlobalVariable *StopELFMetadata = new GlobalVariable(
1758 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1759 "__stop_" + getGlobalMetadataSection());
1760 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1761
1762 // Create a call to register the globals with the runtime.
1763 IRB.CreateCall(AsanRegisterElfGlobals,
1764 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1765 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1766 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1767
1768 // We also need to unregister globals at the end, e.g., when a shared library
1769 // gets closed.
1770 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1771 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1772 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1773 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1774 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1775}
1776
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001777void AddressSanitizerModule::InstrumentGlobalsMachO(
1778 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1779 ArrayRef<Constant *> MetadataInitializers) {
1780 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1781
1782 // On recent Mach-O platforms, use a structure which binds the liveness of
1783 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1784 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001785 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001786 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1787
1788 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1789 Constant *Initializer = MetadataInitializers[i];
1790 GlobalVariable *G = ExtendedGlobals[i];
1791 GlobalVariable *Metadata =
1792 CreateMetadataGlobal(M, Initializer, G->getName());
1793
1794 // On recent Mach-O platforms, we emit the global metadata in a way that
1795 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001796 auto LivenessBinder =
1797 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1798 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001799 GlobalVariable *Liveness = new GlobalVariable(
1800 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1801 Twine("__asan_binder_") + G->getName());
1802 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1803 LivenessGlobals[i] = Liveness;
1804 }
1805
1806 // Update llvm.compiler.used, adding the new liveness globals. This is
1807 // needed so that during LTO these variables stay alive. The alternative
1808 // would be to have the linker handling the LTO symbols, but libLTO
1809 // current API does not expose access to the section for each symbol.
1810 if (!LivenessGlobals.empty())
1811 appendToCompilerUsed(M, LivenessGlobals);
1812
1813 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1814 // to look up the loaded image that contains it. Second, we can store in it
1815 // whether registration has already occurred, to prevent duplicate
1816 // registration.
1817 //
1818 // common linkage ensures that there is only one global per shared library.
1819 GlobalVariable *RegisteredFlag = new GlobalVariable(
1820 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1821 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1822 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1823
1824 IRB.CreateCall(AsanRegisterImageGlobals,
1825 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1826
1827 // We also need to unregister globals at the end, e.g., when a shared library
1828 // gets closed.
1829 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1830 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1831 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1832}
1833
1834void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1835 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1836 ArrayRef<Constant *> MetadataInitializers) {
1837 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1838 unsigned N = ExtendedGlobals.size();
1839 assert(N > 0);
1840
1841 // On platforms that don't have a custom metadata section, we emit an array
1842 // of global metadata structures.
1843 ArrayType *ArrayOfGlobalStructTy =
1844 ArrayType::get(MetadataInitializers[0]->getType(), N);
1845 auto AllGlobals = new GlobalVariable(
1846 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1847 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1848
1849 IRB.CreateCall(AsanRegisterGlobals,
1850 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1851 ConstantInt::get(IntptrTy, N)});
1852
1853 // We also need to unregister globals at the end, e.g., when a shared library
1854 // gets closed.
1855 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1856 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1857 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1858 ConstantInt::get(IntptrTy, N)});
1859}
1860
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001861// This function replaces all global variables with new variables that have
1862// trailing redzones. It also creates a function that poisons
1863// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001864// Sets *CtorComdat to true if the global registration code emitted into the
1865// asan constructor is comdat-compatible.
1866bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1867 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001868 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001869
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001870 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1871
Alexey Samsonova02e6642014-05-29 18:40:48 +00001872 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001873 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001874 }
1875
1876 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001877 if (n == 0) {
1878 *CtorComdat = true;
1879 return false;
1880 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001881
Reid Kleckner78565832016-11-29 01:32:21 +00001882 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001883
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001884 // A global is described by a structure
1885 // size_t beg;
1886 // size_t size;
1887 // size_t size_with_redzone;
1888 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001889 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001890 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001891 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001892 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001893 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001894 StructType *GlobalStructTy =
1895 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00001896 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001897 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1898 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001899
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001900 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001901
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001902 // We shouldn't merge same module names, as this string serves as unique
1903 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001904 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001905 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001906
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001907 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001908 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001909 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001910
1911 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001912 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001913 // Create string holding the global name (use global name from metadata
1914 // if it's available, otherwise just write the name of global variable).
1915 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001916 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001917 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001918
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001919 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001920 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001921 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001922 // MinRZ <= RZ <= kMaxGlobalRedzone
1923 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001924 uint64_t RZ = std::max(
1925 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001926 uint64_t RightRedzoneSize = RZ;
1927 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001928 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001929 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001930 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1931
Serge Gueltone38003f2017-05-09 19:31:13 +00001932 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
1933 Constant *NewInitializer = ConstantStruct::get(
1934 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001935
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001936 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001937 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1938 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1939 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001940 GlobalVariable *NewGlobal =
1941 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1942 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001943 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001944 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001945
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001946 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1947 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1948 G->isConstant()) {
1949 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1950 if (Seq && Seq->isCString())
1951 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1952 }
1953
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001954 // Transfer the debug info. The payload starts at offset zero so we can
1955 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001956 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001957 G->getDebugInfo(GVs);
1958 for (auto *GV : GVs)
1959 NewGlobal->addDebugInfo(GV);
1960
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001961 Value *Indices2[2];
1962 Indices2[0] = IRB.getInt32(0);
1963 Indices2[1] = IRB.getInt32(0);
1964
1965 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001966 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001967 NewGlobal->takeName(G);
1968 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001969 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001970
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001971 Constant *SourceLoc;
1972 if (!MD.SourceLoc.empty()) {
1973 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1974 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1975 } else {
1976 SourceLoc = ConstantInt::get(IntptrTy, 0);
1977 }
1978
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001979 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1980 GlobalValue *InstrumentedGlobal = NewGlobal;
1981
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00001982 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00001983 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
1984 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001985 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1986 // Create local alias for NewGlobal to avoid crash on ODR between
1987 // instrumented and non-instrumented libraries.
1988 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1989 NameForGlobal + M.getName(), NewGlobal);
1990
1991 // With local aliases, we need to provide another externally visible
1992 // symbol __odr_asan_XXX to detect ODR violation.
1993 auto *ODRIndicatorSym =
1994 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1995 Constant::getNullValue(IRB.getInt8Ty()),
1996 kODRGenPrefix + NameForGlobal, nullptr,
1997 NewGlobal->getThreadLocalMode());
1998
1999 // Set meaningful attributes for indicator symbol.
2000 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2001 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2002 ODRIndicatorSym->setAlignment(1);
2003 ODRIndicator = ODRIndicatorSym;
2004 InstrumentedGlobal = GA;
2005 }
2006
Reid Kleckner01660a32016-11-21 20:40:37 +00002007 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002008 GlobalStructTy,
2009 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002010 ConstantInt::get(IntptrTy, SizeInBytes),
2011 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2012 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002013 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002014 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002015 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002016
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002017 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002018
Kostya Serebryany20343352012-10-17 13:40:06 +00002019 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002020
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002021 Initializers[i] = Initializer;
2022 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002023
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002024 std::string ELFUniqueModuleId =
2025 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2026 : "";
2027
2028 if (!ELFUniqueModuleId.empty()) {
2029 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2030 *CtorComdat = true;
2031 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002032 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002033 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002034 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2035 } else {
2036 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002037 }
2038
Reid Kleckner01660a32016-11-21 20:40:37 +00002039 // Create calls for poisoning before initializers run and unpoisoning after.
2040 if (HasDynamicallyInitializedGlobals)
2041 createInitializerPoisonCalls(M, ModuleName);
2042
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002043 DEBUG(dbgs() << M);
2044 return true;
2045}
2046
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002047bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002048 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002049 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002050 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002051 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002052 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002053 initializeCallbacks(M);
2054
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002055 if (CompileKernel)
2056 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002057
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002058 // Create a module constructor. A destructor is created lazily because not all
2059 // platforms, and not all modules need it.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002060 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2061 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2062 /*InitArgs=*/{}, kAsanVersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002063
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002064 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002065 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002066 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002067 if (ClGlobals) {
2068 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002069 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2070 }
2071
2072 // Put the constructor and destructor in comdat if both
2073 // (1) global instrumentation is not TU-specific
2074 // (2) target is ELF.
2075 if (ClWithComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
2076 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2077 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2078 AsanCtorFunction);
2079 if (AsanDtorFunction) {
2080 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2081 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2082 AsanDtorFunction);
2083 }
2084 } else {
2085 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2086 if (AsanDtorFunction)
2087 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002088 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002089
2090 return Changed;
2091}
2092
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002093void AddressSanitizer::initializeCallbacks(Module &M) {
2094 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002095 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002096 // IsWrite, TypeSize and Exp are encoded in the function name.
2097 for (int Exp = 0; Exp < 2; Exp++) {
2098 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2099 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2100 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002101 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002102 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002103
2104 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2105 SmallVector<Type *, 2> Args1{1, IntptrTy};
2106 if (Exp) {
2107 Type *ExpType = Type::getInt32Ty(*C);
2108 Args2.push_back(ExpType);
2109 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002110 }
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002111 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2112 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2113 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2114 EndingStr,
2115 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2116
2117 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2118 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2119 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2120 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2121
2122 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2123 AccessSizeIndex++) {
2124 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2125 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2126 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2127 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2128 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2129
2130 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2131 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2132 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2133 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2134 }
2135 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002136 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002137
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002138 const std::string MemIntrinCallbackPrefix =
2139 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002140 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002141 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002142 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002143 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002144 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002145 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002146 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002147 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002148 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002149
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002150 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002151 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002152
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002153 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002154 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002155 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002156 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002157 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2158 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2159 StringRef(""), StringRef(""),
2160 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002161}
2162
2163// virtual
2164bool AddressSanitizer::doInitialization(Module &M) {
2165 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002166 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002167
2168 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002169 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002170 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002171 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002172
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002173 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002174 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002175}
2176
Keno Fischere03fae42015-12-05 14:42:34 +00002177bool AddressSanitizer::doFinalization(Module &M) {
2178 GlobalsMD.reset();
2179 return false;
2180}
2181
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002182bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2183 // For each NSObject descendant having a +load method, this method is invoked
2184 // by the ObjC runtime before any of the static constructors is called.
2185 // Therefore we need to instrument such methods with a call to __asan_init
2186 // at the beginning in order to initialize our runtime before any access to
2187 // the shadow memory.
2188 // We cannot just ignore these methods, because they may call other
2189 // instrumented functions.
2190 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002191 Function *AsanInitFunction =
2192 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002193 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002194 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002195 return true;
2196 }
2197 return false;
2198}
2199
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002200void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2201 // Generate code only when dynamic addressing is needed.
2202 if (Mapping.Offset != kDynamicShadowSentinel)
2203 return;
2204
2205 IRBuilder<> IRB(&F.front().front());
2206 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2207 kAsanShadowMemoryDynamicAddress, IntptrTy);
2208 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2209}
2210
Reid Kleckner2f907552015-07-21 17:40:14 +00002211void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2212 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2213 // to it as uninteresting. This assumes we haven't started processing allocas
2214 // yet. This check is done up front because iterating the use list in
2215 // isInterestingAlloca would be algorithmically slower.
2216 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2217
2218 // Try to get the declaration of llvm.localescape. If it's not in the module,
2219 // we can exit early.
2220 if (!F.getParent()->getFunction("llvm.localescape")) return;
2221
2222 // Look for a call to llvm.localescape call in the entry block. It can't be in
2223 // any other block.
2224 for (Instruction &I : F.getEntryBlock()) {
2225 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2226 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2227 // We found a call. Mark all the allocas passed in as uninteresting.
2228 for (Value *Arg : II->arg_operands()) {
2229 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2230 assert(AI && AI->isStaticAlloca() &&
2231 "non-static alloca arg to localescape");
2232 ProcessedAllocas[AI] = false;
2233 }
2234 break;
2235 }
2236 }
2237}
2238
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002239bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002240 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002241 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002242 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002243
Etienne Bergeron78582b22016-09-15 15:45:05 +00002244 bool FunctionModified = false;
2245
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002246 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002247 // This function needs to be called even if the function body is not
2248 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002249 if (maybeInsertAsanInitAtFunctionEntry(F))
2250 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002251
2252 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002253 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002254
Etienne Bergeron752f8832016-09-14 17:18:37 +00002255 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2256
2257 initializeCallbacks(*F.getParent());
2258 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002259
Reid Kleckner2f907552015-07-21 17:40:14 +00002260 FunctionStateRAII CleanupObj(this);
2261
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002262 maybeInsertDynamicShadowAtFunctionEntry(F);
2263
Reid Kleckner2f907552015-07-21 17:40:14 +00002264 // We can't instrument allocas used with llvm.localescape. Only static allocas
2265 // can be passed to that intrinsic.
2266 markEscapedLocalAllocas(F);
2267
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002268 // We want to instrument every address only once per basic block (unless there
2269 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002270 SmallSet<Value *, 16> TempsToInstrument;
2271 SmallVector<Instruction *, 16> ToInstrument;
2272 SmallVector<Instruction *, 8> NoReturnCalls;
2273 SmallVector<BasicBlock *, 16> AllBlocks;
2274 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002275 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002276 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002277 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002278 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002279 const TargetLibraryInfo *TLI =
2280 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002281
2282 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002283 for (auto &BB : F) {
2284 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002285 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002286 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002287 for (auto &Inst : BB) {
2288 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002289 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002290 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002291 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002292 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002293 // If we have a mask, skip instrumentation if we've already
2294 // instrumented the full object. But don't add to TempsToInstrument
2295 // because we might get another load/store with a different mask.
2296 if (MaybeMask) {
2297 if (TempsToInstrument.count(Addr))
2298 continue; // We've seen this (whole) temp in the current BB.
2299 } else {
2300 if (!TempsToInstrument.insert(Addr).second)
2301 continue; // We've seen this temp in the current BB.
2302 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002303 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002304 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002305 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2306 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002307 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002308 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002309 // ok, take it.
2310 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002311 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002312 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002313 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002314 // A call inside BB.
2315 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002316 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002317 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002318 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2319 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002320 continue;
2321 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002322 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002323 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002324 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002325 }
2326 }
2327
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002328 bool UseCalls =
2329 CompileKernel ||
2330 (ClInstrumentationWithCallsThreshold >= 0 &&
2331 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002332 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002333 ObjectSizeOpts ObjSizeOpts;
2334 ObjSizeOpts.RoundToAlign = true;
2335 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002336
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002337 // Instrument.
2338 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002339 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002340 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2341 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002342 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002343 instrumentMop(ObjSizeVis, Inst, UseCalls,
2344 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002345 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002346 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002347 }
2348 NumInstrumented++;
2349 }
2350
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002351 FunctionStackPoisoner FSP(F, *this);
2352 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002353
2354 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2355 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002356 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002357 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002358 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002359 }
2360
Alexey Samsonova02e6642014-05-29 18:40:48 +00002361 for (auto Inst : PointerComparisonsOrSubtracts) {
2362 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002363 NumInstrumented++;
2364 }
2365
Etienne Bergeron78582b22016-09-15 15:45:05 +00002366 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2367 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002368
Etienne Bergeron78582b22016-09-15 15:45:05 +00002369 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2370 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002371
Etienne Bergeron78582b22016-09-15 15:45:05 +00002372 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002373}
2374
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002375// Workaround for bug 11395: we don't want to instrument stack in functions
2376// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2377// FIXME: remove once the bug 11395 is fixed.
2378bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2379 if (LongSize != 32) return false;
2380 CallInst *CI = dyn_cast<CallInst>(I);
2381 if (!CI || !CI->isInlineAsm()) return false;
2382 if (CI->getNumArgOperands() <= 5) return false;
2383 // We have inline assembly with quite a few arguments.
2384 return true;
2385}
2386
2387void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2388 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002389 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2390 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002391 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2392 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002393 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002394 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002395 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002396 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002397 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002398 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002399 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2400 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002401 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002402 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2403 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002404 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002405 }
2406
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002407 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2408 std::ostringstream Name;
2409 Name << kAsanSetShadowPrefix;
2410 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002411 AsanSetShadowFunc[Val] =
2412 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002413 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002414 }
2415
Yury Gribov98b18592015-05-28 07:51:49 +00002416 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002417 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002418 AsanAllocasUnpoisonFunc =
2419 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002420 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002421}
2422
Vitaly Buka793913c2016-08-29 18:17:21 +00002423void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2424 ArrayRef<uint8_t> ShadowBytes,
2425 size_t Begin, size_t End,
2426 IRBuilder<> &IRB,
2427 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002428 if (Begin >= End)
2429 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002430
2431 const size_t LargestStoreSizeInBytes =
2432 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2433
2434 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2435
2436 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002437 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2438 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2439 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002440 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002441 if (!ShadowMask[i]) {
2442 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002443 ++i;
2444 continue;
2445 }
2446
2447 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2448 // Fit store size into the range.
2449 while (StoreSizeInBytes > End - i)
2450 StoreSizeInBytes /= 2;
2451
2452 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002453 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002454 while (j <= StoreSizeInBytes / 2)
2455 StoreSizeInBytes /= 2;
2456 }
2457
2458 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002459 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2460 if (IsLittleEndian)
2461 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2462 else
2463 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002464 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002465
2466 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2467 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002468 IRB.CreateAlignedStore(
2469 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002470
2471 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002472 }
2473}
2474
Vitaly Buka793913c2016-08-29 18:17:21 +00002475void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2476 ArrayRef<uint8_t> ShadowBytes,
2477 IRBuilder<> &IRB, Value *ShadowBase) {
2478 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2479}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002480
Vitaly Buka793913c2016-08-29 18:17:21 +00002481void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2482 ArrayRef<uint8_t> ShadowBytes,
2483 size_t Begin, size_t End,
2484 IRBuilder<> &IRB, Value *ShadowBase) {
2485 assert(ShadowMask.size() == ShadowBytes.size());
2486 size_t Done = Begin;
2487 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2488 if (!ShadowMask[i]) {
2489 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002490 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002491 }
2492 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002493 if (!AsanSetShadowFunc[Val])
2494 continue;
2495
2496 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002497 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002498 }
2499
2500 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002501 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002502 IRB.CreateCall(AsanSetShadowFunc[Val],
2503 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2504 ConstantInt::get(IntptrTy, j - i)});
2505 Done = j;
2506 }
2507 }
2508
Vitaly Buka793913c2016-08-29 18:17:21 +00002509 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002510}
2511
Kostya Serebryany6805de52013-09-10 13:16:56 +00002512// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2513// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2514static int StackMallocSizeClass(uint64_t LocalStackSize) {
2515 assert(LocalStackSize <= kMaxStackMallocSize);
2516 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002517 for (int i = 0;; i++, MaxSize *= 2)
2518 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002519 llvm_unreachable("impossible LocalStackSize");
2520}
2521
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002522PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2523 Value *ValueIfTrue,
2524 Instruction *ThenTerm,
2525 Value *ValueIfFalse) {
2526 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2527 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2528 PHI->addIncoming(ValueIfFalse, CondBlock);
2529 BasicBlock *ThenBlock = ThenTerm->getParent();
2530 PHI->addIncoming(ValueIfTrue, ThenBlock);
2531 return PHI;
2532}
2533
2534Value *FunctionStackPoisoner::createAllocaForLayout(
2535 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2536 AllocaInst *Alloca;
2537 if (Dynamic) {
2538 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2539 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2540 "MyAlloca");
2541 } else {
2542 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2543 nullptr, "MyAlloca");
2544 assert(Alloca->isStaticAlloca());
2545 }
2546 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2547 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2548 Alloca->setAlignment(FrameAlignment);
2549 return IRB.CreatePointerCast(Alloca, IntptrTy);
2550}
2551
Yury Gribov98b18592015-05-28 07:51:49 +00002552void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2553 BasicBlock &FirstBB = *F.begin();
2554 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2555 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2556 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2557 DynamicAllocaLayout->setAlignment(32);
2558}
2559
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002560void FunctionStackPoisoner::processDynamicAllocas() {
2561 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2562 assert(DynamicAllocaPoisonCallVec.empty());
2563 return;
2564 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002565
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002566 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2567 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002568 assert(APC.InsBefore);
2569 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002570 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002571 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002572
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002573 IRBuilder<> IRB(APC.InsBefore);
2574 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002575 // Dynamic allocas will be unpoisoned unconditionally below in
2576 // unpoisonDynamicAllocas.
2577 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002578 }
2579
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002580 // Handle dynamic allocas.
2581 createDynamicAllocasInitStorage();
2582 for (auto &AI : DynamicAllocaVec)
2583 handleDynamicAllocaCall(AI);
2584 unpoisonDynamicAllocas();
2585}
Yury Gribov98b18592015-05-28 07:51:49 +00002586
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002587void FunctionStackPoisoner::processStaticAllocas() {
2588 if (AllocaVec.empty()) {
2589 assert(StaticAllocaPoisonCallVec.empty());
2590 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002591 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002592
Kostya Serebryany6805de52013-09-10 13:16:56 +00002593 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002594 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002595 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002596 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002597
2598 Instruction *InsBefore = AllocaVec[0];
2599 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002600 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002601
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002602 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2603 // debug info is broken, because only entry-block allocas are treated as
2604 // regular stack slots.
2605 auto InsBeforeB = InsBefore->getParent();
2606 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002607 for (auto *AI : StaticAllocasToMoveUp)
2608 if (AI->getParent() == InsBeforeB)
2609 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002610
Reid Kleckner2f907552015-07-21 17:40:14 +00002611 // If we have a call to llvm.localescape, keep it in the entry block.
2612 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2613
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002614 SmallVector<ASanStackVariableDescription, 16> SVD;
2615 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002616 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002617 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002618 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002619 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002620 AI->getAlignment(),
2621 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002622 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002623 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002624 SVD.push_back(D);
2625 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002626
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002627 // Minimal header size (left redzone) is 4 pointers,
2628 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2629 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002630 const ASanStackFrameLayout &L =
2631 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002632
Vitaly Buka5910a922016-10-18 23:29:52 +00002633 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2634 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2635 for (auto &Desc : SVD)
2636 AllocaToSVDMap[Desc.AI] = &Desc;
2637
2638 // Update SVD with information from lifetime intrinsics.
2639 for (const auto &APC : StaticAllocaPoisonCallVec) {
2640 assert(APC.InsBefore);
2641 assert(APC.AI);
2642 assert(ASan.isInterestingAlloca(*APC.AI));
2643 assert(APC.AI->isStaticAlloca());
2644
2645 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2646 Desc.LifetimeSize = Desc.Size;
2647 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2648 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2649 if (LifetimeLoc->getFile() == FnLoc->getFile())
2650 if (unsigned Line = LifetimeLoc->getLine())
2651 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2652 }
2653 }
2654 }
2655
2656 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2657 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002658 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002659 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2660 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002661 bool DoDynamicAlloca = ClDynamicAllocaStack;
2662 // Don't do dynamic alloca or stack malloc if:
2663 // 1) There is inline asm: too often it makes assumptions on which registers
2664 // are available.
2665 // 2) There is a returns_twice call (typically setjmp), which is
2666 // optimization-hostile, and doesn't play well with introduced indirect
2667 // register-relative calculation of local variable addresses.
2668 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2669 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002670
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002671 Value *StaticAlloca =
2672 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2673
2674 Value *FakeStack;
2675 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002676
2677 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002678 // void *FakeStack = __asan_option_detect_stack_use_after_return
2679 // ? __asan_stack_malloc_N(LocalStackSize)
2680 // : nullptr;
2681 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002682 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2683 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2684 Value *UseAfterReturnIsEnabled =
2685 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002686 Constant::getNullValue(IRB.getInt32Ty()));
2687 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002688 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002689 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002690 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002691 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2692 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2693 Value *FakeStackValue =
2694 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2695 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002696 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002697 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002698 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002699 ConstantInt::get(IntptrTy, 0));
2700
2701 Value *NoFakeStack =
2702 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2703 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2704 IRBIf.SetInsertPoint(Term);
2705 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2706 Value *AllocaValue =
2707 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2708 IRB.SetInsertPoint(InsBefore);
2709 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2710 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2711 } else {
2712 // void *FakeStack = nullptr;
2713 // void *LocalStackBase = alloca(LocalStackSize);
2714 FakeStack = ConstantInt::get(IntptrTy, 0);
2715 LocalStackBase =
2716 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002717 }
2718
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002719 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002720 for (const auto &Desc : SVD) {
2721 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002722 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002723 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002724 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002725 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002726 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002727 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002728
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002729 // The left-most redzone has enough space for at least 4 pointers.
2730 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002731 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2732 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2733 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002734 // Write the frame description constant to redzone[1].
2735 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002736 IRB.CreateAdd(LocalStackBase,
2737 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2738 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002739 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002740 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002741 /*AllowMerging*/ true);
2742 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002743 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002744 // Write the PC to redzone[2].
2745 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002746 IRB.CreateAdd(LocalStackBase,
2747 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2748 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002749 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002750
Vitaly Buka793913c2016-08-29 18:17:21 +00002751 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2752
2753 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002754 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002755 // As mask we must use most poisoned case: red zones and after scope.
2756 // As bytes we can use either the same or just red zones only.
2757 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2758
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002759 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002760 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2761
2762 // Poison static allocas near lifetime intrinsics.
2763 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002764 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002765 assert(Desc.Offset % L.Granularity == 0);
2766 size_t Begin = Desc.Offset / L.Granularity;
2767 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2768
2769 IRBuilder<> IRB(APC.InsBefore);
2770 copyToShadow(ShadowAfterScope,
2771 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2772 IRB, ShadowBase);
2773 }
2774 }
2775
2776 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002777 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002778
Kostya Serebryany530e2072013-12-23 14:15:08 +00002779 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002780 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002781 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002782 // Mark the current frame as retired.
2783 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2784 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002785 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002786 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002787 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002788 // // In use-after-return mode, poison the whole stack frame.
2789 // if StackMallocIdx <= 4
2790 // // For small sizes inline the whole thing:
2791 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002792 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002793 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002794 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002795 // else
2796 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002797 Value *Cmp =
2798 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002799 TerminatorInst *ThenTerm, *ElseTerm;
2800 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2801
2802 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002803 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002804 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002805 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2806 kAsanStackUseAfterReturnMagic);
2807 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2808 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002809 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002810 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002811 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2812 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2813 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2814 IRBPoison.CreateStore(
2815 Constant::getNullValue(IRBPoison.getInt8Ty()),
2816 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2817 } else {
2818 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002819 IRBPoison.CreateCall(
2820 AsanStackFreeFunc[StackMallocIdx],
2821 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002822 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002823
2824 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002825 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002826 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002827 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002828 }
2829 }
2830
Kostya Serebryany09959942012-10-19 06:20:53 +00002831 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002832 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002833}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002834
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002835void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002836 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002837 // For now just insert the call to ASan runtime.
2838 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2839 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002840 IRB.CreateCall(
2841 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2842 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002843}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002844
2845// Handling llvm.lifetime intrinsics for a given %alloca:
2846// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2847// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2848// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2849// could be poisoned by previous llvm.lifetime.end instruction, as the
2850// variable may go in and out of scope several times, e.g. in loops).
2851// (3) if we poisoned at least one %alloca in a function,
2852// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002853
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002854AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2855 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002856 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002857 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002858 // See if we've already calculated (or started to calculate) alloca for a
2859 // given value.
2860 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002861 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002862 // Store 0 while we're calculating alloca for value V to avoid
2863 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002864 AllocaForValue[V] = nullptr;
2865 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002866 if (CastInst *CI = dyn_cast<CastInst>(V))
2867 Res = findAllocaForValue(CI->getOperand(0));
2868 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002869 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002870 // Allow self-referencing phi-nodes.
2871 if (IncValue == PN) continue;
2872 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2873 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002874 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2875 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002876 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002877 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002878 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2879 Res = findAllocaForValue(EP->getPointerOperand());
2880 } else {
2881 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002882 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002883 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002884 return Res;
2885}
Yury Gribov55441bb2014-11-21 10:29:50 +00002886
Yury Gribov98b18592015-05-28 07:51:49 +00002887void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002888 IRBuilder<> IRB(AI);
2889
Yury Gribov55441bb2014-11-21 10:29:50 +00002890 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2891 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2892
2893 Value *Zero = Constant::getNullValue(IntptrTy);
2894 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2895 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002896
2897 // Since we need to extend alloca with additional memory to locate
2898 // redzones, and OldSize is number of allocated blocks with
2899 // ElementSize size, get allocated memory size in bytes by
2900 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002901 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002902 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002903 Value *OldSize =
2904 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2905 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002906
2907 // PartialSize = OldSize % 32
2908 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2909
2910 // Misalign = kAllocaRzSize - PartialSize;
2911 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2912
2913 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2914 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2915 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2916
2917 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2918 // Align is added to locate left redzone, PartialPadding for possible
2919 // partial redzone and kAllocaRzSize for right redzone respectively.
2920 Value *AdditionalChunkSize = IRB.CreateAdd(
2921 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2922
2923 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2924
2925 // Insert new alloca with new NewSize and Align params.
2926 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2927 NewAlloca->setAlignment(Align);
2928
2929 // NewAddress = Address + Align
2930 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2931 ConstantInt::get(IntptrTy, Align));
2932
Yury Gribov98b18592015-05-28 07:51:49 +00002933 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002934 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002935
2936 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2937 // for unpoisoning stuff.
2938 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2939
Yury Gribov55441bb2014-11-21 10:29:50 +00002940 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2941
Yury Gribov98b18592015-05-28 07:51:49 +00002942 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002943 AI->replaceAllUsesWith(NewAddressPtr);
2944
Yury Gribov98b18592015-05-28 07:51:49 +00002945 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002946 AI->eraseFromParent();
2947}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002948
2949// isSafeAccess returns true if Addr is always inbounds with respect to its
2950// base object. For example, it is a field access or an array access with
2951// constant inbounds index.
2952bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2953 Value *Addr, uint64_t TypeSize) const {
2954 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2955 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002956 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002957 int64_t Offset = SizeOffset.second.getSExtValue();
2958 // Three checks are required to ensure safety:
2959 // . Offset >= 0 (since the offset is given from the base ptr)
2960 // . Size >= Offset (unsigned)
2961 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002962 return Offset >= 0 && Size >= uint64_t(Offset) &&
2963 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002964}