blob: 1f222da18e80605f852b6787a364972b3f9c0a98 [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;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +000086static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +000087static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000088static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Etienne Bergeron0ca05682016-09-30 17:46:32 +000089// The shadow memory space is dynamically allocated.
90static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000091
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000092static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000093static const size_t kMaxStackMallocSize = 1 << 16; // 64K
94static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
95static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
96
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanModuleCtorName = "asan.module_ctor";
98static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000099static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000101static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000102static const char *const kAsanUnregisterGlobalsName =
103 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000104static const char *const kAsanRegisterImageGlobalsName =
105 "__asan_register_image_globals";
106static const char *const kAsanUnregisterImageGlobalsName =
107 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000108static const char *const kAsanRegisterElfGlobalsName =
109 "__asan_register_elf_globals";
110static const char *const kAsanUnregisterElfGlobalsName =
111 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000112static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
113static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000114static const char *const kAsanInitName = "__asan_init";
115static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000116 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000117static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
118static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000119static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000120static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000121static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
122static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000123static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000124static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000125static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000126static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000127static const char *const kAsanPoisonStackMemoryName =
128 "__asan_poison_stack_memory";
129static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000130 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000131
132// ASan version script has __asan_* wildcard. Triple underscore prevents a
133// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000134static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000135 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000136
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000137static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000138 "__asan_option_detect_stack_use_after_return";
139
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000140static const char *const kAsanShadowMemoryDynamicAddress =
141 "__asan_shadow_memory_dynamic_address";
142
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000143static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
144static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000145
Kostya Serebryany874dae62012-07-16 16:15:40 +0000146// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
147static const size_t kNumberOfAccessSizes = 5;
148
Yury Gribov55441bb2014-11-21 10:29:50 +0000149static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000150
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000151// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000152static cl::opt<bool> ClEnableKasan(
153 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
154 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000155static cl::opt<bool> ClRecover(
156 "asan-recover",
157 cl::desc("Enable recovery mode (continue-after-error)."),
158 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000159
160// This flag may need to be replaced with -f[no-]asan-reads.
161static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000162 cl::desc("instrument read instructions"),
163 cl::Hidden, cl::init(true));
164static cl::opt<bool> ClInstrumentWrites(
165 "asan-instrument-writes", cl::desc("instrument write instructions"),
166 cl::Hidden, cl::init(true));
167static cl::opt<bool> ClInstrumentAtomics(
168 "asan-instrument-atomics",
169 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
170 cl::init(true));
171static cl::opt<bool> ClAlwaysSlowPath(
172 "asan-always-slow-path",
173 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
174 cl::init(false));
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000175static cl::opt<bool> ClForceDynamicShadow(
176 "asan-force-dynamic-shadow",
177 cl::desc("Load shadow address into a local variable for each function"),
178 cl::Hidden, cl::init(false));
179
Kostya Serebryany874dae62012-07-16 16:15:40 +0000180// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000181// in any given BB. Normally, this should be set to unlimited (INT_MAX),
182// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
183// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000184static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
185 "asan-max-ins-per-bb", cl::init(10000),
186 cl::desc("maximal number of instructions to instrument in any given BB"),
187 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000188// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000189static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
190 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000191static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
192 "asan-max-inline-poisoning-size",
193 cl::desc(
194 "Inline shadow poisoning for blocks up to the given size in bytes."),
195 cl::Hidden, cl::init(64));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000196static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000197 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198 cl::Hidden, cl::init(true));
Vitaly Buka74443f02017-07-18 22:28:03 +0000199static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
200 cl::desc("Create redzones for byval "
201 "arguments (extra copy "
202 "required)"), cl::Hidden,
203 cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000204static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
205 cl::desc("Check stack-use-after-scope"),
206 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000207// This flag may need to be replaced with -f[no]asan-globals.
208static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209 cl::desc("Handle global objects"), cl::Hidden,
210 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000211static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000212 cl::desc("Handle C++ initializer order"),
213 cl::Hidden, cl::init(true));
214static cl::opt<bool> ClInvalidPointerPairs(
215 "asan-detect-invalid-pointer-pair",
216 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
217 cl::init(false));
218static cl::opt<unsigned> ClRealignStack(
219 "asan-realign-stack",
220 cl::desc("Realign stack to the value of this flag (power of two)"),
221 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000222static cl::opt<int> ClInstrumentationWithCallsThreshold(
223 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224 cl::desc(
225 "If the function being instrumented contains more than "
226 "this number of memory accesses, use callbacks instead of "
227 "inline checks (-1 means never use callbacks)."),
228 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000229static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000230 "asan-memory-access-callback-prefix",
231 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
232 cl::init("__asan_"));
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000233static cl::opt<bool>
234 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
235 cl::desc("instrument dynamic allocas"),
236 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000237static cl::opt<bool> ClSkipPromotableAllocas(
238 "asan-skip-promotable-allocas",
239 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
240 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241
242// These flags allow to change the shadow mapping.
243// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000244// Shadow = (Mem >> scale) + offset
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000245static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000246 cl::desc("scale of asan shadow mapping"),
247 cl::Hidden, cl::init(0));
Ryan Govostes6194ae62016-05-06 11:22:11 +0000248static cl::opt<unsigned long long> ClMappingOffset(
249 "asan-mapping-offset",
250 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
251 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000252
253// Optimization flags. Not user visible, used mostly for testing
254// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000255static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
256 cl::Hidden, cl::init(true));
257static cl::opt<bool> ClOptSameTemp(
258 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
259 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000260static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000261 cl::desc("Don't instrument scalar globals"),
262 cl::Hidden, cl::init(true));
263static cl::opt<bool> ClOptStack(
264 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
265 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000266
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000267static cl::opt<bool> ClDynamicAllocaStack(
268 "asan-stack-dynamic-alloca",
269 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000270 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000271
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000272static cl::opt<uint32_t> ClForceExperiment(
273 "asan-force-experiment",
274 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
275 cl::init(0));
276
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000277static cl::opt<bool>
278 ClUsePrivateAliasForGlobals("asan-use-private-alias",
279 cl::desc("Use private aliases for global"
280 " variables"),
281 cl::Hidden, cl::init(false));
282
Ryan Govostese51401b2016-07-05 21:53:08 +0000283static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000284 ClUseGlobalsGC("asan-globals-live-support",
285 cl::desc("Use linker features to support dead "
286 "code stripping of globals"),
287 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000288
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000289// This is on by default even though there is a bug in gold:
290// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
291static cl::opt<bool>
292 ClWithComdat("asan-with-comdat",
293 cl::desc("Place ASan constructors in comdat sections"),
294 cl::Hidden, cl::init(true));
295
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000296// Debug flags.
297static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
298 cl::init(0));
299static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
300 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000301static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
302 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000303static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
304 cl::Hidden, cl::init(-1));
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000305static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000306 cl::Hidden, cl::init(-1));
307
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000308STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
309STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000310STATISTIC(NumOptimizedAccessesToGlobalVar,
311 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000312STATISTIC(NumOptimizedAccessesToStackVar,
313 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000314
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000315namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000316/// Frontend-provided metadata for source location.
317struct LocationMetadata {
318 StringRef Filename;
319 int LineNo;
320 int ColumnNo;
321
322 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
323
324 bool empty() const { return Filename.empty(); }
325
326 void parse(MDNode *MDN) {
327 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000328 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
329 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000330 LineNo =
331 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
332 ColumnNo =
333 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000334 }
335};
336
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000337/// Frontend-provided metadata for global variables.
338class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000339 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000340 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000341 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000342 LocationMetadata SourceLoc;
343 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000344 bool IsDynInit;
345 bool IsBlacklisted;
346 };
347
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000348 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000349
Keno Fischere03fae42015-12-05 14:42:34 +0000350 void reset() {
351 inited_ = false;
352 Entries.clear();
353 }
354
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000355 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000356 assert(!inited_);
357 inited_ = true;
358 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000359 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000360 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000361 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000362 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000363 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000364 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000365 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000366 // We can already have an entry for GV if it was merged with another
367 // global.
368 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000369 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
370 E.SourceLoc.parse(Loc);
371 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
372 E.Name = Name->getString();
373 ConstantInt *IsDynInit =
374 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000375 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000376 ConstantInt *IsBlacklisted =
377 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000378 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000379 }
380 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000381
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000382 /// Returns metadata entry for a given global.
383 Entry get(GlobalVariable *G) const {
384 auto Pos = Entries.find(G);
385 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000386 }
387
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000388 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000389 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000390 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000391};
392
Alexey Samsonov1345d352013-01-16 13:23:28 +0000393/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000394/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000395struct ShadowMapping {
396 int Scale;
397 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000398 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000399};
400
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000401static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
402 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000403 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000404 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000405 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000406 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000407 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000408 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000409 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
410 TargetTriple.getArch() == llvm::Triple::ppc64le;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000411 bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
Anna Zaks3b50e702016-02-02 22:05:07 +0000412 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000413 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000414 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
415 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000416 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
417 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000418 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000419 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000420 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000421
422 ShadowMapping Mapping;
423
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000424 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000425 // Android is always PIE, which means that the beginning of the address
426 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000427 if (IsAndroid)
428 Mapping.Offset = 0;
429 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000430 Mapping.Offset = kMIPS32_ShadowOffset32;
431 else if (IsFreeBSD)
432 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000433 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000434 // If we're targeting iOS and x86, the binary is built for iOS simulator.
435 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000436 else if (IsWindows)
437 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000438 else
439 Mapping.Offset = kDefaultShadowOffset32;
440 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000441 // Fuchsia is always PIE, which means that the beginning of the address
442 // space is always available.
443 if (IsFuchsia)
444 Mapping.Offset = 0;
445 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000446 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000447 else if (IsSystemZ)
448 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000449 else if (IsFreeBSD)
450 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000451 else if (IsNetBSD)
452 Mapping.Offset = kNetBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000453 else if (IsPS4CPU)
454 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000455 else if (IsLinux && IsX86_64) {
456 if (IsKasan)
457 Mapping.Offset = kLinuxKasan_ShadowOffset64;
458 else
459 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000460 } else if (IsWindows && IsX86_64) {
461 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000462 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000463 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000464 else if (IsIOS)
465 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000466 // We are using dynamic shadow offset on the 64-bit devices.
467 Mapping.Offset =
468 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000469 else if (IsAArch64)
470 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000471 else
472 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000473 }
474
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000475 if (ClForceDynamicShadow) {
476 Mapping.Offset = kDynamicShadowSentinel;
477 }
478
Alexey Samsonov1345d352013-01-16 13:23:28 +0000479 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000480 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000481 Mapping.Scale = ClMappingScale;
482 }
483
Ryan Govostes3f37df02016-05-06 10:25:22 +0000484 if (ClMappingOffset.getNumOccurrences() > 0) {
485 Mapping.Offset = ClMappingOffset;
486 }
487
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000488 // OR-ing shadow offset if more efficient (at least on x86) if the offset
489 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000490 // offset is not necessary 1/8-th of the address space. On SystemZ,
491 // we could OR the constant in a single instruction, but it's more
492 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000493 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
494 !(Mapping.Offset & (Mapping.Offset - 1)) &&
495 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000496
Alexey Samsonov1345d352013-01-16 13:23:28 +0000497 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000498}
499
Alexey Samsonov1345d352013-01-16 13:23:28 +0000500static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000501 // Redzone used for stack and globals is at least 32 bytes.
502 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000503 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000504}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000505
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000506/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000507struct AddressSanitizer : public FunctionPass {
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000508 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
509 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000510 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000511 Recover(Recover || ClRecover),
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000512 UseAfterScope(UseAfterScope || ClUseAfterScope),
513 LocalDynamicShadow(nullptr) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000514 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
515 }
Mehdi Amini117296c2016-10-01 02:56:57 +0000516 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000517 return "AddressSanitizerFunctionPass";
518 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000519 void getAnalysisUsage(AnalysisUsage &AU) const override {
520 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000521 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000522 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000523 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000524 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000525 if (AI.isArrayAllocation()) {
526 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000527 assert(CI && "non-constant array size");
528 ArraySize = CI->getZExtValue();
529 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000530 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000531 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000532 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000533 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000534 }
535 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000536 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000537
Anna Zaks8ed1d812015-02-27 03:12:36 +0000538 /// If it is an interesting memory access, return the PointerOperand
539 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000540 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
541 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000542 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000543 uint64_t *TypeSize, unsigned *Alignment,
544 Value **MaybeMask = nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000545 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000546 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000547 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000548 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
549 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000550 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000551 void instrumentUnusualSizeOrAlignment(Instruction *I,
552 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000553 uint32_t TypeSize, bool IsWrite,
554 Value *SizeArgument, bool UseCalls,
555 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000556 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
557 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000558 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000559 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000560 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000561 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000562 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000563 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000564 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000565 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000566 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000567 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000568 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000569 static char ID; // Pass identification, replacement for typeid
570
Yury Gribov3ae427d2014-12-01 08:47:58 +0000571 DominatorTree &getDominatorTree() const { return *DT; }
572
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000573 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000574 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000575
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000576 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000577 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000578 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
579 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000580
Reid Kleckner2f907552015-07-21 17:40:14 +0000581 /// Helper to cleanup per-function state.
582 struct FunctionStateRAII {
583 AddressSanitizer *Pass;
584 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
585 assert(Pass->ProcessedAllocas.empty() &&
586 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000587 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000588 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000589 ~FunctionStateRAII() {
590 Pass->LocalDynamicShadow = nullptr;
591 Pass->ProcessedAllocas.clear();
592 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000593 };
594
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000595 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000596 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000597 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000598 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000599 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000600 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000601 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000602 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000603 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000604 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000605 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000606 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
607 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
608 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
609 // This array is indexed by AccessIsWrite and Experiment.
610 Function *AsanErrorCallbackSized[2][2];
611 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000612 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000613 InlineAsm *EmptyAsm;
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000614 Value *LocalDynamicShadow;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000615 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000616 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000617
618 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000619};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000620
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000621class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000622public:
Yury Gribovd7731982015-11-11 10:36:49 +0000623 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000624 bool Recover = false,
625 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000626 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000627 Recover(Recover || ClRecover),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000628 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
629 // Not a typo: ClWithComdat is almost completely pointless without
630 // ClUseGlobalsGC (because then it only works on modules without
631 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
632 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
633 // argument is designed as workaround. Therefore, disable both
634 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
635 // do globals-gc.
636 UseCtorComdat(UseGlobalsGC && ClWithComdat) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000637 bool runOnModule(Module &M) override;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000638 static char ID; // Pass identification, replacement for typeid
Mehdi Amini117296c2016-10-01 02:56:57 +0000639 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000640
Mehdi Amini117296c2016-10-01 02:56:57 +0000641private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000642 void initializeCallbacks(Module &M);
643
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000644 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000645 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
646 ArrayRef<GlobalVariable *> ExtendedGlobals,
647 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000648 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
649 ArrayRef<GlobalVariable *> ExtendedGlobals,
650 ArrayRef<Constant *> MetadataInitializers,
651 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000652 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
653 ArrayRef<GlobalVariable *> ExtendedGlobals,
654 ArrayRef<Constant *> MetadataInitializers);
655 void
656 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
657 ArrayRef<GlobalVariable *> ExtendedGlobals,
658 ArrayRef<Constant *> MetadataInitializers);
659
660 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
661 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000662 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
663 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000664 IRBuilder<> CreateAsanModuleDtor(Module &M);
665
Kostya Serebryany20a79972012-11-22 03:18:50 +0000666 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000667 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000668 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000669 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000670 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000671 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000672 return RedzoneSizeForScale(Mapping.Scale);
673 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000674
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000675 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000676 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000677 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000678 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000679 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000680 Type *IntptrTy;
681 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000682 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000683 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000684 Function *AsanPoisonGlobals;
685 Function *AsanUnpoisonGlobals;
686 Function *AsanRegisterGlobals;
687 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000688 Function *AsanRegisterImageGlobals;
689 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000690 Function *AsanRegisterElfGlobals;
691 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000692
693 Function *AsanCtorFunction = nullptr;
694 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000695};
696
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000697// Stack poisoning does not play well with exception handling.
698// When an exception is thrown, we essentially bypass the code
699// that unpoisones the stack. This is why the run-time library has
700// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
701// stack in the interceptor. This however does not work inside the
702// actual function which catches the exception. Most likely because the
703// compiler hoists the load of the shadow value somewhere too high.
704// This causes asan to report a non-existing bug on 453.povray.
705// It sounds like an LLVM bug.
706struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
707 Function &F;
708 AddressSanitizer &ASan;
709 DIBuilder DIB;
710 LLVMContext *C;
711 Type *IntptrTy;
712 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000713 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000714
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000715 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000716 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000717 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000718 unsigned StackAlignment;
719
Kostya Serebryany6805de52013-09-10 13:16:56 +0000720 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000721 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000722 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000723 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000724 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000725
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000726 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
727 struct AllocaPoisonCall {
728 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000729 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000730 uint64_t Size;
731 bool DoPoison;
732 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000733 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
734 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000735
Yury Gribov98b18592015-05-28 07:51:49 +0000736 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
737 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
738 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000739 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000740
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000741 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000742 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000743 AllocaForValueMapTy AllocaForValue;
744
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000745 bool HasNonEmptyInlineAsm = false;
746 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000747 std::unique_ptr<CallInst> EmptyInlineAsm;
748
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000749 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000750 : F(F),
751 ASan(ASan),
752 DIB(*F.getParent(), /*AllowUnresolved*/ false),
753 C(ASan.C),
754 IntptrTy(ASan.IntptrTy),
755 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
756 Mapping(ASan.Mapping),
757 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000758 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000759
760 bool runOnFunction() {
761 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000762
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000763 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000764 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000765
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000766 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000767 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000768
Yury Gribov55441bb2014-11-21 10:29:50 +0000769 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000770
771 initializeCallbacks(*F.getParent());
772
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000773 processDynamicAllocas();
774 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000775
776 if (ClDebugStack) {
777 DEBUG(dbgs() << F);
778 }
779 return true;
780 }
781
Vitaly Buka74443f02017-07-18 22:28:03 +0000782 // Arguments marked with the "byval" attribute are implicitly copied without
783 // using an alloca instruction. To produce redzones for those arguments, we
784 // copy them a second time into memory allocated with an alloca instruction.
785 void copyArgsPassedByValToAllocas();
786
Yury Gribov55441bb2014-11-21 10:29:50 +0000787 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000788 // poisoned red zones around all of them.
789 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000790 void processStaticAllocas();
791 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000792
Yury Gribov98b18592015-05-28 07:51:49 +0000793 void createDynamicAllocasInitStorage();
794
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000795 // ----------------------- Visitors.
796 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000797 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000798
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000799 /// \brief Collect all Resume instructions.
800 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
801
802 /// \brief Collect all CatchReturnInst instructions.
803 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
804
Yury Gribov98b18592015-05-28 07:51:49 +0000805 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
806 Value *SavedStack) {
807 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000808 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
809 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
810 // need to adjust extracted SP to compute the address of the most recent
811 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
812 // this purpose.
813 if (!isa<ReturnInst>(InstBefore)) {
814 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
815 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
816 {IntptrTy});
817
818 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
819
820 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
821 DynamicAreaOffset);
822 }
823
Yury Gribov781bce22015-05-28 08:03:28 +0000824 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000825 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000826 }
827
Yury Gribov55441bb2014-11-21 10:29:50 +0000828 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000829 void unpoisonDynamicAllocas() {
830 for (auto &Ret : RetVec)
831 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000832
Yury Gribov98b18592015-05-28 07:51:49 +0000833 for (auto &StackRestoreInst : StackRestoreVec)
834 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
835 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000836 }
837
Yury Gribov55441bb2014-11-21 10:29:50 +0000838 // Deploy and poison redzones around dynamic alloca call. To do this, we
839 // should replace this call with another one with changed parameters and
840 // replace all its uses with new address, so
841 // addr = alloca type, old_size, align
842 // is replaced by
843 // new_size = (old_size + additional_size) * sizeof(type)
844 // tmp = alloca i8, new_size, max(align, 32)
845 // addr = tmp + 32 (first 32 bytes are for the left redzone).
846 // Additional_size is added to make new memory allocation contain not only
847 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000848 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000849
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000850 /// \brief Collect Alloca instructions we want (and can) handle.
851 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000852 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000853 if (AI.isStaticAlloca()) {
854 // Skip over allocas that are present *before* the first instrumented
855 // alloca, we don't want to move those around.
856 if (AllocaVec.empty())
857 return;
858
859 StaticAllocasToMoveUp.push_back(&AI);
860 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000861 return;
862 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000863
864 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000865 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000866 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000867 else
868 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000869 }
870
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000871 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
872 /// errors.
873 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000874 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000875 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000876 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000877 if (!ASan.UseAfterScope)
878 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000879 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000880 return;
881 // Found lifetime intrinsic, add ASan instrumentation if necessary.
882 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
883 // If size argument is undefined, don't do anything.
884 if (Size->isMinusOne()) return;
885 // Check that size doesn't saturate uint64_t and can
886 // be stored in IntptrTy.
887 const uint64_t SizeValue = Size->getValue().getLimitedValue();
888 if (SizeValue == ~0ULL ||
889 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
890 return;
891 // Find alloca instruction that corresponds to llvm.lifetime argument.
892 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000893 if (!AI || !ASan.isInterestingAlloca(*AI))
894 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000895 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000896 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000897 if (AI->isStaticAlloca())
898 StaticAllocaPoisonCallVec.push_back(APC);
899 else if (ClInstrumentDynamicAllocas)
900 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000901 }
902
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000903 void visitCallSite(CallSite CS) {
904 Instruction *I = CS.getInstruction();
905 if (CallInst *CI = dyn_cast<CallInst>(I)) {
906 HasNonEmptyInlineAsm |=
907 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
908 HasReturnsTwiceCall |= CI->canReturnTwice();
909 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000910 }
911
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000912 // ---------------------- Helpers.
913 void initializeCallbacks(Module &M);
914
Yury Gribov3ae427d2014-12-01 08:47:58 +0000915 bool doesDominateAllExits(const Instruction *I) const {
916 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000917 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000918 }
919 return true;
920 }
921
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000922 /// Finds alloca where the value comes from.
923 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000924
925 // Copies bytes from ShadowBytes into shadow memory for indexes where
926 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
927 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
928 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
929 IRBuilder<> &IRB, Value *ShadowBase);
930 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
931 size_t Begin, size_t End, IRBuilder<> &IRB,
932 Value *ShadowBase);
933 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
934 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
935 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
936
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000937 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000938
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000939 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
940 bool Dynamic);
941 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
942 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000943};
944
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000945} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000946
947char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000948INITIALIZE_PASS_BEGIN(
949 AddressSanitizer, "asan",
950 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
951 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000952INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000953INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000954INITIALIZE_PASS_END(
955 AddressSanitizer, "asan",
956 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
957 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000958FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000959 bool Recover,
960 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +0000961 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000962 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000963}
964
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000965char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000966INITIALIZE_PASS(
967 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000968 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000969 "ModulePass",
970 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000971ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000972 bool Recover,
973 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +0000974 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000975 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000976}
977
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000978static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000979 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000980 assert(Res < kNumberOfAccessSizes);
981 return Res;
982}
983
Bill Wendling58f8cef2013-08-06 22:52:42 +0000984// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000985static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
986 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000987 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000988 // We use private linkage for module-local strings. If they can be merged
989 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000990 GlobalVariable *GV =
991 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000992 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000993 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000994 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
995 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000996}
997
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000998/// \brief Create a global describing a source location.
999static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1000 LocationMetadata MD) {
1001 Constant *LocData[] = {
1002 createPrivateGlobalForString(M, MD.Filename, true),
1003 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1004 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1005 };
1006 auto LocStruct = ConstantStruct::getAnon(LocData);
1007 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1008 GlobalValue::PrivateLinkage, LocStruct,
1009 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001010 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001011 return GV;
1012}
1013
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001014/// \brief Check if \p G has been created by a trusted compiler pass.
1015static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1016 // Do not instrument asan globals.
1017 if (G->getName().startswith(kAsanGenPrefix) ||
1018 G->getName().startswith(kSanCovGenPrefix) ||
1019 G->getName().startswith(kODRGenPrefix))
1020 return true;
1021
1022 // Do not instrument gcov counter arrays.
1023 if (G->getName() == "__llvm_gcov_ctr")
1024 return true;
1025
1026 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001027}
1028
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1030 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001031 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001032 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001033 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001034 Value *ShadowBase;
1035 if (LocalDynamicShadow)
1036 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001037 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001038 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1039 if (Mapping.OrShadowOffset)
1040 return IRB.CreateOr(Shadow, ShadowBase);
1041 else
1042 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001043}
1044
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001045// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001046void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1047 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001048 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001049 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001050 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001051 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1052 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1053 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001054 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001055 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001056 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001057 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1058 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1059 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001060 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001061 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001062}
1063
Anna Zaks8ed1d812015-02-27 03:12:36 +00001064/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001065bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001066 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1067
1068 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1069 return PreviouslySeenAllocaInfo->getSecond();
1070
Yury Gribov98b18592015-05-28 07:51:49 +00001071 bool IsInteresting =
1072 (AI.getAllocatedType()->isSized() &&
1073 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001074 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001075 // We are only interested in allocas not promotable to registers.
1076 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001077 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1078 // inalloca allocas are not treated as static, and we don't want
1079 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001080 !AI.isUsedWithInAlloca() &&
1081 // swifterror allocas are register promoted by ISel
1082 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001083
1084 ProcessedAllocas[&AI] = IsInteresting;
1085 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001086}
1087
Anna Zaks8ed1d812015-02-27 03:12:36 +00001088Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1089 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001090 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001091 unsigned *Alignment,
1092 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001093 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001094 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001095
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001096 // Do not instrument the load fetching the dynamic shadow address.
1097 if (LocalDynamicShadow == I)
1098 return nullptr;
1099
Anna Zaks8ed1d812015-02-27 03:12:36 +00001100 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001101 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001102 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001103 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001104 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001105 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001106 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001107 PtrOperand = LI->getPointerOperand();
1108 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001109 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001110 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001111 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001112 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001113 PtrOperand = SI->getPointerOperand();
1114 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001115 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001116 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001117 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001118 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001119 PtrOperand = RMW->getPointerOperand();
1120 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001121 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001122 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001123 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001124 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001125 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001126 } else if (auto CI = dyn_cast<CallInst>(I)) {
1127 auto *F = dyn_cast<Function>(CI->getCalledValue());
1128 if (F && (F->getName().startswith("llvm.masked.load.") ||
1129 F->getName().startswith("llvm.masked.store."))) {
1130 unsigned OpOffset = 0;
1131 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001132 if (!ClInstrumentWrites)
1133 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001134 // Masked store has an initial operand for the value.
1135 OpOffset = 1;
1136 *IsWrite = true;
1137 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001138 if (!ClInstrumentReads)
1139 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001140 *IsWrite = false;
1141 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001142
1143 auto BasePtr = CI->getOperand(0 + OpOffset);
1144 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1145 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1146 if (auto AlignmentConstant =
1147 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1148 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1149 else
1150 *Alignment = 1; // No alignment guarantees. We probably got Undef
1151 if (MaybeMask)
1152 *MaybeMask = CI->getOperand(2 + OpOffset);
1153 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001154 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001155 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001156
Anna Zaks644d9d32016-06-22 00:15:52 +00001157 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001158 // Do not instrument acesses from different address spaces; we cannot deal
1159 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001160 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1161 if (PtrTy->getPointerAddressSpace() != 0)
1162 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001163
1164 // Ignore swifterror addresses.
1165 // swifterror memory addresses are mem2reg promoted by instruction
1166 // selection. As such they cannot have regular uses like an instrumentation
1167 // function and it makes no sense to track them as memory.
1168 if (PtrOperand->isSwiftError())
1169 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001170 }
1171
Anna Zaks8ed1d812015-02-27 03:12:36 +00001172 // Treat memory accesses to promotable allocas as non-interesting since they
1173 // will not cause memory violations. This greatly speeds up the instrumented
1174 // executable at -O0.
1175 if (ClSkipPromotableAllocas)
1176 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1177 return isInterestingAlloca(*AI) ? AI : nullptr;
1178
1179 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001180}
1181
Kostya Serebryany796f6552014-02-27 12:45:36 +00001182static bool isPointerOperand(Value *V) {
1183 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1184}
1185
1186// This is a rough heuristic; it may cause both false positives and
1187// false negatives. The proper implementation requires cooperation with
1188// the frontend.
1189static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1190 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001191 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001192 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001193 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001194 } else {
1195 return false;
1196 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001197 return isPointerOperand(I->getOperand(0)) &&
1198 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001199}
1200
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001201bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1202 // If a global variable does not have dynamic initialization we don't
1203 // have to instrument it. However, if a global does not have initializer
1204 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001205 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001206}
1207
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001208void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1209 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001210 IRBuilder<> IRB(I);
1211 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1212 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001213 for (Value *&i : Param) {
1214 if (i->getType()->isPointerTy())
1215 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001216 }
David Blaikieff6409d2015-05-18 22:13:54 +00001217 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001218}
1219
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001220static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001221 Instruction *InsertBefore, Value *Addr,
1222 unsigned Alignment, unsigned Granularity,
1223 uint32_t TypeSize, bool IsWrite,
1224 Value *SizeArgument, bool UseCalls,
1225 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001226 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1227 // if the data is properly aligned.
1228 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1229 TypeSize == 128) &&
1230 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001231 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1232 nullptr, UseCalls, Exp);
1233 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1234 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001235}
1236
1237static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1238 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001239 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001240 Value *Addr, unsigned Alignment,
1241 unsigned Granularity, uint32_t TypeSize,
1242 bool IsWrite, Value *SizeArgument,
1243 bool UseCalls, uint32_t Exp) {
1244 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1245 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1246 unsigned Num = VTy->getVectorNumElements();
1247 auto Zero = ConstantInt::get(IntptrTy, 0);
1248 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001249 Value *InstrumentedAddress = nullptr;
1250 Instruction *InsertBefore = I;
1251 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1252 // dyn_cast as we might get UndefValue
1253 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001254 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001255 // Mask is constant false, so no instrumentation needed.
1256 continue;
1257 // If we have a true or undef value, fall through to doInstrumentAddress
1258 // with InsertBefore == I
1259 }
1260 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001261 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001262 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1263 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1264 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001265 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001266
1267 IRBuilder<> IRB(InsertBefore);
1268 InstrumentedAddress =
1269 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1270 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1271 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1272 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001273 }
1274}
1275
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001276void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001277 Instruction *I, bool UseCalls,
1278 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001279 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001280 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001281 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001282 Value *MaybeMask = nullptr;
1283 Value *Addr =
1284 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001285 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001286
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001287 // Optimization experiments.
1288 // The experiments can be used to evaluate potential optimizations that remove
1289 // instrumentation (assess false negatives). Instead of completely removing
1290 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1291 // experiments that want to remove instrumentation of this instruction).
1292 // If Exp is non-zero, this pass will emit special calls into runtime
1293 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1294 // make runtime terminate the program in a special way (with a different
1295 // exit status). Then you run the new compiler on a buggy corpus, collect
1296 // the special terminations (ideally, you don't see them at all -- no false
1297 // negatives) and make the decision on the optimization.
1298 uint32_t Exp = ClForceExperiment;
1299
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001300 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001301 // If initialization order checking is disabled, a simple access to a
1302 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001303 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001304 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001305 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1306 NumOptimizedAccessesToGlobalVar++;
1307 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001308 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001309 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001310
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001311 if (ClOpt && ClOptStack) {
1312 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001313 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001314 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1315 NumOptimizedAccessesToStackVar++;
1316 return;
1317 }
1318 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001319
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001320 if (IsWrite)
1321 NumInstrumentedWrites++;
1322 else
1323 NumInstrumentedReads++;
1324
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001325 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001326 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001327 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1328 Alignment, Granularity, TypeSize, IsWrite,
1329 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001330 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001331 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001332 IsWrite, nullptr, UseCalls, Exp);
1333 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001334}
1335
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001336Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1337 Value *Addr, bool IsWrite,
1338 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001339 Value *SizeArgument,
1340 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001341 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001342 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1343 CallInst *Call = nullptr;
1344 if (SizeArgument) {
1345 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001346 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1347 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001348 else
David Blaikieff6409d2015-05-18 22:13:54 +00001349 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1350 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001351 } else {
1352 if (Exp == 0)
1353 Call =
1354 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1355 else
David Blaikieff6409d2015-05-18 22:13:54 +00001356 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1357 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001358 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001359
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001360 // We don't do Call->setDoesNotReturn() because the BB already has
1361 // UnreachableInst at the end.
1362 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001363 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001364 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001365}
1366
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001367Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001368 Value *ShadowValue,
1369 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001370 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001371 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001372 Value *LastAccessedByte =
1373 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001374 // (Addr & (Granularity - 1)) + size - 1
1375 if (TypeSize / 8 > 1)
1376 LastAccessedByte = IRB.CreateAdd(
1377 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1378 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001379 LastAccessedByte =
1380 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001381 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1382 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1383}
1384
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001385void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001386 Instruction *InsertBefore, Value *Addr,
1387 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001388 Value *SizeArgument, bool UseCalls,
1389 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001390 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001391 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001392 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1393
1394 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001395 if (Exp == 0)
1396 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1397 AddrLong);
1398 else
David Blaikieff6409d2015-05-18 22:13:54 +00001399 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1400 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001401 return;
1402 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001403
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001404 Type *ShadowTy =
1405 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001406 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1407 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1408 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001409 Value *ShadowValue =
1410 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001411
1412 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001413 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001414 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001415
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001416 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001417 // We use branch weights for the slow path check, to indicate that the slow
1418 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001419 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1420 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001421 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001422 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001423 IRB.SetInsertPoint(CheckTerm);
1424 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001425 if (Recover) {
1426 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1427 } else {
1428 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001429 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001430 CrashTerm = new UnreachableInst(*C, CrashBlock);
1431 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1432 ReplaceInstWithInst(CheckTerm, NewTerm);
1433 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001434 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001435 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001436 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001437
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001438 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001439 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001440 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001441}
1442
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001443// Instrument unusual size or unusual alignment.
1444// We can not do it with a single check, so we do 1-byte check for the first
1445// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1446// to report the actual access size.
1447void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001448 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1449 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1450 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001451 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1452 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1453 if (UseCalls) {
1454 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001455 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1456 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001457 else
David Blaikieff6409d2015-05-18 22:13:54 +00001458 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1459 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001460 } else {
1461 Value *LastByte = IRB.CreateIntToPtr(
1462 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1463 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001464 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1465 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001466 }
1467}
1468
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001469void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1470 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001471 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001472 IRBuilder<> IRB(&GlobalInit.front(),
1473 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001474
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001475 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001476 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1477 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001478
1479 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001480 for (auto &BB : GlobalInit.getBasicBlockList())
1481 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001482 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001483}
1484
1485void AddressSanitizerModule::createInitializerPoisonCalls(
1486 Module &M, GlobalValue *ModuleName) {
1487 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001488 if (!GV)
1489 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001490
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001491 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1492 if (!CA)
1493 return;
1494
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001495 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001496 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001497 ConstantStruct *CS = cast<ConstantStruct>(OP);
1498
1499 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001500 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001501 if (F->getName() == kAsanModuleCtorName) continue;
1502 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1503 // Don't instrument CTORs that will run before asan.module_ctor.
1504 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1505 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001506 }
1507 }
1508}
1509
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001510bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001511 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001512 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001513
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001514 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001515 if (!Ty->isSized()) return false;
1516 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001517 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001518 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001519 // Don't handle ODR linkage types and COMDATs since other modules may be built
1520 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001521 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1522 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1523 G->getLinkage() != GlobalVariable::InternalLinkage)
1524 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001525 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001526 // Two problems with thread-locals:
1527 // - The address of the main thread's copy can't be computed at link-time.
1528 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001529 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001530 // For now, just ignore this Global if the alignment is large.
1531 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001532
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001533 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001534 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001535
Anna Zaks11904602015-06-09 00:58:08 +00001536 // Globals from llvm.metadata aren't emitted, do not instrument them.
1537 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001538 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001539 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001540
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001541 // Do not instrument function pointers to initialization and termination
1542 // routines: dynamic linker will not properly handle redzones.
1543 if (Section.startswith(".preinit_array") ||
1544 Section.startswith(".init_array") ||
1545 Section.startswith(".fini_array")) {
1546 return false;
1547 }
1548
Anna Zaks11904602015-06-09 00:58:08 +00001549 // Callbacks put into the CRT initializer/terminator sections
1550 // should not be instrumented.
1551 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1552 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1553 if (Section.startswith(".CRT")) {
1554 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1555 return false;
1556 }
1557
Kuba Brecka1001bb52014-12-05 22:19:18 +00001558 if (TargetTriple.isOSBinFormatMachO()) {
1559 StringRef ParsedSegment, ParsedSection;
1560 unsigned TAA = 0, StubSize = 0;
1561 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001562 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1563 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001564 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001565
1566 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1567 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1568 // them.
1569 if (ParsedSegment == "__OBJC" ||
1570 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1571 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1572 return false;
1573 }
1574 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1575 // Constant CFString instances are compiled in the following way:
1576 // -- the string buffer is emitted into
1577 // __TEXT,__cstring,cstring_literals
1578 // -- the constant NSConstantString structure referencing that buffer
1579 // is placed into __DATA,__cfstring
1580 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1581 // Moreover, it causes the linker to crash on OS X 10.7
1582 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1583 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1584 return false;
1585 }
1586 // The linker merges the contents of cstring_literals and removes the
1587 // trailing zeroes.
1588 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1589 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1590 return false;
1591 }
1592 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001593 }
1594
1595 return true;
1596}
1597
Ryan Govostes653f9d02016-03-28 20:28:57 +00001598// On Mach-O platforms, we emit global metadata in a separate section of the
1599// binary in order to allow the linker to properly dead strip. This is only
1600// supported on recent versions of ld64.
1601bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1602 if (!TargetTriple.isOSBinFormatMachO())
1603 return false;
1604
1605 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1606 return true;
1607 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001608 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001609 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1610 return true;
1611
1612 return false;
1613}
1614
Reid Kleckner01660a32016-11-21 20:40:37 +00001615StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1616 switch (TargetTriple.getObjectFormat()) {
1617 case Triple::COFF: return ".ASAN$GL";
1618 case Triple::ELF: return "asan_globals";
1619 case Triple::MachO: return "__DATA,__asan_globals,regular";
1620 default: break;
1621 }
1622 llvm_unreachable("unsupported object format");
1623}
1624
Alexey Samsonov788381b2012-12-25 12:28:20 +00001625void AddressSanitizerModule::initializeCallbacks(Module &M) {
1626 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001627
Alexey Samsonov788381b2012-12-25 12:28:20 +00001628 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001629 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001630 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001631 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001632 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001633 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001634 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001635
Alexey Samsonov788381b2012-12-25 12:28:20 +00001636 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001637 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001638 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001639 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001640 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1641 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001642 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001643 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001644
1645 // Declare the functions that find globals in a shared object and then invoke
1646 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001647 AsanRegisterImageGlobals =
1648 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001649 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001650 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001651
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001652 AsanUnregisterImageGlobals =
1653 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001654 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001655 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001656
1657 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1658 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1659 IntptrTy, IntptrTy, IntptrTy));
1660 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1661
1662 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1663 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1664 IntptrTy, IntptrTy, IntptrTy));
1665 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001666}
1667
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001668// Put the metadata and the instrumented global in the same group. This ensures
1669// that the metadata is discarded if the instrumented global is discarded.
1670void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001671 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001672 Module &M = *G->getParent();
1673 Comdat *C = G->getComdat();
1674 if (!C) {
1675 if (!G->hasName()) {
1676 // If G is unnamed, it must be internal. Give it an artificial name
1677 // so we can put it in a comdat.
1678 assert(G->hasLocalLinkage());
1679 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1680 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001681
1682 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1683 std::string Name = G->getName();
1684 Name += InternalSuffix;
1685 C = M.getOrInsertComdat(Name);
1686 } else {
1687 C = M.getOrInsertComdat(G->getName());
1688 }
1689
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001690 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1691 if (TargetTriple.isOSBinFormatCOFF())
1692 C->setSelectionKind(Comdat::NoDuplicates);
1693 G->setComdat(C);
1694 }
1695
1696 assert(G->hasComdat());
1697 Metadata->setComdat(G->getComdat());
1698}
1699
1700// Create a separate metadata global and put it in the appropriate ASan
1701// global registration section.
1702GlobalVariable *
1703AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1704 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001705 auto Linkage = TargetTriple.isOSBinFormatMachO()
1706 ? GlobalVariable::InternalLinkage
1707 : GlobalVariable::PrivateLinkage;
1708 GlobalVariable *Metadata = new GlobalVariable(
1709 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001710 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001711 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001712 return Metadata;
1713}
1714
1715IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001716 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001717 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1718 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1719 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001720
1721 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1722}
1723
1724void AddressSanitizerModule::InstrumentGlobalsCOFF(
1725 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1726 ArrayRef<Constant *> MetadataInitializers) {
1727 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001728 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001729
1730 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001731 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001732 GlobalVariable *G = ExtendedGlobals[i];
1733 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001734 CreateMetadataGlobal(M, Initializer, G->getName());
1735
1736 // The MSVC linker always inserts padding when linking incrementally. We
1737 // cope with that by aligning each struct to its size, which must be a power
1738 // of two.
1739 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1740 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1741 "global metadata will not be padded appropriately");
1742 Metadata->setAlignment(SizeOfGlobalStruct);
1743
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001744 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001745 }
1746}
1747
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001748void AddressSanitizerModule::InstrumentGlobalsELF(
1749 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1750 ArrayRef<Constant *> MetadataInitializers,
1751 const std::string &UniqueModuleId) {
1752 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1753
1754 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1755 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1756 GlobalVariable *G = ExtendedGlobals[i];
1757 GlobalVariable *Metadata =
1758 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1759 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1760 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1761 MetadataGlobals[i] = Metadata;
1762
1763 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1764 }
1765
1766 // Update llvm.compiler.used, adding the new metadata globals. This is
1767 // needed so that during LTO these variables stay alive.
1768 if (!MetadataGlobals.empty())
1769 appendToCompilerUsed(M, MetadataGlobals);
1770
1771 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1772 // to look up the loaded image that contains it. Second, we can store in it
1773 // whether registration has already occurred, to prevent duplicate
1774 // registration.
1775 //
1776 // Common linkage ensures that there is only one global per shared library.
1777 GlobalVariable *RegisteredFlag = new GlobalVariable(
1778 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1779 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1780 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1781
1782 // Create start and stop symbols.
1783 GlobalVariable *StartELFMetadata = new GlobalVariable(
1784 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1785 "__start_" + getGlobalMetadataSection());
1786 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1787 GlobalVariable *StopELFMetadata = new GlobalVariable(
1788 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1789 "__stop_" + getGlobalMetadataSection());
1790 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1791
1792 // Create a call to register the globals with the runtime.
1793 IRB.CreateCall(AsanRegisterElfGlobals,
1794 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1795 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1796 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1797
1798 // We also need to unregister globals at the end, e.g., when a shared library
1799 // gets closed.
1800 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1801 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1802 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1803 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1804 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1805}
1806
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001807void AddressSanitizerModule::InstrumentGlobalsMachO(
1808 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1809 ArrayRef<Constant *> MetadataInitializers) {
1810 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1811
1812 // On recent Mach-O platforms, use a structure which binds the liveness of
1813 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1814 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001815 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001816 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1817
1818 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1819 Constant *Initializer = MetadataInitializers[i];
1820 GlobalVariable *G = ExtendedGlobals[i];
1821 GlobalVariable *Metadata =
1822 CreateMetadataGlobal(M, Initializer, G->getName());
1823
1824 // On recent Mach-O platforms, we emit the global metadata in a way that
1825 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001826 auto LivenessBinder =
1827 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1828 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001829 GlobalVariable *Liveness = new GlobalVariable(
1830 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1831 Twine("__asan_binder_") + G->getName());
1832 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1833 LivenessGlobals[i] = Liveness;
1834 }
1835
1836 // Update llvm.compiler.used, adding the new liveness globals. This is
1837 // needed so that during LTO these variables stay alive. The alternative
1838 // would be to have the linker handling the LTO symbols, but libLTO
1839 // current API does not expose access to the section for each symbol.
1840 if (!LivenessGlobals.empty())
1841 appendToCompilerUsed(M, LivenessGlobals);
1842
1843 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1844 // to look up the loaded image that contains it. Second, we can store in it
1845 // whether registration has already occurred, to prevent duplicate
1846 // registration.
1847 //
1848 // common linkage ensures that there is only one global per shared library.
1849 GlobalVariable *RegisteredFlag = new GlobalVariable(
1850 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1851 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1852 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1853
1854 IRB.CreateCall(AsanRegisterImageGlobals,
1855 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1856
1857 // We also need to unregister globals at the end, e.g., when a shared library
1858 // gets closed.
1859 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1860 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1861 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1862}
1863
1864void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1865 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1866 ArrayRef<Constant *> MetadataInitializers) {
1867 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1868 unsigned N = ExtendedGlobals.size();
1869 assert(N > 0);
1870
1871 // On platforms that don't have a custom metadata section, we emit an array
1872 // of global metadata structures.
1873 ArrayType *ArrayOfGlobalStructTy =
1874 ArrayType::get(MetadataInitializers[0]->getType(), N);
1875 auto AllGlobals = new GlobalVariable(
1876 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1877 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1878
1879 IRB.CreateCall(AsanRegisterGlobals,
1880 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1881 ConstantInt::get(IntptrTy, N)});
1882
1883 // We also need to unregister globals at the end, e.g., when a shared library
1884 // gets closed.
1885 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1886 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1887 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1888 ConstantInt::get(IntptrTy, N)});
1889}
1890
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001891// This function replaces all global variables with new variables that have
1892// trailing redzones. It also creates a function that poisons
1893// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001894// Sets *CtorComdat to true if the global registration code emitted into the
1895// asan constructor is comdat-compatible.
1896bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1897 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001898 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001899
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001900 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1901
Alexey Samsonova02e6642014-05-29 18:40:48 +00001902 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001903 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001904 }
1905
1906 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001907 if (n == 0) {
1908 *CtorComdat = true;
1909 return false;
1910 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001911
Reid Kleckner78565832016-11-29 01:32:21 +00001912 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001913
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001914 // A global is described by a structure
1915 // size_t beg;
1916 // size_t size;
1917 // size_t size_with_redzone;
1918 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001919 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001920 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001921 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001922 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001923 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001924 StructType *GlobalStructTy =
1925 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00001926 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001927 SmallVector<GlobalVariable *, 16> NewGlobals(n);
1928 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001929
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001930 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001931
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001932 // We shouldn't merge same module names, as this string serves as unique
1933 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001934 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001935 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001936
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001937 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001938 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001939 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001940
1941 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001942 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001943 // Create string holding the global name (use global name from metadata
1944 // if it's available, otherwise just write the name of global variable).
1945 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001946 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001947 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001948
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001949 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001950 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001951 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001952 // MinRZ <= RZ <= kMaxGlobalRedzone
1953 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001954 uint64_t RZ = std::max(
1955 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001956 uint64_t RightRedzoneSize = RZ;
1957 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001958 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001959 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001960 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1961
Serge Gueltone38003f2017-05-09 19:31:13 +00001962 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
1963 Constant *NewInitializer = ConstantStruct::get(
1964 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001965
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001966 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001967 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1968 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1969 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001970 GlobalVariable *NewGlobal =
1971 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1972 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001973 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001974 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001975
Kuba Breckaa28c9e82016-10-31 18:51:58 +00001976 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1977 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1978 G->isConstant()) {
1979 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1980 if (Seq && Seq->isCString())
1981 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1982 }
1983
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001984 // Transfer the debug info. The payload starts at offset zero so we can
1985 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00001986 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00001987 G->getDebugInfo(GVs);
1988 for (auto *GV : GVs)
1989 NewGlobal->addDebugInfo(GV);
1990
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001991 Value *Indices2[2];
1992 Indices2[0] = IRB.getInt32(0);
1993 Indices2[1] = IRB.getInt32(0);
1994
1995 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001996 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001997 NewGlobal->takeName(G);
1998 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001999 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002000
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002001 Constant *SourceLoc;
2002 if (!MD.SourceLoc.empty()) {
2003 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2004 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2005 } else {
2006 SourceLoc = ConstantInt::get(IntptrTy, 0);
2007 }
2008
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002009 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2010 GlobalValue *InstrumentedGlobal = NewGlobal;
2011
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002012 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002013 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2014 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002015 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2016 // Create local alias for NewGlobal to avoid crash on ODR between
2017 // instrumented and non-instrumented libraries.
2018 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2019 NameForGlobal + M.getName(), NewGlobal);
2020
2021 // With local aliases, we need to provide another externally visible
2022 // symbol __odr_asan_XXX to detect ODR violation.
2023 auto *ODRIndicatorSym =
2024 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2025 Constant::getNullValue(IRB.getInt8Ty()),
2026 kODRGenPrefix + NameForGlobal, nullptr,
2027 NewGlobal->getThreadLocalMode());
2028
2029 // Set meaningful attributes for indicator symbol.
2030 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2031 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2032 ODRIndicatorSym->setAlignment(1);
2033 ODRIndicator = ODRIndicatorSym;
2034 InstrumentedGlobal = GA;
2035 }
2036
Reid Kleckner01660a32016-11-21 20:40:37 +00002037 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002038 GlobalStructTy,
2039 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002040 ConstantInt::get(IntptrTy, SizeInBytes),
2041 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2042 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002043 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002044 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002045 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002046
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002047 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002048
Kostya Serebryany20343352012-10-17 13:40:06 +00002049 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002050
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002051 Initializers[i] = Initializer;
2052 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002053
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002054 std::string ELFUniqueModuleId =
2055 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2056 : "";
2057
2058 if (!ELFUniqueModuleId.empty()) {
2059 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2060 *CtorComdat = true;
2061 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002062 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002063 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002064 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2065 } else {
2066 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002067 }
2068
Reid Kleckner01660a32016-11-21 20:40:37 +00002069 // Create calls for poisoning before initializers run and unpoisoning after.
2070 if (HasDynamicallyInitializedGlobals)
2071 createInitializerPoisonCalls(M, ModuleName);
2072
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002073 DEBUG(dbgs() << M);
2074 return true;
2075}
2076
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002077bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002078 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002079 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002080 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002081 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002082 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002083 initializeCallbacks(M);
2084
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002085 if (CompileKernel)
2086 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002087
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002088 // Create a module constructor. A destructor is created lazily because not all
2089 // platforms, and not all modules need it.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002090 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2091 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2092 /*InitArgs=*/{}, kAsanVersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002093
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002094 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002095 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002096 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002097 if (ClGlobals) {
2098 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002099 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2100 }
2101
2102 // Put the constructor and destructor in comdat if both
2103 // (1) global instrumentation is not TU-specific
2104 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002105 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002106 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2107 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2108 AsanCtorFunction);
2109 if (AsanDtorFunction) {
2110 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2111 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2112 AsanDtorFunction);
2113 }
2114 } else {
2115 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2116 if (AsanDtorFunction)
2117 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002118 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002119
2120 return Changed;
2121}
2122
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002123void AddressSanitizer::initializeCallbacks(Module &M) {
2124 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002125 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002126 // IsWrite, TypeSize and Exp are encoded in the function name.
2127 for (int Exp = 0; Exp < 2; Exp++) {
2128 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2129 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2130 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002131 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002132 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002133
2134 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2135 SmallVector<Type *, 2> Args1{1, IntptrTy};
2136 if (Exp) {
2137 Type *ExpType = Type::getInt32Ty(*C);
2138 Args2.push_back(ExpType);
2139 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002140 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002141 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2142 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2143 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2144 EndingStr,
2145 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002146
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002147 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2148 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2149 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2150 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002151
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002152 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2153 AccessSizeIndex++) {
2154 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2155 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2156 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2157 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2158 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002159
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002160 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2161 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2162 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2163 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2164 }
2165 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002166 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002167
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002168 const std::string MemIntrinCallbackPrefix =
2169 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002170 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002171 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002172 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002173 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002174 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002175 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002176 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002177 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002178 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002179
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002180 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002181 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002182
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002183 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002184 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002185 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002186 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002187 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2188 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2189 StringRef(""), StringRef(""),
2190 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002191}
2192
2193// virtual
2194bool AddressSanitizer::doInitialization(Module &M) {
2195 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002196 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002197
2198 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002199 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002200 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002201 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002202
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002203 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002204 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002205}
2206
Keno Fischere03fae42015-12-05 14:42:34 +00002207bool AddressSanitizer::doFinalization(Module &M) {
2208 GlobalsMD.reset();
2209 return false;
2210}
2211
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002212bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2213 // For each NSObject descendant having a +load method, this method is invoked
2214 // by the ObjC runtime before any of the static constructors is called.
2215 // Therefore we need to instrument such methods with a call to __asan_init
2216 // at the beginning in order to initialize our runtime before any access to
2217 // the shadow memory.
2218 // We cannot just ignore these methods, because they may call other
2219 // instrumented functions.
2220 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002221 Function *AsanInitFunction =
2222 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002223 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002224 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002225 return true;
2226 }
2227 return false;
2228}
2229
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002230void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2231 // Generate code only when dynamic addressing is needed.
2232 if (Mapping.Offset != kDynamicShadowSentinel)
2233 return;
2234
2235 IRBuilder<> IRB(&F.front().front());
2236 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2237 kAsanShadowMemoryDynamicAddress, IntptrTy);
2238 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2239}
2240
Reid Kleckner2f907552015-07-21 17:40:14 +00002241void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2242 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2243 // to it as uninteresting. This assumes we haven't started processing allocas
2244 // yet. This check is done up front because iterating the use list in
2245 // isInterestingAlloca would be algorithmically slower.
2246 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2247
2248 // Try to get the declaration of llvm.localescape. If it's not in the module,
2249 // we can exit early.
2250 if (!F.getParent()->getFunction("llvm.localescape")) return;
2251
2252 // Look for a call to llvm.localescape call in the entry block. It can't be in
2253 // any other block.
2254 for (Instruction &I : F.getEntryBlock()) {
2255 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2256 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2257 // We found a call. Mark all the allocas passed in as uninteresting.
2258 for (Value *Arg : II->arg_operands()) {
2259 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2260 assert(AI && AI->isStaticAlloca() &&
2261 "non-static alloca arg to localescape");
2262 ProcessedAllocas[AI] = false;
2263 }
2264 break;
2265 }
2266 }
2267}
2268
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002269bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002270 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002271 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002272 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002273
Etienne Bergeron78582b22016-09-15 15:45:05 +00002274 bool FunctionModified = false;
2275
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002276 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002277 // This function needs to be called even if the function body is not
2278 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002279 if (maybeInsertAsanInitAtFunctionEntry(F))
2280 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002281
2282 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002283 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002284
Etienne Bergeron752f8832016-09-14 17:18:37 +00002285 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2286
2287 initializeCallbacks(*F.getParent());
2288 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002289
Reid Kleckner2f907552015-07-21 17:40:14 +00002290 FunctionStateRAII CleanupObj(this);
2291
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002292 maybeInsertDynamicShadowAtFunctionEntry(F);
2293
Reid Kleckner2f907552015-07-21 17:40:14 +00002294 // We can't instrument allocas used with llvm.localescape. Only static allocas
2295 // can be passed to that intrinsic.
2296 markEscapedLocalAllocas(F);
2297
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002298 // We want to instrument every address only once per basic block (unless there
2299 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002300 SmallSet<Value *, 16> TempsToInstrument;
2301 SmallVector<Instruction *, 16> ToInstrument;
2302 SmallVector<Instruction *, 8> NoReturnCalls;
2303 SmallVector<BasicBlock *, 16> AllBlocks;
2304 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002305 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002306 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002307 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002308 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002309 const TargetLibraryInfo *TLI =
2310 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002311
2312 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002313 for (auto &BB : F) {
2314 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002315 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002316 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002317 for (auto &Inst : BB) {
2318 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002319 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002320 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002321 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002322 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002323 // If we have a mask, skip instrumentation if we've already
2324 // instrumented the full object. But don't add to TempsToInstrument
2325 // because we might get another load/store with a different mask.
2326 if (MaybeMask) {
2327 if (TempsToInstrument.count(Addr))
2328 continue; // We've seen this (whole) temp in the current BB.
2329 } else {
2330 if (!TempsToInstrument.insert(Addr).second)
2331 continue; // We've seen this temp in the current BB.
2332 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002333 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002334 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002335 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2336 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002337 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002338 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002339 // ok, take it.
2340 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002341 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002342 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002343 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002344 // A call inside BB.
2345 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002346 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002347 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002348 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2349 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002350 continue;
2351 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002352 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002353 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002354 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002355 }
2356 }
2357
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002358 bool UseCalls =
2359 CompileKernel ||
2360 (ClInstrumentationWithCallsThreshold >= 0 &&
2361 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002362 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002363 ObjectSizeOpts ObjSizeOpts;
2364 ObjSizeOpts.RoundToAlign = true;
2365 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002366
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002367 // Instrument.
2368 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002369 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002370 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2371 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002372 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002373 instrumentMop(ObjSizeVis, Inst, UseCalls,
2374 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002375 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002376 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002377 }
2378 NumInstrumented++;
2379 }
2380
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002381 FunctionStackPoisoner FSP(F, *this);
2382 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002383
2384 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2385 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002386 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002387 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002388 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002389 }
2390
Alexey Samsonova02e6642014-05-29 18:40:48 +00002391 for (auto Inst : PointerComparisonsOrSubtracts) {
2392 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002393 NumInstrumented++;
2394 }
2395
Etienne Bergeron78582b22016-09-15 15:45:05 +00002396 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2397 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002398
Etienne Bergeron78582b22016-09-15 15:45:05 +00002399 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2400 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002401
Etienne Bergeron78582b22016-09-15 15:45:05 +00002402 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002403}
2404
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002405// Workaround for bug 11395: we don't want to instrument stack in functions
2406// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2407// FIXME: remove once the bug 11395 is fixed.
2408bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2409 if (LongSize != 32) return false;
2410 CallInst *CI = dyn_cast<CallInst>(I);
2411 if (!CI || !CI->isInlineAsm()) return false;
2412 if (CI->getNumArgOperands() <= 5) return false;
2413 // We have inline assembly with quite a few arguments.
2414 return true;
2415}
2416
2417void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2418 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002419 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2420 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002421 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2422 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002423 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002424 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002425 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002426 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002427 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002428 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002429 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2430 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002431 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002432 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2433 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002434 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002435 }
2436
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002437 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2438 std::ostringstream Name;
2439 Name << kAsanSetShadowPrefix;
2440 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002441 AsanSetShadowFunc[Val] =
2442 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002443 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002444 }
2445
Yury Gribov98b18592015-05-28 07:51:49 +00002446 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002447 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002448 AsanAllocasUnpoisonFunc =
2449 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002450 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002451}
2452
Vitaly Buka793913c2016-08-29 18:17:21 +00002453void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2454 ArrayRef<uint8_t> ShadowBytes,
2455 size_t Begin, size_t End,
2456 IRBuilder<> &IRB,
2457 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002458 if (Begin >= End)
2459 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002460
2461 const size_t LargestStoreSizeInBytes =
2462 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2463
2464 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2465
2466 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002467 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2468 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2469 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002470 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002471 if (!ShadowMask[i]) {
2472 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002473 ++i;
2474 continue;
2475 }
2476
2477 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2478 // Fit store size into the range.
2479 while (StoreSizeInBytes > End - i)
2480 StoreSizeInBytes /= 2;
2481
2482 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002483 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002484 while (j <= StoreSizeInBytes / 2)
2485 StoreSizeInBytes /= 2;
2486 }
2487
2488 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002489 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2490 if (IsLittleEndian)
2491 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2492 else
2493 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002494 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002495
2496 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2497 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002498 IRB.CreateAlignedStore(
2499 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002500
2501 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002502 }
2503}
2504
Vitaly Buka793913c2016-08-29 18:17:21 +00002505void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2506 ArrayRef<uint8_t> ShadowBytes,
2507 IRBuilder<> &IRB, Value *ShadowBase) {
2508 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2509}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002510
Vitaly Buka793913c2016-08-29 18:17:21 +00002511void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2512 ArrayRef<uint8_t> ShadowBytes,
2513 size_t Begin, size_t End,
2514 IRBuilder<> &IRB, Value *ShadowBase) {
2515 assert(ShadowMask.size() == ShadowBytes.size());
2516 size_t Done = Begin;
2517 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2518 if (!ShadowMask[i]) {
2519 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002520 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002521 }
2522 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002523 if (!AsanSetShadowFunc[Val])
2524 continue;
2525
2526 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002527 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002528 }
2529
2530 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002531 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002532 IRB.CreateCall(AsanSetShadowFunc[Val],
2533 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2534 ConstantInt::get(IntptrTy, j - i)});
2535 Done = j;
2536 }
2537 }
2538
Vitaly Buka793913c2016-08-29 18:17:21 +00002539 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002540}
2541
Kostya Serebryany6805de52013-09-10 13:16:56 +00002542// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2543// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2544static int StackMallocSizeClass(uint64_t LocalStackSize) {
2545 assert(LocalStackSize <= kMaxStackMallocSize);
2546 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002547 for (int i = 0;; i++, MaxSize *= 2)
2548 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002549 llvm_unreachable("impossible LocalStackSize");
2550}
2551
Vitaly Buka74443f02017-07-18 22:28:03 +00002552void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002553 Instruction *CopyInsertPoint = &F.front().front();
2554 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2555 // Insert after the dynamic shadow location is determined
2556 CopyInsertPoint = CopyInsertPoint->getNextNode();
2557 assert(CopyInsertPoint);
2558 }
2559 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002560 const DataLayout &DL = F.getParent()->getDataLayout();
2561 for (Argument &Arg : F.args()) {
2562 if (Arg.hasByValAttr()) {
2563 Type *Ty = Arg.getType()->getPointerElementType();
2564 unsigned Align = Arg.getParamAlignment();
2565 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2566
2567 const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2568 "Arg" + llvm::to_string(Arg.getArgNo());
2569 AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2570 AI->setAlignment(Align);
2571 Arg.replaceAllUsesWith(AI);
2572
2573 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2574 IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2575 }
2576 }
2577}
2578
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002579PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2580 Value *ValueIfTrue,
2581 Instruction *ThenTerm,
2582 Value *ValueIfFalse) {
2583 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2584 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2585 PHI->addIncoming(ValueIfFalse, CondBlock);
2586 BasicBlock *ThenBlock = ThenTerm->getParent();
2587 PHI->addIncoming(ValueIfTrue, ThenBlock);
2588 return PHI;
2589}
2590
2591Value *FunctionStackPoisoner::createAllocaForLayout(
2592 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2593 AllocaInst *Alloca;
2594 if (Dynamic) {
2595 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2596 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2597 "MyAlloca");
2598 } else {
2599 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2600 nullptr, "MyAlloca");
2601 assert(Alloca->isStaticAlloca());
2602 }
2603 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2604 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2605 Alloca->setAlignment(FrameAlignment);
2606 return IRB.CreatePointerCast(Alloca, IntptrTy);
2607}
2608
Yury Gribov98b18592015-05-28 07:51:49 +00002609void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2610 BasicBlock &FirstBB = *F.begin();
2611 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2612 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2613 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2614 DynamicAllocaLayout->setAlignment(32);
2615}
2616
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002617void FunctionStackPoisoner::processDynamicAllocas() {
2618 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2619 assert(DynamicAllocaPoisonCallVec.empty());
2620 return;
2621 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002622
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002623 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2624 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002625 assert(APC.InsBefore);
2626 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002627 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002628 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002629
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002630 IRBuilder<> IRB(APC.InsBefore);
2631 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002632 // Dynamic allocas will be unpoisoned unconditionally below in
2633 // unpoisonDynamicAllocas.
2634 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002635 }
2636
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002637 // Handle dynamic allocas.
2638 createDynamicAllocasInitStorage();
2639 for (auto &AI : DynamicAllocaVec)
2640 handleDynamicAllocaCall(AI);
2641 unpoisonDynamicAllocas();
2642}
Yury Gribov98b18592015-05-28 07:51:49 +00002643
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002644void FunctionStackPoisoner::processStaticAllocas() {
2645 if (AllocaVec.empty()) {
2646 assert(StaticAllocaPoisonCallVec.empty());
2647 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002648 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002649
Kostya Serebryany6805de52013-09-10 13:16:56 +00002650 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002651 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002652 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002653 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002654
2655 Instruction *InsBefore = AllocaVec[0];
2656 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002657 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002658
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002659 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2660 // debug info is broken, because only entry-block allocas are treated as
2661 // regular stack slots.
2662 auto InsBeforeB = InsBefore->getParent();
2663 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002664 for (auto *AI : StaticAllocasToMoveUp)
2665 if (AI->getParent() == InsBeforeB)
2666 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002667
Reid Kleckner2f907552015-07-21 17:40:14 +00002668 // If we have a call to llvm.localescape, keep it in the entry block.
2669 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2670
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002671 SmallVector<ASanStackVariableDescription, 16> SVD;
2672 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002673 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002674 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002675 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002676 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002677 AI->getAlignment(),
2678 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002679 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002680 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002681 SVD.push_back(D);
2682 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002683
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002684 // Minimal header size (left redzone) is 4 pointers,
2685 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2686 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002687 const ASanStackFrameLayout &L =
2688 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002689
Vitaly Buka5910a922016-10-18 23:29:52 +00002690 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2691 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2692 for (auto &Desc : SVD)
2693 AllocaToSVDMap[Desc.AI] = &Desc;
2694
2695 // Update SVD with information from lifetime intrinsics.
2696 for (const auto &APC : StaticAllocaPoisonCallVec) {
2697 assert(APC.InsBefore);
2698 assert(APC.AI);
2699 assert(ASan.isInterestingAlloca(*APC.AI));
2700 assert(APC.AI->isStaticAlloca());
2701
2702 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2703 Desc.LifetimeSize = Desc.Size;
2704 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2705 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2706 if (LifetimeLoc->getFile() == FnLoc->getFile())
2707 if (unsigned Line = LifetimeLoc->getLine())
2708 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2709 }
2710 }
2711 }
2712
2713 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2714 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002715 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002716 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2717 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002718 bool DoDynamicAlloca = ClDynamicAllocaStack;
2719 // Don't do dynamic alloca or stack malloc if:
2720 // 1) There is inline asm: too often it makes assumptions on which registers
2721 // are available.
2722 // 2) There is a returns_twice call (typically setjmp), which is
2723 // optimization-hostile, and doesn't play well with introduced indirect
2724 // register-relative calculation of local variable addresses.
2725 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2726 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002727
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002728 Value *StaticAlloca =
2729 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2730
2731 Value *FakeStack;
2732 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002733
2734 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002735 // void *FakeStack = __asan_option_detect_stack_use_after_return
2736 // ? __asan_stack_malloc_N(LocalStackSize)
2737 // : nullptr;
2738 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002739 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2740 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2741 Value *UseAfterReturnIsEnabled =
2742 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002743 Constant::getNullValue(IRB.getInt32Ty()));
2744 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002745 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002746 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002747 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002748 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2749 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2750 Value *FakeStackValue =
2751 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2752 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002753 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002754 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002755 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002756 ConstantInt::get(IntptrTy, 0));
2757
2758 Value *NoFakeStack =
2759 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2760 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2761 IRBIf.SetInsertPoint(Term);
2762 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2763 Value *AllocaValue =
2764 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2765 IRB.SetInsertPoint(InsBefore);
2766 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2767 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2768 } else {
2769 // void *FakeStack = nullptr;
2770 // void *LocalStackBase = alloca(LocalStackSize);
2771 FakeStack = ConstantInt::get(IntptrTy, 0);
2772 LocalStackBase =
2773 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002774 }
2775
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002776 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002777 for (const auto &Desc : SVD) {
2778 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002779 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002780 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002781 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002782 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002783 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002784 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002785
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002786 // The left-most redzone has enough space for at least 4 pointers.
2787 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002788 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2789 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2790 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002791 // Write the frame description constant to redzone[1].
2792 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002793 IRB.CreateAdd(LocalStackBase,
2794 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2795 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002796 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002797 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002798 /*AllowMerging*/ true);
2799 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002800 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002801 // Write the PC to redzone[2].
2802 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002803 IRB.CreateAdd(LocalStackBase,
2804 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2805 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002806 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002807
Vitaly Buka793913c2016-08-29 18:17:21 +00002808 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2809
2810 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002811 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002812 // As mask we must use most poisoned case: red zones and after scope.
2813 // As bytes we can use either the same or just red zones only.
2814 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2815
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002816 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002817 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2818
2819 // Poison static allocas near lifetime intrinsics.
2820 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002821 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002822 assert(Desc.Offset % L.Granularity == 0);
2823 size_t Begin = Desc.Offset / L.Granularity;
2824 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2825
2826 IRBuilder<> IRB(APC.InsBefore);
2827 copyToShadow(ShadowAfterScope,
2828 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2829 IRB, ShadowBase);
2830 }
2831 }
2832
2833 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002834 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002835
Kostya Serebryany530e2072013-12-23 14:15:08 +00002836 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002837 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002838 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002839 // Mark the current frame as retired.
2840 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2841 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002842 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002843 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002844 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002845 // // In use-after-return mode, poison the whole stack frame.
2846 // if StackMallocIdx <= 4
2847 // // For small sizes inline the whole thing:
2848 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002849 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002850 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002851 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002852 // else
2853 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002854 Value *Cmp =
2855 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002856 TerminatorInst *ThenTerm, *ElseTerm;
2857 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2858
2859 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002860 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002861 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002862 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2863 kAsanStackUseAfterReturnMagic);
2864 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2865 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002866 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002867 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002868 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2869 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2870 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2871 IRBPoison.CreateStore(
2872 Constant::getNullValue(IRBPoison.getInt8Ty()),
2873 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2874 } else {
2875 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002876 IRBPoison.CreateCall(
2877 AsanStackFreeFunc[StackMallocIdx],
2878 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002879 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002880
2881 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002882 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002883 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002884 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002885 }
2886 }
2887
Kostya Serebryany09959942012-10-19 06:20:53 +00002888 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002889 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002890}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002891
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002892void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002893 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002894 // For now just insert the call to ASan runtime.
2895 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2896 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002897 IRB.CreateCall(
2898 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2899 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002900}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002901
2902// Handling llvm.lifetime intrinsics for a given %alloca:
2903// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2904// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2905// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2906// could be poisoned by previous llvm.lifetime.end instruction, as the
2907// variable may go in and out of scope several times, e.g. in loops).
2908// (3) if we poisoned at least one %alloca in a function,
2909// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002910
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002911AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2912 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002913 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002914 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002915 // See if we've already calculated (or started to calculate) alloca for a
2916 // given value.
2917 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002918 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002919 // Store 0 while we're calculating alloca for value V to avoid
2920 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002921 AllocaForValue[V] = nullptr;
2922 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002923 if (CastInst *CI = dyn_cast<CastInst>(V))
2924 Res = findAllocaForValue(CI->getOperand(0));
2925 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002926 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002927 // Allow self-referencing phi-nodes.
2928 if (IncValue == PN) continue;
2929 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2930 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002931 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2932 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002933 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002934 }
Vitaly Buka53054a72016-07-22 00:56:17 +00002935 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2936 Res = findAllocaForValue(EP->getPointerOperand());
2937 } else {
2938 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002939 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002940 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002941 return Res;
2942}
Yury Gribov55441bb2014-11-21 10:29:50 +00002943
Yury Gribov98b18592015-05-28 07:51:49 +00002944void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002945 IRBuilder<> IRB(AI);
2946
Yury Gribov55441bb2014-11-21 10:29:50 +00002947 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2948 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2949
2950 Value *Zero = Constant::getNullValue(IntptrTy);
2951 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2952 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002953
2954 // Since we need to extend alloca with additional memory to locate
2955 // redzones, and OldSize is number of allocated blocks with
2956 // ElementSize size, get allocated memory size in bytes by
2957 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002958 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002959 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002960 Value *OldSize =
2961 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2962 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002963
2964 // PartialSize = OldSize % 32
2965 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2966
2967 // Misalign = kAllocaRzSize - PartialSize;
2968 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2969
2970 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2971 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2972 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2973
2974 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2975 // Align is added to locate left redzone, PartialPadding for possible
2976 // partial redzone and kAllocaRzSize for right redzone respectively.
2977 Value *AdditionalChunkSize = IRB.CreateAdd(
2978 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2979
2980 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2981
2982 // Insert new alloca with new NewSize and Align params.
2983 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2984 NewAlloca->setAlignment(Align);
2985
2986 // NewAddress = Address + Align
2987 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2988 ConstantInt::get(IntptrTy, Align));
2989
Yury Gribov98b18592015-05-28 07:51:49 +00002990 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002991 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002992
2993 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2994 // for unpoisoning stuff.
2995 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2996
Yury Gribov55441bb2014-11-21 10:29:50 +00002997 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2998
Yury Gribov98b18592015-05-28 07:51:49 +00002999 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003000 AI->replaceAllUsesWith(NewAddressPtr);
3001
Yury Gribov98b18592015-05-28 07:51:49 +00003002 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003003 AI->eraseFromParent();
3004}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003005
3006// isSafeAccess returns true if Addr is always inbounds with respect to its
3007// base object. For example, it is a field access or an array access with
3008// constant inbounds index.
3009bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3010 Value *Addr, uint64_t TypeSize) const {
3011 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3012 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003013 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003014 int64_t Offset = SizeOffset.second.getSExtValue();
3015 // Three checks are required to ensure safety:
3016 // . Offset >= 0 (since the offset is given from the base ptr)
3017 // . Size >= Offset (unsigned)
3018 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003019 return Offset >= 0 && Size >= uint64_t(Offset) &&
3020 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003021}