blob: d437ae93f790654eaf50a696bf6fba4d07b92790 [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"
Vitaly Buka74443f02017-07-18 22:28:03 +000025#include "llvm/ADT/Twine.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000026#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/TargetLibraryInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000029#include "llvm/IR/Argument.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000037#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000043#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/DataTypes.h"
46#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000047#include "llvm/Support/Endian.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000048#include "llvm/Support/ScopedPrinter.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000049#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000051#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000052#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000053#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000055#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000056#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000058#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059#include <algorithm>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000060#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000061#include <limits>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000062#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000064#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065
66using namespace llvm;
67
Chandler Carruth964daaa2014-04-22 02:55:47 +000068#define DEBUG_TYPE "asan"
69
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000070static const uint64_t kDefaultShadowScale = 3;
71static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
72static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000073static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
Anna Zaks3b50e702016-02-02 22:05:07 +000074static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000075static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
76static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000077static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000078static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000079static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +000080static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000081static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000082static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000083static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000084static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
85static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +000086static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000087static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000088// The shadow memory space is dynamically allocated.
89static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000090
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000091static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const size_t kMaxStackMallocSize = 1 << 16; // 64K
93static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
94static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
95
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanModuleCtorName = "asan.module_ctor";
97static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000098static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000101static const char *const kAsanUnregisterGlobalsName =
102 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000103static const char *const kAsanRegisterImageGlobalsName =
104 "__asan_register_image_globals";
105static const char *const kAsanUnregisterImageGlobalsName =
106 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000107static const char *const kAsanRegisterElfGlobalsName =
108 "__asan_register_elf_globals";
109static const char *const kAsanUnregisterElfGlobalsName =
110 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000111static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
112static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000113static const char *const kAsanInitName = "__asan_init";
114static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000115 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000116static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
117static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000118static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000119static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000120static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
121static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000122static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000123static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000124static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000125static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000126static const char *const kAsanPoisonStackMemoryName =
127 "__asan_poison_stack_memory";
128static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000129 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000130
131// ASan version script has __asan_* wildcard. Triple underscore prevents a
132// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000133static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000134 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000135
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000136static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000137 "__asan_option_detect_stack_use_after_return";
138
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000139static const char *const kAsanShadowMemoryDynamicAddress =
140 "__asan_shadow_memory_dynamic_address";
141
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000142static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
143static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000144
Kostya Serebryany874dae62012-07-16 16:15:40 +0000145// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
146static const size_t kNumberOfAccessSizes = 5;
147
Yury Gribov55441bb2014-11-21 10:29:50 +0000148static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000149
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000150// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000151static cl::opt<bool> ClEnableKasan(
152 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
153 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000154static cl::opt<bool> ClRecover(
155 "asan-recover",
156 cl::desc("Enable recovery mode (continue-after-error)."),
157 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000158
159// This flag may need to be replaced with -f[no-]asan-reads.
160static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000161 cl::desc("instrument read instructions"),
162 cl::Hidden, cl::init(true));
163static cl::opt<bool> ClInstrumentWrites(
164 "asan-instrument-writes", cl::desc("instrument write instructions"),
165 cl::Hidden, cl::init(true));
166static cl::opt<bool> ClInstrumentAtomics(
167 "asan-instrument-atomics",
168 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
169 cl::init(true));
170static cl::opt<bool> ClAlwaysSlowPath(
171 "asan-always-slow-path",
172 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
173 cl::init(false));
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000174static cl::opt<bool> ClForceDynamicShadow(
175 "asan-force-dynamic-shadow",
176 cl::desc("Load shadow address into a local variable for each function"),
177 cl::Hidden, cl::init(false));
178
Kostya Serebryany874dae62012-07-16 16:15:40 +0000179// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000180// in any given BB. Normally, this should be set to unlimited (INT_MAX),
181// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
182// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000183static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
184 "asan-max-ins-per-bb", cl::init(10000),
185 cl::desc("maximal number of instructions to instrument in any given BB"),
186 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000187// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
189 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000190static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
191 "asan-max-inline-poisoning-size",
192 cl::desc(
193 "Inline shadow poisoning for blocks up to the given size in bytes."),
194 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000195static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000196 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::Hidden, cl::init(true));
Vitaly Buka74443f02017-07-18 22:28:03 +0000198static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
199 cl::desc("Create redzones for byval "
200 "arguments (extra copy "
201 "required)"), cl::Hidden,
202 cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000203static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
204 cl::desc("Check stack-use-after-scope"),
205 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000206// This flag may need to be replaced with -f[no]asan-globals.
207static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000208 cl::desc("Handle global objects"), cl::Hidden,
209 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000210static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000211 cl::desc("Handle C++ initializer order"),
212 cl::Hidden, cl::init(true));
213static cl::opt<bool> ClInvalidPointerPairs(
214 "asan-detect-invalid-pointer-pair",
215 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
216 cl::init(false));
217static cl::opt<unsigned> ClRealignStack(
218 "asan-realign-stack",
219 cl::desc("Realign stack to the value of this flag (power of two)"),
220 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000221static cl::opt<int> ClInstrumentationWithCallsThreshold(
222 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000223 cl::desc(
224 "If the function being instrumented contains more than "
225 "this number of memory accesses, use callbacks instead of "
226 "inline checks (-1 means never use callbacks)."),
227 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000228static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000229 "asan-memory-access-callback-prefix",
230 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
231 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000232static cl::opt<bool>
233 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
234 cl::desc("instrument dynamic allocas"),
235 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000236static cl::opt<bool> ClSkipPromotableAllocas(
237 "asan-skip-promotable-allocas",
238 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
239 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000240
241// These flags allow to change the shadow mapping.
242// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000243// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000244static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000245 cl::desc("scale of asan shadow mapping"),
246 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000247static cl::opt<unsigned long long> ClMappingOffset(
248 "asan-mapping-offset",
249 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
250 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000251
252// Optimization flags. Not user visible, used mostly for testing
253// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000254static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
255 cl::Hidden, cl::init(true));
256static cl::opt<bool> ClOptSameTemp(
257 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
258 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000259static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000260 cl::desc("Don't instrument scalar globals"),
261 cl::Hidden, cl::init(true));
262static cl::opt<bool> ClOptStack(
263 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
264 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000265
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000266static cl::opt<bool> ClDynamicAllocaStack(
267 "asan-stack-dynamic-alloca",
268 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000269 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000270
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000271static cl::opt<uint32_t> ClForceExperiment(
272 "asan-force-experiment",
273 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
274 cl::init(0));
275
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000276static cl::opt<bool>
277 ClUsePrivateAliasForGlobals("asan-use-private-alias",
278 cl::desc("Use private aliases for global"
279 " variables"),
280 cl::Hidden, cl::init(false));
281
Ryan Govostese51401b2016-07-05 21:53:08 +0000282static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000283 ClUseGlobalsGC("asan-globals-live-support",
284 cl::desc("Use linker features to support dead "
285 "code stripping of globals"),
286 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000287
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000288// This is on by default even though there is a bug in gold:
289// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
290static cl::opt<bool>
291 ClWithComdat("asan-with-comdat",
292 cl::desc("Place ASan constructors in comdat sections"),
293 cl::Hidden, cl::init(true));
294
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000295// Debug flags.
296static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
297 cl::init(0));
298static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
299 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
301 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000302static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
303 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000304static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000305 cl::Hidden, cl::init(-1));
306
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000307STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
308STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000309STATISTIC(NumOptimizedAccessesToGlobalVar,
310 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311STATISTIC(NumOptimizedAccessesToStackVar,
312 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000313
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000314namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000315/// Frontend-provided metadata for source location.
316struct LocationMetadata {
317 StringRef Filename;
318 int LineNo;
319 int ColumnNo;
320
321 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
322
323 bool empty() const { return Filename.empty(); }
324
325 void parse(MDNode *MDN) {
326 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000327 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
328 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000329 LineNo =
330 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
331 ColumnNo =
332 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000333 }
334};
335
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000336/// Frontend-provided metadata for global variables.
337class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000338 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000339 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000340 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000341 LocationMetadata SourceLoc;
342 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000343 bool IsDynInit;
344 bool IsBlacklisted;
345 };
346
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000347 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000348
Keno Fischere03fae42015-12-05 14:42:34 +0000349 void reset() {
350 inited_ = false;
351 Entries.clear();
352 }
353
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000354 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000355 assert(!inited_);
356 inited_ = true;
357 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000358 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000359 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000360 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000361 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000362 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000363 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000364 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000365 // We can already have an entry for GV if it was merged with another
366 // global.
367 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000368 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
369 E.SourceLoc.parse(Loc);
370 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
371 E.Name = Name->getString();
372 ConstantInt *IsDynInit =
373 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000374 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000375 ConstantInt *IsBlacklisted =
376 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000377 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000378 }
379 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000380
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000381 /// Returns metadata entry for a given global.
382 Entry get(GlobalVariable *G) const {
383 auto Pos = Entries.find(G);
384 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000385 }
386
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000387 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000388 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000389 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000390};
391
Alexey Samsonov1345d352013-01-16 13:23:28 +0000392/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000393/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000394struct ShadowMapping {
395 int Scale;
396 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000397 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000398};
399
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000400static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
401 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000402 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000403 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000404 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000405 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000406 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000407 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
408 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000409 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000410 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000411 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000412 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
413 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000414 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
415 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000416 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000417 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000418 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000419
420 ShadowMapping Mapping;
421
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000422 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000423 // Android is always PIE, which means that the beginning of the address
424 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000425 if (IsAndroid)
426 Mapping.Offset = 0;
427 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000428 Mapping.Offset = kMIPS32_ShadowOffset32;
429 else if (IsFreeBSD)
430 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000431 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000432 // If we're targeting iOS and x86, the binary is built for iOS simulator.
433 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000434 else if (IsWindows)
435 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000436 else
437 Mapping.Offset = kDefaultShadowOffset32;
438 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000439 // Fuchsia is always PIE, which means that the beginning of the address
440 // space is always available.
441 if (IsFuchsia)
442 Mapping.Offset = 0;
443 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000444 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000445 else if (IsSystemZ)
446 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000447 else if (IsFreeBSD)
448 Mapping.Offset = kFreeBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000449 else if (IsPS4CPU)
450 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000451 else if (IsLinux && IsX86_64) {
452 if (IsKasan)
453 Mapping.Offset = kLinuxKasan_ShadowOffset64;
454 else
455 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000456 } else if (IsWindows && IsX86_64) {
457 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000458 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000459 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000460 else if (IsIOS)
461 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000462 // We are using dynamic shadow offset on the 64-bit devices.
463 Mapping.Offset =
464 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000465 else if (IsAArch64)
466 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000467 else
468 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000469 }
470
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000471 if (ClForceDynamicShadow) {
472 Mapping.Offset = kDynamicShadowSentinel;
473 }
474
Alexey Samsonov1345d352013-01-16 13:23:28 +0000475 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000476 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000477 Mapping.Scale = ClMappingScale;
478 }
479
Ryan Govostes3f37df02016-05-06 10:25:22 +0000480 if (ClMappingOffset.getNumOccurrences() > 0) {
481 Mapping.Offset = ClMappingOffset;
482 }
483
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000484 // OR-ing shadow offset if more efficient (at least on x86) if the offset
485 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000486 // offset is not necessary 1/8-th of the address space. On SystemZ,
487 // we could OR the constant in a single instruction, but it's more
488 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000489 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
490 !(Mapping.Offset & (Mapping.Offset - 1)) &&
491 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000492
Alexey Samsonov1345d352013-01-16 13:23:28 +0000493 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000494}
495
Alexey Samsonov1345d352013-01-16 13:23:28 +0000496static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000497 // Redzone used for stack and globals is at least 32 bytes.
498 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000499 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000500}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000501
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000502/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000503struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000504 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
505 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000506 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000507 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000508 UseAfterScope(UseAfterScope || ClUseAfterScope),
509 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000510 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
511 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000512 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000513 return "AddressSanitizerFunctionPass";
514 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000515 void getAnalysisUsage(AnalysisUsage &AU) const override {
516 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000517 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000518 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000519 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000520 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000521 if (AI.isArrayAllocation()) {
522 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000523 assert(CI && "non-constant array size");
524 ArraySize = CI->getZExtValue();
525 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000526 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000527 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000528 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000529 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000530 }
531 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000532 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000533
Anna Zaks8ed1d812015-02-27 03:12:36 +0000534 /// If it is an interesting memory access, return the PointerOperand
535 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000536 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
537 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000538 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000539 uint64_t *TypeSize, unsigned *Alignment,
540 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000541 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000542 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000543 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000544 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
545 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000546 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000547 void instrumentUnusualSizeOrAlignment(Instruction *I,
548 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000549 uint32_t TypeSize, bool IsWrite,
550 Value *SizeArgument, bool UseCalls,
551 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000552 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
553 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000554 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000555 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000556 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000557 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000558 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000559 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000560 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000561 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000562 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000563 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000564 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000565 static char ID; // Pass identification, replacement for typeid
566
Yury Gribov3ae427d2014-12-01 08:47:58 +0000567 DominatorTree &getDominatorTree() const { return *DT; }
568
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000569 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000570 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000571
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000572 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000573 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000574 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
575 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000576
Reid Kleckner2f907552015-07-21 17:40:14 +0000577 /// Helper to cleanup per-function state.
578 struct FunctionStateRAII {
579 AddressSanitizer *Pass;
580 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
581 assert(Pass->ProcessedAllocas.empty() &&
582 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000583 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000584 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000585 ~FunctionStateRAII() {
586 Pass->LocalDynamicShadow = nullptr;
587 Pass->ProcessedAllocas.clear();
588 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000589 };
590
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000591 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000592 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000593 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000594 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000595 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000596 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000597 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000598 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000599 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000600 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000601 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000602 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
603 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
604 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
605 // This array is indexed by AccessIsWrite and Experiment.
606 Function *AsanErrorCallbackSized[2][2];
607 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000608 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000609 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000610 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000611 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000612 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000613
614 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000615};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000616
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000617class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000618public:
Yury Gribovd7731982015-11-11 10:36:49 +0000619 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000620 bool Recover = false,
621 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000622 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000623 Recover(Recover || ClRecover),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000624 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
625 // Not a typo: ClWithComdat is almost completely pointless without
626 // ClUseGlobalsGC (because then it only works on modules without
627 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
628 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
629 // argument is designed as workaround. Therefore, disable both
630 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
631 // do globals-gc.
632 UseCtorComdat(UseGlobalsGC && ClWithComdat) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000633 bool runOnModule(Module &M) override;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000634 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000635 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000636
Mehdi Amini117296c2016-10-01 02:56:57 +0000637private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000638 void initializeCallbacks(Module &M);
639
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000640 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000641 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
642 ArrayRef<GlobalVariable *> ExtendedGlobals,
643 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000644 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
645 ArrayRef<GlobalVariable *> ExtendedGlobals,
646 ArrayRef<Constant *> MetadataInitializers,
647 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000648 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
649 ArrayRef<GlobalVariable *> ExtendedGlobals,
650 ArrayRef<Constant *> MetadataInitializers);
651 void
652 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
653 ArrayRef<GlobalVariable *> ExtendedGlobals,
654 ArrayRef<Constant *> MetadataInitializers);
655
656 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
657 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000658 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
659 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000660 IRBuilder<> CreateAsanModuleDtor(Module &M);
661
Kostya Serebryany20a79972012-11-22 03:18:50 +0000662 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000663 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000664 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000665 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000666 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000667 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000668 return RedzoneSizeForScale(Mapping.Scale);
669 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000670
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000671 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000672 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000673 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000674 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000675 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000676 Type *IntptrTy;
677 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000678 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000679 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000680 Function *AsanPoisonGlobals;
681 Function *AsanUnpoisonGlobals;
682 Function *AsanRegisterGlobals;
683 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000684 Function *AsanRegisterImageGlobals;
685 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000686 Function *AsanRegisterElfGlobals;
687 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000688
689 Function *AsanCtorFunction = nullptr;
690 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000691};
692
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000693// Stack poisoning does not play well with exception handling.
694// When an exception is thrown, we essentially bypass the code
695// that unpoisones the stack. This is why the run-time library has
696// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
697// stack in the interceptor. This however does not work inside the
698// actual function which catches the exception. Most likely because the
699// compiler hoists the load of the shadow value somewhere too high.
700// This causes asan to report a non-existing bug on 453.povray.
701// It sounds like an LLVM bug.
702struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
703 Function &F;
704 AddressSanitizer &ASan;
705 DIBuilder DIB;
706 LLVMContext *C;
707 Type *IntptrTy;
708 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000709 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000710
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000711 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000712 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000713 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000714 unsigned StackAlignment;
715
Kostya Serebryany6805de52013-09-10 13:16:56 +0000716 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000717 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000718 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000719 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000720 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000721
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000722 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
723 struct AllocaPoisonCall {
724 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000725 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000726 uint64_t Size;
727 bool DoPoison;
728 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000729 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
730 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000731
Yury Gribov98b18592015-05-28 07:51:49 +0000732 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
733 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
734 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000735 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000736
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000737 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000738 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000739 AllocaForValueMapTy AllocaForValue;
740
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000741 bool HasNonEmptyInlineAsm = false;
742 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000743 std::unique_ptr<CallInst> EmptyInlineAsm;
744
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000745 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000746 : F(F),
747 ASan(ASan),
748 DIB(*F.getParent(), /*AllowUnresolved*/ false),
749 C(ASan.C),
750 IntptrTy(ASan.IntptrTy),
751 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
752 Mapping(ASan.Mapping),
753 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000754 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000755
756 bool runOnFunction() {
757 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000758
Vitaly Buka629047de2017-08-07 07:12:34 +0000759 if (ClRedzoneByvalArgs && !ClForceDynamicShadow)
760 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000761
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000762 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000763 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000764
Yury Gribov55441bb2014-11-21 10:29:50 +0000765 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000766
767 initializeCallbacks(*F.getParent());
768
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000769 processDynamicAllocas();
770 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000771
772 if (ClDebugStack) {
773 DEBUG(dbgs() << F);
774 }
775 return true;
776 }
777
Vitaly Buka74443f02017-07-18 22:28:03 +0000778 // Arguments marked with the "byval" attribute are implicitly copied without
779 // using an alloca instruction. To produce redzones for those arguments, we
780 // copy them a second time into memory allocated with an alloca instruction.
781 void copyArgsPassedByValToAllocas();
782
Yury Gribov55441bb2014-11-21 10:29:50 +0000783 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000784 // poisoned red zones around all of them.
785 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000786 void processStaticAllocas();
787 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000788
Yury Gribov98b18592015-05-28 07:51:49 +0000789 void createDynamicAllocasInitStorage();
790
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000791 // ----------------------- Visitors.
792 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000793 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000794
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000795 /// \brief Collect all Resume instructions.
796 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
797
798 /// \brief Collect all CatchReturnInst instructions.
799 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
800
Yury Gribov98b18592015-05-28 07:51:49 +0000801 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
802 Value *SavedStack) {
803 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000804 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
805 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
806 // need to adjust extracted SP to compute the address of the most recent
807 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
808 // this purpose.
809 if (!isa<ReturnInst>(InstBefore)) {
810 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
811 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
812 {IntptrTy});
813
814 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
815
816 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
817 DynamicAreaOffset);
818 }
819
Yury Gribov781bce22015-05-28 08:03:28 +0000820 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000821 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000822 }
823
Yury Gribov55441bb2014-11-21 10:29:50 +0000824 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000825 void unpoisonDynamicAllocas() {
826 for (auto &Ret : RetVec)
827 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000828
Yury Gribov98b18592015-05-28 07:51:49 +0000829 for (auto &StackRestoreInst : StackRestoreVec)
830 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
831 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000832 }
833
Yury Gribov55441bb2014-11-21 10:29:50 +0000834 // Deploy and poison redzones around dynamic alloca call. To do this, we
835 // should replace this call with another one with changed parameters and
836 // replace all its uses with new address, so
837 // addr = alloca type, old_size, align
838 // is replaced by
839 // new_size = (old_size + additional_size) * sizeof(type)
840 // tmp = alloca i8, new_size, max(align, 32)
841 // addr = tmp + 32 (first 32 bytes are for the left redzone).
842 // Additional_size is added to make new memory allocation contain not only
843 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000844 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000845
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000846 /// \brief Collect Alloca instructions we want (and can) handle.
847 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000848 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000849 if (AI.isStaticAlloca()) {
850 // Skip over allocas that are present *before* the first instrumented
851 // alloca, we don't want to move those around.
852 if (AllocaVec.empty())
853 return;
854
855 StaticAllocasToMoveUp.push_back(&AI);
856 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000857 return;
858 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000859
860 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000861 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000862 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000863 else
864 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000865 }
866
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000867 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
868 /// errors.
869 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000870 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000871 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000872 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000873 if (!ASan.UseAfterScope)
874 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000875 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000876 return;
877 // Found lifetime intrinsic, add ASan instrumentation if necessary.
878 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
879 // If size argument is undefined, don't do anything.
880 if (Size->isMinusOne()) return;
881 // Check that size doesn't saturate uint64_t and can
882 // be stored in IntptrTy.
883 const uint64_t SizeValue = Size->getValue().getLimitedValue();
884 if (SizeValue == ~0ULL ||
885 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
886 return;
887 // Find alloca instruction that corresponds to llvm.lifetime argument.
888 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000889 if (!AI || !ASan.isInterestingAlloca(*AI))
890 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000891 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000892 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000893 if (AI->isStaticAlloca())
894 StaticAllocaPoisonCallVec.push_back(APC);
895 else if (ClInstrumentDynamicAllocas)
896 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000897 }
898
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000899 void visitCallSite(CallSite CS) {
900 Instruction *I = CS.getInstruction();
901 if (CallInst *CI = dyn_cast<CallInst>(I)) {
902 HasNonEmptyInlineAsm |=
903 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
904 HasReturnsTwiceCall |= CI->canReturnTwice();
905 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000906 }
907
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000908 // ---------------------- Helpers.
909 void initializeCallbacks(Module &M);
910
Yury Gribov3ae427d2014-12-01 08:47:58 +0000911 bool doesDominateAllExits(const Instruction *I) const {
912 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000913 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000914 }
915 return true;
916 }
917
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000918 /// Finds alloca where the value comes from.
919 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000920
921 // Copies bytes from ShadowBytes into shadow memory for indexes where
922 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
923 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
924 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
925 IRBuilder<> &IRB, Value *ShadowBase);
926 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
927 size_t Begin, size_t End, IRBuilder<> &IRB,
928 Value *ShadowBase);
929 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
930 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
931 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
932
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000933 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000934
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000935 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
936 bool Dynamic);
937 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
938 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000939};
940
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000941} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000942
943char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000944INITIALIZE_PASS_BEGIN(
945 AddressSanitizer, "asan",
946 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
947 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000948INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000949INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000950INITIALIZE_PASS_END(
951 AddressSanitizer, "asan",
952 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
953 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000954FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000955 bool Recover,
956 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000957 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000958 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000959}
960
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000961char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000962INITIALIZE_PASS(
963 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000964 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000965 "ModulePass",
966 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000967ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000968 bool Recover,
969 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +0000970 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000971 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000972}
973
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000974static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000975 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000976 assert(Res < kNumberOfAccessSizes);
977 return Res;
978}
979
Bill Wendling58f8cef2013-08-06 22:52:42 +0000980// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000981static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
982 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000983 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000984 // We use private linkage for module-local strings. If they can be merged
985 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000986 GlobalVariable *GV =
987 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000988 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000989 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000990 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
991 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000992}
993
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000994/// \brief Create a global describing a source location.
995static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
996 LocationMetadata MD) {
997 Constant *LocData[] = {
998 createPrivateGlobalForString(M, MD.Filename, true),
999 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1000 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1001 };
1002 auto LocStruct = ConstantStruct::getAnon(LocData);
1003 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1004 GlobalValue::PrivateLinkage, LocStruct,
1005 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001006 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001007 return GV;
1008}
1009
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001010/// \brief Check if \p G has been created by a trusted compiler pass.
1011static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1012 // Do not instrument asan globals.
1013 if (G->getName().startswith(kAsanGenPrefix) ||
1014 G->getName().startswith(kSanCovGenPrefix) ||
1015 G->getName().startswith(kODRGenPrefix))
1016 return true;
1017
1018 // Do not instrument gcov counter arrays.
1019 if (G->getName() == "__llvm_gcov_ctr")
1020 return true;
1021
1022 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001023}
1024
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001025Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1026 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001027 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001030 Value *ShadowBase;
1031 if (LocalDynamicShadow)
1032 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001033 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001034 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1035 if (Mapping.OrShadowOffset)
1036 return IRB.CreateOr(Shadow, ShadowBase);
1037 else
1038 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001039}
1040
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001041// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001042void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1043 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001044 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001045 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001046 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001047 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1048 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1049 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001050 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001051 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001052 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001053 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1054 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1055 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001056 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001057 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001058}
1059
Anna Zaks8ed1d812015-02-27 03:12:36 +00001060/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001061bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001062 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1063
1064 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1065 return PreviouslySeenAllocaInfo->getSecond();
1066
Yury Gribov98b18592015-05-28 07:51:49 +00001067 bool IsInteresting =
1068 (AI.getAllocatedType()->isSized() &&
1069 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001070 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001071 // We are only interested in allocas not promotable to registers.
1072 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001073 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1074 // inalloca allocas are not treated as static, and we don't want
1075 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001076 !AI.isUsedWithInAlloca() &&
1077 // swifterror allocas are register promoted by ISel
1078 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001079
1080 ProcessedAllocas[&AI] = IsInteresting;
1081 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001082}
1083
Anna Zaks8ed1d812015-02-27 03:12:36 +00001084Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1085 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001086 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001087 unsigned *Alignment,
1088 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001089 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001090 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001091
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001092 // Do not instrument the load fetching the dynamic shadow address.
1093 if (LocalDynamicShadow == I)
1094 return nullptr;
1095
Anna Zaks8ed1d812015-02-27 03:12:36 +00001096 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001097 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001098 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001099 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001100 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001101 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001102 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001103 PtrOperand = LI->getPointerOperand();
1104 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001105 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001106 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001107 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001108 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001109 PtrOperand = SI->getPointerOperand();
1110 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001111 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001112 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001113 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001114 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001115 PtrOperand = RMW->getPointerOperand();
1116 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001117 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001118 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001119 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001120 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001121 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001122 } else if (auto CI = dyn_cast<CallInst>(I)) {
1123 auto *F = dyn_cast<Function>(CI->getCalledValue());
1124 if (F && (F->getName().startswith("llvm.masked.load.") ||
1125 F->getName().startswith("llvm.masked.store."))) {
1126 unsigned OpOffset = 0;
1127 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001128 if (!ClInstrumentWrites)
1129 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001130 // Masked store has an initial operand for the value.
1131 OpOffset = 1;
1132 *IsWrite = true;
1133 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001134 if (!ClInstrumentReads)
1135 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001136 *IsWrite = false;
1137 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001138
1139 auto BasePtr = CI->getOperand(0 + OpOffset);
1140 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1141 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1142 if (auto AlignmentConstant =
1143 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1144 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1145 else
1146 *Alignment = 1; // No alignment guarantees. We probably got Undef
1147 if (MaybeMask)
1148 *MaybeMask = CI->getOperand(2 + OpOffset);
1149 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001150 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001151 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001152
Anna Zaks644d9d32016-06-22 00:15:52 +00001153 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001154 // Do not instrument acesses from different address spaces; we cannot deal
1155 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001156 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1157 if (PtrTy->getPointerAddressSpace() != 0)
1158 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001159
1160 // Ignore swifterror addresses.
1161 // swifterror memory addresses are mem2reg promoted by instruction
1162 // selection. As such they cannot have regular uses like an instrumentation
1163 // function and it makes no sense to track them as memory.
1164 if (PtrOperand->isSwiftError())
1165 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001166 }
1167
Anna Zaks8ed1d812015-02-27 03:12:36 +00001168 // Treat memory accesses to promotable allocas as non-interesting since they
1169 // will not cause memory violations. This greatly speeds up the instrumented
1170 // executable at -O0.
1171 if (ClSkipPromotableAllocas)
1172 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1173 return isInterestingAlloca(*AI) ? AI : nullptr;
1174
1175 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001176}
1177
Kostya Serebryany796f6552014-02-27 12:45:36 +00001178static bool isPointerOperand(Value *V) {
1179 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1180}
1181
1182// This is a rough heuristic; it may cause both false positives and
1183// false negatives. The proper implementation requires cooperation with
1184// the frontend.
1185static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1186 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001187 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001188 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001189 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001190 } else {
1191 return false;
1192 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001193 return isPointerOperand(I->getOperand(0)) &&
1194 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001195}
1196
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001197bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1198 // If a global variable does not have dynamic initialization we don't
1199 // have to instrument it. However, if a global does not have initializer
1200 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001201 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001202}
1203
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001204void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1205 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001206 IRBuilder<> IRB(I);
1207 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1208 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001209 for (Value *&i : Param) {
1210 if (i->getType()->isPointerTy())
1211 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001212 }
David Blaikieff6409d2015-05-18 22:13:54 +00001213 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001214}
1215
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001216static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001217 Instruction *InsertBefore, Value *Addr,
1218 unsigned Alignment, unsigned Granularity,
1219 uint32_t TypeSize, bool IsWrite,
1220 Value *SizeArgument, bool UseCalls,
1221 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001222 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1223 // if the data is properly aligned.
1224 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1225 TypeSize == 128) &&
1226 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001227 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1228 nullptr, UseCalls, Exp);
1229 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1230 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001231}
1232
1233static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1234 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001235 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001236 Value *Addr, unsigned Alignment,
1237 unsigned Granularity, uint32_t TypeSize,
1238 bool IsWrite, Value *SizeArgument,
1239 bool UseCalls, uint32_t Exp) {
1240 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1241 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1242 unsigned Num = VTy->getVectorNumElements();
1243 auto Zero = ConstantInt::get(IntptrTy, 0);
1244 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001245 Value *InstrumentedAddress = nullptr;
1246 Instruction *InsertBefore = I;
1247 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1248 // dyn_cast as we might get UndefValue
1249 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001250 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001251 // Mask is constant false, so no instrumentation needed.
1252 continue;
1253 // If we have a true or undef value, fall through to doInstrumentAddress
1254 // with InsertBefore == I
1255 }
1256 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001257 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001258 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1259 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1260 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001261 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001262
1263 IRBuilder<> IRB(InsertBefore);
1264 InstrumentedAddress =
1265 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1266 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1267 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1268 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001269 }
1270}
1271
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001272void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273 Instruction *I, bool UseCalls,
1274 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001275 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001276 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001277 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001278 Value *MaybeMask = nullptr;
1279 Value *Addr =
1280 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001281 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001282
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001283 // Optimization experiments.
1284 // The experiments can be used to evaluate potential optimizations that remove
1285 // instrumentation (assess false negatives). Instead of completely removing
1286 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1287 // experiments that want to remove instrumentation of this instruction).
1288 // If Exp is non-zero, this pass will emit special calls into runtime
1289 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1290 // make runtime terminate the program in a special way (with a different
1291 // exit status). Then you run the new compiler on a buggy corpus, collect
1292 // the special terminations (ideally, you don't see them at all -- no false
1293 // negatives) and make the decision on the optimization.
1294 uint32_t Exp = ClForceExperiment;
1295
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001296 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001297 // If initialization order checking is disabled, a simple access to a
1298 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001299 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001300 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001301 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1302 NumOptimizedAccessesToGlobalVar++;
1303 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001304 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001305 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001306
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001307 if (ClOpt && ClOptStack) {
1308 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001309 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001310 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1311 NumOptimizedAccessesToStackVar++;
1312 return;
1313 }
1314 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001315
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001316 if (IsWrite)
1317 NumInstrumentedWrites++;
1318 else
1319 NumInstrumentedReads++;
1320
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001321 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001322 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001323 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1324 Alignment, Granularity, TypeSize, IsWrite,
1325 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001326 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001327 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001328 IsWrite, nullptr, UseCalls, Exp);
1329 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001330}
1331
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001332Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1333 Value *Addr, bool IsWrite,
1334 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001335 Value *SizeArgument,
1336 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001337 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001338 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1339 CallInst *Call = nullptr;
1340 if (SizeArgument) {
1341 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001342 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1343 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001344 else
David Blaikieff6409d2015-05-18 22:13:54 +00001345 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1346 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001347 } else {
1348 if (Exp == 0)
1349 Call =
1350 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1351 else
David Blaikieff6409d2015-05-18 22:13:54 +00001352 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1353 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001354 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001355
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001356 // We don't do Call->setDoesNotReturn() because the BB already has
1357 // UnreachableInst at the end.
1358 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001359 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001360 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001361}
1362
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001363Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001364 Value *ShadowValue,
1365 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001366 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001367 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001368 Value *LastAccessedByte =
1369 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001370 // (Addr & (Granularity - 1)) + size - 1
1371 if (TypeSize / 8 > 1)
1372 LastAccessedByte = IRB.CreateAdd(
1373 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1374 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001375 LastAccessedByte =
1376 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001377 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1378 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1379}
1380
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001381void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001382 Instruction *InsertBefore, Value *Addr,
1383 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001384 Value *SizeArgument, bool UseCalls,
1385 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001386 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001387 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001388 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1389
1390 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001391 if (Exp == 0)
1392 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1393 AddrLong);
1394 else
David Blaikieff6409d2015-05-18 22:13:54 +00001395 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1396 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001397 return;
1398 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001399
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001400 Type *ShadowTy =
1401 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001402 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1403 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1404 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001405 Value *ShadowValue =
1406 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001407
1408 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001409 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001410 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001411
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001412 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001413 // We use branch weights for the slow path check, to indicate that the slow
1414 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001415 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1416 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001417 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001418 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001419 IRB.SetInsertPoint(CheckTerm);
1420 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001421 if (Recover) {
1422 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1423 } else {
1424 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001425 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001426 CrashTerm = new UnreachableInst(*C, CrashBlock);
1427 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1428 ReplaceInstWithInst(CheckTerm, NewTerm);
1429 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001430 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001431 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001432 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001433
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001434 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001435 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001436 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001437}
1438
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001439// Instrument unusual size or unusual alignment.
1440// We can not do it with a single check, so we do 1-byte check for the first
1441// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1442// to report the actual access size.
1443void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001444 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1445 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1446 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001447 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1448 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1449 if (UseCalls) {
1450 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001451 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1452 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001453 else
David Blaikieff6409d2015-05-18 22:13:54 +00001454 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1455 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001456 } else {
1457 Value *LastByte = IRB.CreateIntToPtr(
1458 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1459 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001460 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1461 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001462 }
1463}
1464
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001465void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1466 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001467 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001468 IRBuilder<> IRB(&GlobalInit.front(),
1469 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001470
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001471 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001472 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1473 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001474
1475 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001476 for (auto &BB : GlobalInit.getBasicBlockList())
1477 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001478 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001479}
1480
1481void AddressSanitizerModule::createInitializerPoisonCalls(
1482 Module &M, GlobalValue *ModuleName) {
1483 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001484 if (!GV)
1485 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001486
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001487 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1488 if (!CA)
1489 return;
1490
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001491 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001492 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001493 ConstantStruct *CS = cast<ConstantStruct>(OP);
1494
1495 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001496 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001497 if (F->getName() == kAsanModuleCtorName) continue;
1498 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1499 // Don't instrument CTORs that will run before asan.module_ctor.
1500 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1501 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001502 }
1503 }
1504}
1505
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001506bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001507 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001508 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001509
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001510 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001511 if (!Ty->isSized()) return false;
1512 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001513 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001514 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001515 // Don't handle ODR linkage types and COMDATs since other modules may be built
1516 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001517 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1518 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1519 G->getLinkage() != GlobalVariable::InternalLinkage)
1520 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001521 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001522 // Two problems with thread-locals:
1523 // - The address of the main thread's copy can't be computed at link-time.
1524 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001525 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001526 // For now, just ignore this Global if the alignment is large.
1527 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001528
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001529 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001530 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001531
Anna Zaks11904602015-06-09 00:58:08 +00001532 // Globals from llvm.metadata aren't emitted, do not instrument them.
1533 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001534 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001535 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001536
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001537 // Do not instrument function pointers to initialization and termination
1538 // routines: dynamic linker will not properly handle redzones.
1539 if (Section.startswith(".preinit_array") ||
1540 Section.startswith(".init_array") ||
1541 Section.startswith(".fini_array")) {
1542 return false;
1543 }
1544
Anna Zaks11904602015-06-09 00:58:08 +00001545 // Callbacks put into the CRT initializer/terminator sections
1546 // should not be instrumented.
1547 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1548 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1549 if (Section.startswith(".CRT")) {
1550 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1551 return false;
1552 }
1553
Kuba Brecka1001bb52014-12-05 22:19:18 +00001554 if (TargetTriple.isOSBinFormatMachO()) {
1555 StringRef ParsedSegment, ParsedSection;
1556 unsigned TAA = 0, StubSize = 0;
1557 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001558 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1559 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001560 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001561
1562 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1563 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1564 // them.
1565 if (ParsedSegment == "__OBJC" ||
1566 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1567 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1568 return false;
1569 }
1570 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1571 // Constant CFString instances are compiled in the following way:
1572 // -- the string buffer is emitted into
1573 // __TEXT,__cstring,cstring_literals
1574 // -- the constant NSConstantString structure referencing that buffer
1575 // is placed into __DATA,__cfstring
1576 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1577 // Moreover, it causes the linker to crash on OS X 10.7
1578 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1579 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1580 return false;
1581 }
1582 // The linker merges the contents of cstring_literals and removes the
1583 // trailing zeroes.
1584 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1585 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1586 return false;
1587 }
1588 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001589 }
1590
1591 return true;
1592}
1593
Ryan Govostes653f9d02016-03-28 20:28:57 +00001594// On Mach-O platforms, we emit global metadata in a separate section of the
1595// binary in order to allow the linker to properly dead strip. This is only
1596// supported on recent versions of ld64.
1597bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1598 if (!TargetTriple.isOSBinFormatMachO())
1599 return false;
1600
1601 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1602 return true;
1603 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001604 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001605 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1606 return true;
1607
1608 return false;
1609}
1610
Reid Kleckner01660a32016-11-21 20:40:37 +00001611StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1612 switch (TargetTriple.getObjectFormat()) {
1613 case Triple::COFF: return ".ASAN$GL";
1614 case Triple::ELF: return "asan_globals";
1615 case Triple::MachO: return "__DATA,__asan_globals,regular";
1616 default: break;
1617 }
1618 llvm_unreachable("unsupported object format");
1619}
1620
Alexey Samsonov788381b2012-12-25 12:28:20 +00001621void AddressSanitizerModule::initializeCallbacks(Module &M) {
1622 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001623
Alexey Samsonov788381b2012-12-25 12:28:20 +00001624 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001625 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001626 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001627 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001628 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001629 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001630 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001631
Alexey Samsonov788381b2012-12-25 12:28:20 +00001632 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001633 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001634 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001635 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001636 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1637 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001638 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001639 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001640
1641 // Declare the functions that find globals in a shared object and then invoke
1642 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001643 AsanRegisterImageGlobals =
1644 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001645 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001646 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001647
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001648 AsanUnregisterImageGlobals =
1649 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001650 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001651 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001652
1653 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1654 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1655 IntptrTy, IntptrTy, IntptrTy));
1656 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1657
1658 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1659 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1660 IntptrTy, IntptrTy, IntptrTy));
1661 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001662}
1663
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001664// Put the metadata and the instrumented global in the same group. This ensures
1665// that the metadata is discarded if the instrumented global is discarded.
1666void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001667 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001668 Module &M = *G->getParent();
1669 Comdat *C = G->getComdat();
1670 if (!C) {
1671 if (!G->hasName()) {
1672 // If G is unnamed, it must be internal. Give it an artificial name
1673 // so we can put it in a comdat.
1674 assert(G->hasLocalLinkage());
1675 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1676 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001677
1678 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1679 std::string Name = G->getName();
1680 Name += InternalSuffix;
1681 C = M.getOrInsertComdat(Name);
1682 } else {
1683 C = M.getOrInsertComdat(G->getName());
1684 }
1685
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001686 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1687 if (TargetTriple.isOSBinFormatCOFF())
1688 C->setSelectionKind(Comdat::NoDuplicates);
1689 G->setComdat(C);
1690 }
1691
1692 assert(G->hasComdat());
1693 Metadata->setComdat(G->getComdat());
1694}
1695
1696// Create a separate metadata global and put it in the appropriate ASan
1697// global registration section.
1698GlobalVariable *
1699AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1700 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001701 auto Linkage = TargetTriple.isOSBinFormatMachO()
1702 ? GlobalVariable::InternalLinkage
1703 : GlobalVariable::PrivateLinkage;
1704 GlobalVariable *Metadata = new GlobalVariable(
1705 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001706 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001707 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001708 return Metadata;
1709}
1710
1711IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001712 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001713 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1714 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1715 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001716
1717 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1718}
1719
1720void AddressSanitizerModule::InstrumentGlobalsCOFF(
1721 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1722 ArrayRef<Constant *> MetadataInitializers) {
1723 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001724 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001725
1726 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001727 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001728 GlobalVariable *G = ExtendedGlobals[i];
1729 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001730 CreateMetadataGlobal(M, Initializer, G->getName());
1731
1732 // The MSVC linker always inserts padding when linking incrementally. We
1733 // cope with that by aligning each struct to its size, which must be a power
1734 // of two.
1735 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1736 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1737 "global metadata will not be padded appropriately");
1738 Metadata->setAlignment(SizeOfGlobalStruct);
1739
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001740 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001741 }
1742}
1743
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001744void AddressSanitizerModule::InstrumentGlobalsELF(
1745 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1746 ArrayRef<Constant *> MetadataInitializers,
1747 const std::string &UniqueModuleId) {
1748 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1749
1750 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1751 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1752 GlobalVariable *G = ExtendedGlobals[i];
1753 GlobalVariable *Metadata =
1754 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1755 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1756 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1757 MetadataGlobals[i] = Metadata;
1758
1759 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1760 }
1761
1762 // Update llvm.compiler.used, adding the new metadata globals. This is
1763 // needed so that during LTO these variables stay alive.
1764 if (!MetadataGlobals.empty())
1765 appendToCompilerUsed(M, MetadataGlobals);
1766
1767 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1768 // to look up the loaded image that contains it. Second, we can store in it
1769 // whether registration has already occurred, to prevent duplicate
1770 // registration.
1771 //
1772 // Common linkage ensures that there is only one global per shared library.
1773 GlobalVariable *RegisteredFlag = new GlobalVariable(
1774 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1775 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1776 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1777
1778 // Create start and stop symbols.
1779 GlobalVariable *StartELFMetadata = new GlobalVariable(
1780 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1781 "__start_" + getGlobalMetadataSection());
1782 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1783 GlobalVariable *StopELFMetadata = new GlobalVariable(
1784 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1785 "__stop_" + getGlobalMetadataSection());
1786 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1787
1788 // Create a call to register the globals with the runtime.
1789 IRB.CreateCall(AsanRegisterElfGlobals,
1790 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1791 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1792 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1793
1794 // We also need to unregister globals at the end, e.g., when a shared library
1795 // gets closed.
1796 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1797 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1798 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1799 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1800 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1801}
1802
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001803void AddressSanitizerModule::InstrumentGlobalsMachO(
1804 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1805 ArrayRef<Constant *> MetadataInitializers) {
1806 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1807
1808 // On recent Mach-O platforms, use a structure which binds the liveness of
1809 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1810 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001811 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001812 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1813
1814 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1815 Constant *Initializer = MetadataInitializers[i];
1816 GlobalVariable *G = ExtendedGlobals[i];
1817 GlobalVariable *Metadata =
1818 CreateMetadataGlobal(M, Initializer, G->getName());
1819
1820 // On recent Mach-O platforms, we emit the global metadata in a way that
1821 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001822 auto LivenessBinder =
1823 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1824 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001825 GlobalVariable *Liveness = new GlobalVariable(
1826 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1827 Twine("__asan_binder_") + G->getName());
1828 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1829 LivenessGlobals[i] = Liveness;
1830 }
1831
1832 // Update llvm.compiler.used, adding the new liveness globals. This is
1833 // needed so that during LTO these variables stay alive. The alternative
1834 // would be to have the linker handling the LTO symbols, but libLTO
1835 // current API does not expose access to the section for each symbol.
1836 if (!LivenessGlobals.empty())
1837 appendToCompilerUsed(M, LivenessGlobals);
1838
1839 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1840 // to look up the loaded image that contains it. Second, we can store in it
1841 // whether registration has already occurred, to prevent duplicate
1842 // registration.
1843 //
1844 // common linkage ensures that there is only one global per shared library.
1845 GlobalVariable *RegisteredFlag = new GlobalVariable(
1846 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1847 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1848 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1849
1850 IRB.CreateCall(AsanRegisterImageGlobals,
1851 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
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(AsanUnregisterImageGlobals,
1857 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1858}
1859
1860void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1861 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1862 ArrayRef<Constant *> MetadataInitializers) {
1863 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1864 unsigned N = ExtendedGlobals.size();
1865 assert(N > 0);
1866
1867 // On platforms that don't have a custom metadata section, we emit an array
1868 // of global metadata structures.
1869 ArrayType *ArrayOfGlobalStructTy =
1870 ArrayType::get(MetadataInitializers[0]->getType(), N);
1871 auto AllGlobals = new GlobalVariable(
1872 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1873 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1874
1875 IRB.CreateCall(AsanRegisterGlobals,
1876 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1877 ConstantInt::get(IntptrTy, N)});
1878
1879 // We also need to unregister globals at the end, e.g., when a shared library
1880 // gets closed.
1881 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1882 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1883 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1884 ConstantInt::get(IntptrTy, N)});
1885}
1886
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001887// This function replaces all global variables with new variables that have
1888// trailing redzones. It also creates a function that poisons
1889// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001890// Sets *CtorComdat to true if the global registration code emitted into the
1891// asan constructor is comdat-compatible.
1892bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1893 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001894 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001895
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001896 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1897
Alexey Samsonova02e6642014-05-29 18:40:48 +00001898 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001899 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001900 }
1901
1902 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001903 if (n == 0) {
1904 *CtorComdat = true;
1905 return false;
1906 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001907
Reid Kleckner78565832016-11-29 01:32:21 +00001908 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001909
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001910 // A global is described by a structure
1911 // size_t beg;
1912 // size_t size;
1913 // size_t size_with_redzone;
1914 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001915 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001916 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001917 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001918 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001919 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001920 StructType *GlobalStructTy =
1921 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00001922 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001923 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1924 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001925
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001926 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001927
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001928 // We shouldn't merge same module names, as this string serves as unique
1929 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001930 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001931 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001932
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001933 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001934 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001935 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001936
1937 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001938 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001939 // Create string holding the global name (use global name from metadata
1940 // if it's available, otherwise just write the name of global variable).
1941 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001942 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001943 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001944
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001945 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001946 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001947 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001948 // MinRZ <= RZ <= kMaxGlobalRedzone
1949 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001950 uint64_t RZ = std::max(
1951 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001952 uint64_t RightRedzoneSize = RZ;
1953 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001954 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001955 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001956 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1957
Serge Gueltone38003f2017-05-09 19:31:13 +00001958 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
1959 Constant *NewInitializer = ConstantStruct::get(
1960 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001961
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001962 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001963 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1964 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1965 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001966 GlobalVariable *NewGlobal =
1967 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1968 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001969 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001970 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001971
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001972 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1973 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1974 G->isConstant()) {
1975 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1976 if (Seq && Seq->isCString())
1977 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1978 }
1979
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001980 // Transfer the debug info. The payload starts at offset zero so we can
1981 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001982 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001983 G->getDebugInfo(GVs);
1984 for (auto *GV : GVs)
1985 NewGlobal->addDebugInfo(GV);
1986
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001987 Value *Indices2[2];
1988 Indices2[0] = IRB.getInt32(0);
1989 Indices2[1] = IRB.getInt32(0);
1990
1991 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001992 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001993 NewGlobal->takeName(G);
1994 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001995 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001996
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001997 Constant *SourceLoc;
1998 if (!MD.SourceLoc.empty()) {
1999 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2000 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2001 } else {
2002 SourceLoc = ConstantInt::get(IntptrTy, 0);
2003 }
2004
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002005 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2006 GlobalValue *InstrumentedGlobal = NewGlobal;
2007
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002008 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002009 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2010 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002011 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2012 // Create local alias for NewGlobal to avoid crash on ODR between
2013 // instrumented and non-instrumented libraries.
2014 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2015 NameForGlobal + M.getName(), NewGlobal);
2016
2017 // With local aliases, we need to provide another externally visible
2018 // symbol __odr_asan_XXX to detect ODR violation.
2019 auto *ODRIndicatorSym =
2020 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2021 Constant::getNullValue(IRB.getInt8Ty()),
2022 kODRGenPrefix + NameForGlobal, nullptr,
2023 NewGlobal->getThreadLocalMode());
2024
2025 // Set meaningful attributes for indicator symbol.
2026 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2027 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2028 ODRIndicatorSym->setAlignment(1);
2029 ODRIndicator = ODRIndicatorSym;
2030 InstrumentedGlobal = GA;
2031 }
2032
Reid Kleckner01660a32016-11-21 20:40:37 +00002033 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002034 GlobalStructTy,
2035 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002036 ConstantInt::get(IntptrTy, SizeInBytes),
2037 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2038 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002039 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002040 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002041 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002042
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002043 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002044
Kostya Serebryany20343352012-10-17 13:40:06 +00002045 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002046
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002047 Initializers[i] = Initializer;
2048 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002049
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002050 std::string ELFUniqueModuleId =
2051 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2052 : "";
2053
2054 if (!ELFUniqueModuleId.empty()) {
2055 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2056 *CtorComdat = true;
2057 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002058 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002059 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002060 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2061 } else {
2062 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002063 }
2064
Reid Kleckner01660a32016-11-21 20:40:37 +00002065 // Create calls for poisoning before initializers run and unpoisoning after.
2066 if (HasDynamicallyInitializedGlobals)
2067 createInitializerPoisonCalls(M, ModuleName);
2068
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002069 DEBUG(dbgs() << M);
2070 return true;
2071}
2072
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002073bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002074 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002075 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002076 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002077 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002078 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002079 initializeCallbacks(M);
2080
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002081 if (CompileKernel)
2082 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002083
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002084 // Create a module constructor. A destructor is created lazily because not all
2085 // platforms, and not all modules need it.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002086 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2087 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2088 /*InitArgs=*/{}, kAsanVersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002089
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002090 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002091 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002092 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002093 if (ClGlobals) {
2094 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002095 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2096 }
2097
2098 // Put the constructor and destructor in comdat if both
2099 // (1) global instrumentation is not TU-specific
2100 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002101 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002102 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2103 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2104 AsanCtorFunction);
2105 if (AsanDtorFunction) {
2106 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2107 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2108 AsanDtorFunction);
2109 }
2110 } else {
2111 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2112 if (AsanDtorFunction)
2113 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002114 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002115
2116 return Changed;
2117}
2118
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002119void AddressSanitizer::initializeCallbacks(Module &M) {
2120 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002121 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002122 // IsWrite, TypeSize and Exp are encoded in the function name.
2123 for (int Exp = 0; Exp < 2; Exp++) {
2124 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2125 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2126 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002127 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002128 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002129
2130 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2131 SmallVector<Type *, 2> Args1{1, IntptrTy};
2132 if (Exp) {
2133 Type *ExpType = Type::getInt32Ty(*C);
2134 Args2.push_back(ExpType);
2135 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002136 }
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002137 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2138 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2139 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2140 EndingStr,
2141 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2142
2143 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2144 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2145 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2146 FunctionType::get(IRB.getVoidTy(), Args2, false)));
2147
2148 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2149 AccessSizeIndex++) {
2150 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2151 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2152 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2153 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2154 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2155
2156 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2157 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2158 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2159 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2160 }
2161 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002162 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002163
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002164 const std::string MemIntrinCallbackPrefix =
2165 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002166 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002167 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002168 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002169 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002170 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002171 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002172 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002173 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002174 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002175
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002176 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002177 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002178
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002179 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002180 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002181 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002182 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002183 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2184 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2185 StringRef(""), StringRef(""),
2186 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002187}
2188
2189// virtual
2190bool AddressSanitizer::doInitialization(Module &M) {
2191 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002192 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002193
2194 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002195 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002196 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002197 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002198
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002199 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002200 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002201}
2202
Keno Fischere03fae42015-12-05 14:42:34 +00002203bool AddressSanitizer::doFinalization(Module &M) {
2204 GlobalsMD.reset();
2205 return false;
2206}
2207
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002208bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2209 // For each NSObject descendant having a +load method, this method is invoked
2210 // by the ObjC runtime before any of the static constructors is called.
2211 // Therefore we need to instrument such methods with a call to __asan_init
2212 // at the beginning in order to initialize our runtime before any access to
2213 // the shadow memory.
2214 // We cannot just ignore these methods, because they may call other
2215 // instrumented functions.
2216 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002217 Function *AsanInitFunction =
2218 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002219 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002220 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002221 return true;
2222 }
2223 return false;
2224}
2225
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002226void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2227 // Generate code only when dynamic addressing is needed.
2228 if (Mapping.Offset != kDynamicShadowSentinel)
2229 return;
2230
2231 IRBuilder<> IRB(&F.front().front());
2232 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2233 kAsanShadowMemoryDynamicAddress, IntptrTy);
2234 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2235}
2236
Reid Kleckner2f907552015-07-21 17:40:14 +00002237void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2238 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2239 // to it as uninteresting. This assumes we haven't started processing allocas
2240 // yet. This check is done up front because iterating the use list in
2241 // isInterestingAlloca would be algorithmically slower.
2242 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2243
2244 // Try to get the declaration of llvm.localescape. If it's not in the module,
2245 // we can exit early.
2246 if (!F.getParent()->getFunction("llvm.localescape")) return;
2247
2248 // Look for a call to llvm.localescape call in the entry block. It can't be in
2249 // any other block.
2250 for (Instruction &I : F.getEntryBlock()) {
2251 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2252 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2253 // We found a call. Mark all the allocas passed in as uninteresting.
2254 for (Value *Arg : II->arg_operands()) {
2255 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2256 assert(AI && AI->isStaticAlloca() &&
2257 "non-static alloca arg to localescape");
2258 ProcessedAllocas[AI] = false;
2259 }
2260 break;
2261 }
2262 }
2263}
2264
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002265bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002266 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002267 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002268 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002269
Etienne Bergeron78582b22016-09-15 15:45:05 +00002270 bool FunctionModified = false;
2271
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002272 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002273 // This function needs to be called even if the function body is not
2274 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002275 if (maybeInsertAsanInitAtFunctionEntry(F))
2276 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002277
2278 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002279 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002280
Etienne Bergeron752f8832016-09-14 17:18:37 +00002281 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2282
2283 initializeCallbacks(*F.getParent());
2284 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002285
Reid Kleckner2f907552015-07-21 17:40:14 +00002286 FunctionStateRAII CleanupObj(this);
2287
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002288 maybeInsertDynamicShadowAtFunctionEntry(F);
2289
Reid Kleckner2f907552015-07-21 17:40:14 +00002290 // We can't instrument allocas used with llvm.localescape. Only static allocas
2291 // can be passed to that intrinsic.
2292 markEscapedLocalAllocas(F);
2293
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002294 // We want to instrument every address only once per basic block (unless there
2295 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002296 SmallSet<Value *, 16> TempsToInstrument;
2297 SmallVector<Instruction *, 16> ToInstrument;
2298 SmallVector<Instruction *, 8> NoReturnCalls;
2299 SmallVector<BasicBlock *, 16> AllBlocks;
2300 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002301 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002302 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002303 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002304 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002305 const TargetLibraryInfo *TLI =
2306 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002307
2308 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002309 for (auto &BB : F) {
2310 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002311 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002312 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002313 for (auto &Inst : BB) {
2314 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002315 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002316 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002317 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002318 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002319 // If we have a mask, skip instrumentation if we've already
2320 // instrumented the full object. But don't add to TempsToInstrument
2321 // because we might get another load/store with a different mask.
2322 if (MaybeMask) {
2323 if (TempsToInstrument.count(Addr))
2324 continue; // We've seen this (whole) temp in the current BB.
2325 } else {
2326 if (!TempsToInstrument.insert(Addr).second)
2327 continue; // We've seen this temp in the current BB.
2328 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002329 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002330 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002331 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2332 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002333 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002334 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002335 // ok, take it.
2336 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002337 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002338 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002339 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002340 // A call inside BB.
2341 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002342 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002343 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002344 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2345 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002346 continue;
2347 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002348 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002349 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002350 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002351 }
2352 }
2353
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002354 bool UseCalls =
2355 CompileKernel ||
2356 (ClInstrumentationWithCallsThreshold >= 0 &&
2357 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002358 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002359 ObjectSizeOpts ObjSizeOpts;
2360 ObjSizeOpts.RoundToAlign = true;
2361 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002362
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002363 // Instrument.
2364 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002365 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002366 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2367 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002368 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002369 instrumentMop(ObjSizeVis, Inst, UseCalls,
2370 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002371 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002372 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002373 }
2374 NumInstrumented++;
2375 }
2376
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002377 FunctionStackPoisoner FSP(F, *this);
2378 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002379
2380 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2381 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002382 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002383 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002384 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002385 }
2386
Alexey Samsonova02e6642014-05-29 18:40:48 +00002387 for (auto Inst : PointerComparisonsOrSubtracts) {
2388 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002389 NumInstrumented++;
2390 }
2391
Etienne Bergeron78582b22016-09-15 15:45:05 +00002392 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2393 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002394
Etienne Bergeron78582b22016-09-15 15:45:05 +00002395 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2396 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002397
Etienne Bergeron78582b22016-09-15 15:45:05 +00002398 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002399}
2400
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002401// Workaround for bug 11395: we don't want to instrument stack in functions
2402// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2403// FIXME: remove once the bug 11395 is fixed.
2404bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2405 if (LongSize != 32) return false;
2406 CallInst *CI = dyn_cast<CallInst>(I);
2407 if (!CI || !CI->isInlineAsm()) return false;
2408 if (CI->getNumArgOperands() <= 5) return false;
2409 // We have inline assembly with quite a few arguments.
2410 return true;
2411}
2412
2413void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2414 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002415 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2416 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002417 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2418 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002419 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002420 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002421 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002422 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002423 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002424 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002425 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2426 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002427 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002428 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2429 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002430 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002431 }
2432
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002433 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2434 std::ostringstream Name;
2435 Name << kAsanSetShadowPrefix;
2436 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002437 AsanSetShadowFunc[Val] =
2438 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002439 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002440 }
2441
Yury Gribov98b18592015-05-28 07:51:49 +00002442 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002443 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002444 AsanAllocasUnpoisonFunc =
2445 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002446 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002447}
2448
Vitaly Buka793913c2016-08-29 18:17:21 +00002449void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2450 ArrayRef<uint8_t> ShadowBytes,
2451 size_t Begin, size_t End,
2452 IRBuilder<> &IRB,
2453 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002454 if (Begin >= End)
2455 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002456
2457 const size_t LargestStoreSizeInBytes =
2458 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2459
2460 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2461
2462 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002463 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2464 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2465 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002466 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002467 if (!ShadowMask[i]) {
2468 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002469 ++i;
2470 continue;
2471 }
2472
2473 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2474 // Fit store size into the range.
2475 while (StoreSizeInBytes > End - i)
2476 StoreSizeInBytes /= 2;
2477
2478 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002479 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002480 while (j <= StoreSizeInBytes / 2)
2481 StoreSizeInBytes /= 2;
2482 }
2483
2484 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002485 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2486 if (IsLittleEndian)
2487 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2488 else
2489 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002490 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002491
2492 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2493 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002494 IRB.CreateAlignedStore(
2495 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002496
2497 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002498 }
2499}
2500
Vitaly Buka793913c2016-08-29 18:17:21 +00002501void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2502 ArrayRef<uint8_t> ShadowBytes,
2503 IRBuilder<> &IRB, Value *ShadowBase) {
2504 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2505}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002506
Vitaly Buka793913c2016-08-29 18:17:21 +00002507void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2508 ArrayRef<uint8_t> ShadowBytes,
2509 size_t Begin, size_t End,
2510 IRBuilder<> &IRB, Value *ShadowBase) {
2511 assert(ShadowMask.size() == ShadowBytes.size());
2512 size_t Done = Begin;
2513 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2514 if (!ShadowMask[i]) {
2515 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002516 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002517 }
2518 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002519 if (!AsanSetShadowFunc[Val])
2520 continue;
2521
2522 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002523 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002524 }
2525
2526 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002527 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002528 IRB.CreateCall(AsanSetShadowFunc[Val],
2529 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2530 ConstantInt::get(IntptrTy, j - i)});
2531 Done = j;
2532 }
2533 }
2534
Vitaly Buka793913c2016-08-29 18:17:21 +00002535 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002536}
2537
Kostya Serebryany6805de52013-09-10 13:16:56 +00002538// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2539// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2540static int StackMallocSizeClass(uint64_t LocalStackSize) {
2541 assert(LocalStackSize <= kMaxStackMallocSize);
2542 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002543 for (int i = 0;; i++, MaxSize *= 2)
2544 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002545 llvm_unreachable("impossible LocalStackSize");
2546}
2547
Vitaly Buka74443f02017-07-18 22:28:03 +00002548void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
2549 BasicBlock &FirstBB = *F.begin();
2550 IRBuilder<> IRB(&FirstBB, FirstBB.getFirstInsertionPt());
2551 const DataLayout &DL = F.getParent()->getDataLayout();
2552 for (Argument &Arg : F.args()) {
2553 if (Arg.hasByValAttr()) {
2554 Type *Ty = Arg.getType()->getPointerElementType();
2555 unsigned Align = Arg.getParamAlignment();
2556 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2557
2558 const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2559 "Arg" + llvm::to_string(Arg.getArgNo());
2560 AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2561 AI->setAlignment(Align);
2562 Arg.replaceAllUsesWith(AI);
2563
2564 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2565 IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2566 }
2567 }
2568}
2569
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002570PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2571 Value *ValueIfTrue,
2572 Instruction *ThenTerm,
2573 Value *ValueIfFalse) {
2574 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2575 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2576 PHI->addIncoming(ValueIfFalse, CondBlock);
2577 BasicBlock *ThenBlock = ThenTerm->getParent();
2578 PHI->addIncoming(ValueIfTrue, ThenBlock);
2579 return PHI;
2580}
2581
2582Value *FunctionStackPoisoner::createAllocaForLayout(
2583 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2584 AllocaInst *Alloca;
2585 if (Dynamic) {
2586 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2587 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2588 "MyAlloca");
2589 } else {
2590 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2591 nullptr, "MyAlloca");
2592 assert(Alloca->isStaticAlloca());
2593 }
2594 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2595 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2596 Alloca->setAlignment(FrameAlignment);
2597 return IRB.CreatePointerCast(Alloca, IntptrTy);
2598}
2599
Yury Gribov98b18592015-05-28 07:51:49 +00002600void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2601 BasicBlock &FirstBB = *F.begin();
2602 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2603 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2604 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2605 DynamicAllocaLayout->setAlignment(32);
2606}
2607
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002608void FunctionStackPoisoner::processDynamicAllocas() {
2609 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2610 assert(DynamicAllocaPoisonCallVec.empty());
2611 return;
2612 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002613
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002614 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2615 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002616 assert(APC.InsBefore);
2617 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002618 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002619 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002620
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002621 IRBuilder<> IRB(APC.InsBefore);
2622 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002623 // Dynamic allocas will be unpoisoned unconditionally below in
2624 // unpoisonDynamicAllocas.
2625 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002626 }
2627
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002628 // Handle dynamic allocas.
2629 createDynamicAllocasInitStorage();
2630 for (auto &AI : DynamicAllocaVec)
2631 handleDynamicAllocaCall(AI);
2632 unpoisonDynamicAllocas();
2633}
Yury Gribov98b18592015-05-28 07:51:49 +00002634
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002635void FunctionStackPoisoner::processStaticAllocas() {
2636 if (AllocaVec.empty()) {
2637 assert(StaticAllocaPoisonCallVec.empty());
2638 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002639 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002640
Kostya Serebryany6805de52013-09-10 13:16:56 +00002641 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002642 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002643 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002644 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002645
2646 Instruction *InsBefore = AllocaVec[0];
2647 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002648 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002649
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002650 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2651 // debug info is broken, because only entry-block allocas are treated as
2652 // regular stack slots.
2653 auto InsBeforeB = InsBefore->getParent();
2654 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002655 for (auto *AI : StaticAllocasToMoveUp)
2656 if (AI->getParent() == InsBeforeB)
2657 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002658
Reid Kleckner2f907552015-07-21 17:40:14 +00002659 // If we have a call to llvm.localescape, keep it in the entry block.
2660 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2661
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002662 SmallVector<ASanStackVariableDescription, 16> SVD;
2663 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002664 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002665 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002666 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002667 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002668 AI->getAlignment(),
2669 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002670 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002671 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002672 SVD.push_back(D);
2673 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002674
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002675 // Minimal header size (left redzone) is 4 pointers,
2676 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2677 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002678 const ASanStackFrameLayout &L =
2679 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002680
Vitaly Buka5910a922016-10-18 23:29:52 +00002681 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2682 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2683 for (auto &Desc : SVD)
2684 AllocaToSVDMap[Desc.AI] = &Desc;
2685
2686 // Update SVD with information from lifetime intrinsics.
2687 for (const auto &APC : StaticAllocaPoisonCallVec) {
2688 assert(APC.InsBefore);
2689 assert(APC.AI);
2690 assert(ASan.isInterestingAlloca(*APC.AI));
2691 assert(APC.AI->isStaticAlloca());
2692
2693 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2694 Desc.LifetimeSize = Desc.Size;
2695 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2696 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2697 if (LifetimeLoc->getFile() == FnLoc->getFile())
2698 if (unsigned Line = LifetimeLoc->getLine())
2699 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2700 }
2701 }
2702 }
2703
2704 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2705 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002706 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002707 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2708 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002709 bool DoDynamicAlloca = ClDynamicAllocaStack;
2710 // Don't do dynamic alloca or stack malloc if:
2711 // 1) There is inline asm: too often it makes assumptions on which registers
2712 // are available.
2713 // 2) There is a returns_twice call (typically setjmp), which is
2714 // optimization-hostile, and doesn't play well with introduced indirect
2715 // register-relative calculation of local variable addresses.
2716 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2717 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002718
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002719 Value *StaticAlloca =
2720 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2721
2722 Value *FakeStack;
2723 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002724
2725 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002726 // void *FakeStack = __asan_option_detect_stack_use_after_return
2727 // ? __asan_stack_malloc_N(LocalStackSize)
2728 // : nullptr;
2729 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002730 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2731 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2732 Value *UseAfterReturnIsEnabled =
2733 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002734 Constant::getNullValue(IRB.getInt32Ty()));
2735 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002736 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002737 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002738 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002739 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2740 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2741 Value *FakeStackValue =
2742 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2743 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002744 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002745 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002746 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002747 ConstantInt::get(IntptrTy, 0));
2748
2749 Value *NoFakeStack =
2750 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2751 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2752 IRBIf.SetInsertPoint(Term);
2753 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2754 Value *AllocaValue =
2755 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2756 IRB.SetInsertPoint(InsBefore);
2757 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2758 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2759 } else {
2760 // void *FakeStack = nullptr;
2761 // void *LocalStackBase = alloca(LocalStackSize);
2762 FakeStack = ConstantInt::get(IntptrTy, 0);
2763 LocalStackBase =
2764 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002765 }
2766
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002767 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002768 for (const auto &Desc : SVD) {
2769 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002770 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002771 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002772 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002773 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002774 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002775 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002776
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002777 // The left-most redzone has enough space for at least 4 pointers.
2778 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002779 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2780 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2781 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002782 // Write the frame description constant to redzone[1].
2783 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002784 IRB.CreateAdd(LocalStackBase,
2785 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2786 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002787 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002788 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002789 /*AllowMerging*/ true);
2790 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002791 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002792 // Write the PC to redzone[2].
2793 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002794 IRB.CreateAdd(LocalStackBase,
2795 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2796 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002797 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002798
Vitaly Buka793913c2016-08-29 18:17:21 +00002799 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2800
2801 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002802 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002803 // As mask we must use most poisoned case: red zones and after scope.
2804 // As bytes we can use either the same or just red zones only.
2805 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2806
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002807 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002808 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2809
2810 // Poison static allocas near lifetime intrinsics.
2811 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002812 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002813 assert(Desc.Offset % L.Granularity == 0);
2814 size_t Begin = Desc.Offset / L.Granularity;
2815 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2816
2817 IRBuilder<> IRB(APC.InsBefore);
2818 copyToShadow(ShadowAfterScope,
2819 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2820 IRB, ShadowBase);
2821 }
2822 }
2823
2824 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002825 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002826
Kostya Serebryany530e2072013-12-23 14:15:08 +00002827 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002828 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002829 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002830 // Mark the current frame as retired.
2831 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2832 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002833 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002834 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002835 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002836 // // In use-after-return mode, poison the whole stack frame.
2837 // if StackMallocIdx <= 4
2838 // // For small sizes inline the whole thing:
2839 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002840 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002841 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002842 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002843 // else
2844 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002845 Value *Cmp =
2846 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002847 TerminatorInst *ThenTerm, *ElseTerm;
2848 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2849
2850 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002851 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002852 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002853 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2854 kAsanStackUseAfterReturnMagic);
2855 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2856 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002857 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002858 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002859 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2860 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2861 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2862 IRBPoison.CreateStore(
2863 Constant::getNullValue(IRBPoison.getInt8Ty()),
2864 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2865 } else {
2866 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002867 IRBPoison.CreateCall(
2868 AsanStackFreeFunc[StackMallocIdx],
2869 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002870 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002871
2872 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002873 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002874 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002875 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002876 }
2877 }
2878
Kostya Serebryany09959942012-10-19 06:20:53 +00002879 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002880 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002881}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002882
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002883void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002884 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002885 // For now just insert the call to ASan runtime.
2886 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2887 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002888 IRB.CreateCall(
2889 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2890 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002891}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002892
2893// Handling llvm.lifetime intrinsics for a given %alloca:
2894// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2895// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2896// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2897// could be poisoned by previous llvm.lifetime.end instruction, as the
2898// variable may go in and out of scope several times, e.g. in loops).
2899// (3) if we poisoned at least one %alloca in a function,
2900// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002901
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002902AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2903 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002904 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002905 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002906 // See if we've already calculated (or started to calculate) alloca for a
2907 // given value.
2908 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002909 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002910 // Store 0 while we're calculating alloca for value V to avoid
2911 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002912 AllocaForValue[V] = nullptr;
2913 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002914 if (CastInst *CI = dyn_cast<CastInst>(V))
2915 Res = findAllocaForValue(CI->getOperand(0));
2916 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002917 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002918 // Allow self-referencing phi-nodes.
2919 if (IncValue == PN) continue;
2920 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2921 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002922 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2923 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002924 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002925 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002926 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2927 Res = findAllocaForValue(EP->getPointerOperand());
2928 } else {
2929 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002930 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002931 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002932 return Res;
2933}
Yury Gribov55441bb2014-11-21 10:29:50 +00002934
Yury Gribov98b18592015-05-28 07:51:49 +00002935void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002936 IRBuilder<> IRB(AI);
2937
Yury Gribov55441bb2014-11-21 10:29:50 +00002938 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2939 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2940
2941 Value *Zero = Constant::getNullValue(IntptrTy);
2942 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2943 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002944
2945 // Since we need to extend alloca with additional memory to locate
2946 // redzones, and OldSize is number of allocated blocks with
2947 // ElementSize size, get allocated memory size in bytes by
2948 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002949 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002950 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002951 Value *OldSize =
2952 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2953 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002954
2955 // PartialSize = OldSize % 32
2956 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2957
2958 // Misalign = kAllocaRzSize - PartialSize;
2959 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2960
2961 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2962 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2963 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2964
2965 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2966 // Align is added to locate left redzone, PartialPadding for possible
2967 // partial redzone and kAllocaRzSize for right redzone respectively.
2968 Value *AdditionalChunkSize = IRB.CreateAdd(
2969 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2970
2971 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2972
2973 // Insert new alloca with new NewSize and Align params.
2974 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2975 NewAlloca->setAlignment(Align);
2976
2977 // NewAddress = Address + Align
2978 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2979 ConstantInt::get(IntptrTy, Align));
2980
Yury Gribov98b18592015-05-28 07:51:49 +00002981 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002982 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002983
2984 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2985 // for unpoisoning stuff.
2986 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2987
Yury Gribov55441bb2014-11-21 10:29:50 +00002988 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2989
Yury Gribov98b18592015-05-28 07:51:49 +00002990 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002991 AI->replaceAllUsesWith(NewAddressPtr);
2992
Yury Gribov98b18592015-05-28 07:51:49 +00002993 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002994 AI->eraseFromParent();
2995}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002996
2997// isSafeAccess returns true if Addr is always inbounds with respect to its
2998// base object. For example, it is a field access or an array access with
2999// constant inbounds index.
3000bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3001 Value *Addr, uint64_t TypeSize) const {
3002 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3003 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003004 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003005 int64_t Offset = SizeOffset.second.getSExtValue();
3006 // Three checks are required to ensure safety:
3007 // . Offset >= 0 (since the offset is given from the base ptr)
3008 // . Size >= Offset (unsigned)
3009 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003010 return Offset >= 0 && Size >= uint64_t(Offset) &&
3011 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003012}