blob: 7dcab7a49650f397ae35f3d80216dc707e5218a7 [file] [log] [blame]
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001//===- AddressSanitizer.cpp - memory error detector -----------------------===//
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file is a part of AddressSanitizer, an address sanity checker.
10// Details of the algorithm:
Hans Wennborg08b34a02017-11-13 23:47:58 +000011// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000012//
13//===----------------------------------------------------------------------===//
14
Leonard Chan436fb2b2019-02-13 22:22:48 +000015#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
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"
Florian Hahna1cc8482018-06-12 11:16:56 +000019#include "llvm/ADT/SmallPtrSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000021#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/ADT/StringRef.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"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000029#include "llvm/BinaryFormat/MachO.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000030#include "llvm/IR/Argument.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000031#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000034#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000037#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000039#include "llvm/IR/DebugInfoMetadata.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/DerivedTypes.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000042#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000044#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000049#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000056#include "llvm/IR/MDBuilder.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000057#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Module.h"
59#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000060#include "llvm/IR/Use.h"
61#include "llvm/IR/Value.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000062#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000063#include "llvm/Pass.h"
64#include "llvm/Support/Casting.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065#include "llvm/Support/CommandLine.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000067#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/MathExtras.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000069#include "llvm/Support/ScopedPrinter.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000070#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000072#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000073#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Leonard Chan436fb2b2019-02-13 22:22:48 +000074#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000075#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000076#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000078#include <cassert>
79#include <cstddef>
80#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000081#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000082#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000083#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000084#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000086#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
88using namespace llvm;
89
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "asan"
91
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const uint64_t kDefaultShadowScale = 3;
93static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
Walter Lee8f1545c2017-11-16 17:03:00 +000097static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
98static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000099static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Bill Seurer957a0762017-12-07 22:53:33 +0000100static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000101static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000102static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000103static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000104static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000105static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
106static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000107static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000108static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000109static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000110static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000111static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Guanzhong Chen9aad9972019-06-26 20:16:14 +0000112static const uint64_t kEmscriptenShadowOffset = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000113
Walter Leecdbb2072018-05-18 04:10:38 +0000114static const uint64_t kMyriadShadowScale = 5;
115static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
116static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
117static const uint64_t kMyriadTagShift = 29;
118static const uint64_t kMyriadDDRTag = 4;
119static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
120
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000121// The shadow memory space is dynamically allocated.
122static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000123
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000124static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125static const size_t kMaxStackMallocSize = 1 << 16; // 64K
126static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
127static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
128
Craig Topperd3a34f82013-07-16 01:17:10 +0000129static const char *const kAsanModuleCtorName = "asan.module_ctor";
130static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000131static const uint64_t kAsanCtorAndDtorPriority = 1;
Guanzhong Chenb3292a82019-08-06 21:52:58 +0000132// On Emscripten, the system needs more than one priorities for constructors.
133static const uint64_t kAsanEmscriptenCtorAndDtorPriority = 50;
Craig Topperd3a34f82013-07-16 01:17:10 +0000134static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000135static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000136static const char *const kAsanUnregisterGlobalsName =
137 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000138static const char *const kAsanRegisterImageGlobalsName =
139 "__asan_register_image_globals";
140static const char *const kAsanUnregisterImageGlobalsName =
141 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000142static const char *const kAsanRegisterElfGlobalsName =
143 "__asan_register_elf_globals";
144static const char *const kAsanUnregisterElfGlobalsName =
145 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000146static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
147static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000148static const char *const kAsanInitName = "__asan_init";
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000149static const char *const kAsanVersionCheckNamePrefix =
150 "__asan_version_mismatch_check_v";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000151static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
152static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000153static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000154static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000155static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
156static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Peter Collingbourne4a653fa2018-07-18 22:23:14 +0000157static const char *const kAsanGenPrefix = "___asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000158static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000159static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000160static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000161static const char *const kAsanPoisonStackMemoryName =
162 "__asan_poison_stack_memory";
163static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000164 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000165
166// ASan version script has __asan_* wildcard. Triple underscore prevents a
167// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000168static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000169 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000170
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000171static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000172 "__asan_option_detect_stack_use_after_return";
173
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000174static const char *const kAsanShadowMemoryDynamicAddress =
175 "__asan_shadow_memory_dynamic_address";
176
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000177static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
178static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000179
Kostya Serebryany874dae62012-07-16 16:15:40 +0000180// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
181static const size_t kNumberOfAccessSizes = 5;
182
Yury Gribov55441bb2014-11-21 10:29:50 +0000183static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000184
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185// Command-line flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000186
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000187static cl::opt<bool> ClEnableKasan(
188 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
189 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000190
Yury Gribovd7731982015-11-11 10:36:49 +0000191static cl::opt<bool> ClRecover(
192 "asan-recover",
193 cl::desc("Enable recovery mode (continue-after-error)."),
194 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000195
Julian Lettner3ae9b9d2019-08-28 20:40:55 +0000196static cl::opt<bool> ClInsertVersionCheck(
197 "asan-guard-against-version-mismatch",
198 cl::desc("Guard against compiler/runtime version mismatch."),
199 cl::Hidden, cl::init(true));
200
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000201// This flag may need to be replaced with -f[no-]asan-reads.
202static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203 cl::desc("instrument read instructions"),
204 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000205
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000206static cl::opt<bool> ClInstrumentWrites(
207 "asan-instrument-writes", cl::desc("instrument write instructions"),
208 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000209
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000210static cl::opt<bool> ClInstrumentAtomics(
211 "asan-instrument-atomics",
212 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
213 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000214
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000215static cl::opt<bool> ClAlwaysSlowPath(
216 "asan-always-slow-path",
217 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
218 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000219
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000220static cl::opt<bool> ClForceDynamicShadow(
221 "asan-force-dynamic-shadow",
222 cl::desc("Load shadow address into a local variable for each function"),
223 cl::Hidden, cl::init(false));
224
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000225static cl::opt<bool>
226 ClWithIfunc("asan-with-ifunc",
227 cl::desc("Access dynamic shadow through an ifunc global on "
228 "platforms that support this"),
229 cl::Hidden, cl::init(true));
230
231static cl::opt<bool> ClWithIfuncSuppressRemat(
232 "asan-with-ifunc-suppress-remat",
233 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
234 "it through inline asm in prologue."),
235 cl::Hidden, cl::init(true));
236
Kostya Serebryany874dae62012-07-16 16:15:40 +0000237// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000238// in any given BB. Normally, this should be set to unlimited (INT_MAX),
239// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
240// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000241static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
242 "asan-max-ins-per-bb", cl::init(10000),
243 cl::desc("maximal number of instructions to instrument in any given BB"),
244 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000245
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000246// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000247static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
248 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000249static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
250 "asan-max-inline-poisoning-size",
251 cl::desc(
252 "Inline shadow poisoning for blocks up to the given size in bytes."),
253 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000254
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000255static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000256 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000257 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000258
Vitaly Buka74443f02017-07-18 22:28:03 +0000259static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
260 cl::desc("Create redzones for byval "
261 "arguments (extra copy "
262 "required)"), cl::Hidden,
263 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000264
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000265static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
266 cl::desc("Check stack-use-after-scope"),
267 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000268
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000269// This flag may need to be replaced with -f[no]asan-globals.
270static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000271 cl::desc("Handle global objects"), cl::Hidden,
272 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000273
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000274static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000275 cl::desc("Handle C++ initializer order"),
276 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000277
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000278static cl::opt<bool> ClInvalidPointerPairs(
279 "asan-detect-invalid-pointer-pair",
280 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
281 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000282
Pierre Gousseaua833c2b2019-03-28 10:51:24 +0000283static cl::opt<bool> ClInvalidPointerCmp(
284 "asan-detect-invalid-pointer-cmp",
285 cl::desc("Instrument <, <=, >, >= with pointer operands"), cl::Hidden,
286 cl::init(false));
287
288static cl::opt<bool> ClInvalidPointerSub(
289 "asan-detect-invalid-pointer-sub",
290 cl::desc("Instrument - operations with pointer operands"), cl::Hidden,
291 cl::init(false));
292
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293static cl::opt<unsigned> ClRealignStack(
294 "asan-realign-stack",
295 cl::desc("Realign stack to the value of this flag (power of two)"),
296 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000297
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000298static cl::opt<int> ClInstrumentationWithCallsThreshold(
299 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300 cl::desc(
301 "If the function being instrumented contains more than "
302 "this number of memory accesses, use callbacks instead of "
303 "inline checks (-1 means never use callbacks)."),
304 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000305
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000306static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000307 "asan-memory-access-callback-prefix",
308 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
309 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000310
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000311static cl::opt<bool>
312 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
313 cl::desc("instrument dynamic allocas"),
314 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000315
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000316static cl::opt<bool> ClSkipPromotableAllocas(
317 "asan-skip-promotable-allocas",
318 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
319 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000320
321// These flags allow to change the shadow mapping.
322// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000323// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000324
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000325static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000326 cl::desc("scale of asan shadow mapping"),
327 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000328
Fangrui Songb5f39842019-04-24 02:40:20 +0000329static cl::opt<uint64_t>
330 ClMappingOffset("asan-mapping-offset",
331 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"),
332 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000333
334// Optimization flags. Not user visible, used mostly for testing
335// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000336
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000337static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
338 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000339
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000340static cl::opt<bool> ClOptSameTemp(
341 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
342 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000343
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000344static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000345 cl::desc("Don't instrument scalar globals"),
346 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000347
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000348static cl::opt<bool> ClOptStack(
349 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
350 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000351
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000352static cl::opt<bool> ClDynamicAllocaStack(
353 "asan-stack-dynamic-alloca",
354 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000355 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000356
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000357static cl::opt<uint32_t> ClForceExperiment(
358 "asan-force-experiment",
359 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
360 cl::init(0));
361
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000362static cl::opt<bool>
Vitaly Bukad6bab092018-12-04 23:17:41 +0000363 ClUsePrivateAlias("asan-use-private-alias",
364 cl::desc("Use private aliases for global variables"),
365 cl::Hidden, cl::init(false));
366
367static cl::opt<bool>
368 ClUseOdrIndicator("asan-use-odr-indicator",
369 cl::desc("Use odr indicators to improve ODR reporting"),
370 cl::Hidden, cl::init(false));
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000371
Ryan Govostese51401b2016-07-05 21:53:08 +0000372static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000373 ClUseGlobalsGC("asan-globals-live-support",
374 cl::desc("Use linker features to support dead "
375 "code stripping of globals"),
376 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000377
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000378// This is on by default even though there is a bug in gold:
379// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
380static cl::opt<bool>
381 ClWithComdat("asan-with-comdat",
382 cl::desc("Place ASan constructors in comdat sections"),
383 cl::Hidden, cl::init(true));
384
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000386
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000387static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
388 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000389
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
391 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000392
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000393static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
394 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000395
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000396static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
397 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000398
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000399static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000400 cl::Hidden, cl::init(-1));
401
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000402STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
403STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000404STATISTIC(NumOptimizedAccessesToGlobalVar,
405 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000406STATISTIC(NumOptimizedAccessesToStackVar,
407 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000408
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000409namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000410
Alexey Samsonov1345d352013-01-16 13:23:28 +0000411/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000412/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000413/// If InGlobal is true, then
414/// extern char __asan_shadow[];
415/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000416struct ShadowMapping {
417 int Scale;
418 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000419 bool OrShadowOffset;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000420 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000421};
422
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000423} // end anonymous namespace
424
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000425static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
426 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000427 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000428 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000429 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000430 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000431 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000432 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000433 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
434 TargetTriple.getArch() == Triple::ppc64le;
435 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000436 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000437 bool IsMIPS32 = TargetTriple.isMIPS32();
438 bool IsMIPS64 = TargetTriple.isMIPS64();
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000439 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000440 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000441 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000442 bool IsFuchsia = TargetTriple.isOSFuchsia();
Walter Leecdbb2072018-05-18 04:10:38 +0000443 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
Guanzhong Chen9aad9972019-06-26 20:16:14 +0000444 bool IsEmscripten = TargetTriple.isOSEmscripten();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000445
446 ShadowMapping Mapping;
447
Walter Leecdbb2072018-05-18 04:10:38 +0000448 Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
Walter Lee8f1545c2017-11-16 17:03:00 +0000449 if (ClMappingScale.getNumOccurrences() > 0) {
450 Mapping.Scale = ClMappingScale;
451 }
452
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000453 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000454 if (IsAndroid)
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000455 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000456 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000457 Mapping.Offset = kMIPS32_ShadowOffset32;
458 else if (IsFreeBSD)
459 Mapping.Offset = kFreeBSD_ShadowOffset32;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000460 else if (IsNetBSD)
461 Mapping.Offset = kNetBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000462 else if (IsIOS)
Julian Lettner19c4d662019-06-21 21:01:39 +0000463 Mapping.Offset = kDynamicShadowSentinel;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000464 else if (IsWindows)
465 Mapping.Offset = kWindowsShadowOffset32;
Guanzhong Chen9aad9972019-06-26 20:16:14 +0000466 else if (IsEmscripten)
467 Mapping.Offset = kEmscriptenShadowOffset;
Walter Leecdbb2072018-05-18 04:10:38 +0000468 else if (IsMyriad) {
469 uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
470 (kMyriadMemorySize32 >> Mapping.Scale));
471 Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
472 }
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000473 else
474 Mapping.Offset = kDefaultShadowOffset32;
475 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000476 // Fuchsia is always PIE, which means that the beginning of the address
477 // space is always available.
478 if (IsFuchsia)
479 Mapping.Offset = 0;
480 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000481 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000482 else if (IsSystemZ)
483 Mapping.Offset = kSystemZ_ShadowOffset64;
John Baldwinc5d7e042018-08-01 22:51:13 +0000484 else if (IsFreeBSD && !IsMIPS64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000485 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000486 else if (IsNetBSD) {
487 if (IsKasan)
488 Mapping.Offset = kNetBSDKasan_ShadowOffset64;
489 else
490 Mapping.Offset = kNetBSD_ShadowOffset64;
491 } else if (IsPS4CPU)
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000492 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000493 else if (IsLinux && IsX86_64) {
494 if (IsKasan)
495 Mapping.Offset = kLinuxKasan_ShadowOffset64;
496 else
Walter Lee8f1545c2017-11-16 17:03:00 +0000497 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
498 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
Etienne Bergeron70684f92016-06-21 15:07:29 +0000499 } else if (IsWindows && IsX86_64) {
500 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000501 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000502 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000503 else if (IsIOS)
Julian Lettner19c4d662019-06-21 21:01:39 +0000504 Mapping.Offset = kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000505 else if (IsAArch64)
506 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000507 else
508 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000509 }
510
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000511 if (ClForceDynamicShadow) {
512 Mapping.Offset = kDynamicShadowSentinel;
513 }
514
Ryan Govostes3f37df02016-05-06 10:25:22 +0000515 if (ClMappingOffset.getNumOccurrences() > 0) {
516 Mapping.Offset = ClMappingOffset;
517 }
518
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000519 // OR-ing shadow offset if more efficient (at least on x86) if the offset
520 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000521 // offset is not necessary 1/8-th of the address space. On SystemZ,
522 // we could OR the constant in a single instruction, but it's more
523 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000524 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
525 !(Mapping.Offset & (Mapping.Offset - 1)) &&
526 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000527 bool IsAndroidWithIfuncSupport =
528 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
529 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000530
Alexey Samsonov1345d352013-01-16 13:23:28 +0000531 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000532}
533
Alexey Samsonov1345d352013-01-16 13:23:28 +0000534static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000535 // Redzone used for stack and globals is at least 32 bytes.
536 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000537 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000538}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000539
Guanzhong Chenb3292a82019-08-06 21:52:58 +0000540static uint64_t GetCtorAndDtorPriority(Triple &TargetTriple) {
541 if (TargetTriple.isOSEmscripten()) {
542 return kAsanEmscriptenCtorAndDtorPriority;
543 } else {
544 return kAsanCtorAndDtorPriority;
545 }
546}
547
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000548namespace {
549
Leonard Chan436fb2b2019-02-13 22:22:48 +0000550/// Module analysis for getting various metadata about the module.
551class ASanGlobalsMetadataWrapperPass : public ModulePass {
552public:
Leonard Chaneebecb32018-10-26 22:51:51 +0000553 static char ID;
554
Leonard Chan436fb2b2019-02-13 22:22:48 +0000555 ASanGlobalsMetadataWrapperPass() : ModulePass(ID) {
556 initializeASanGlobalsMetadataWrapperPassPass(
557 *PassRegistry::getPassRegistry());
558 }
559
560 bool runOnModule(Module &M) override {
561 GlobalsMD = GlobalsMetadata(M);
562 return false;
Leonard Chaneebecb32018-10-26 22:51:51 +0000563 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000564
Leonard Chaneebecb32018-10-26 22:51:51 +0000565 StringRef getPassName() const override {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000566 return "ASanGlobalsMetadataWrapperPass";
Leonard Chaneebecb32018-10-26 22:51:51 +0000567 }
568
569 void getAnalysisUsage(AnalysisUsage &AU) const override {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000570 AU.setPreservesAll();
571 }
572
573 GlobalsMetadata &getGlobalsMD() { return GlobalsMD; }
574
575private:
576 GlobalsMetadata GlobalsMD;
577};
578
579char ASanGlobalsMetadataWrapperPass::ID = 0;
580
581/// AddressSanitizer: instrument the code in module to find memory bugs.
582struct AddressSanitizer {
583 AddressSanitizer(Module &M, GlobalsMetadata &GlobalsMD,
584 bool CompileKernel = false, bool Recover = false,
585 bool UseAfterScope = false)
586 : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(GlobalsMD) {
587 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
588 this->CompileKernel =
589 ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
590
591 C = &(M.getContext());
592 LongSize = M.getDataLayout().getPointerSizeInBits();
593 IntptrTy = Type::getIntNTy(*C, LongSize);
594 TargetTriple = Triple(M.getTargetTriple());
595
596 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
Yury Gribov3ae427d2014-12-01 08:47:58 +0000597 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000598
Vitaly Buka21a9e572016-07-28 22:50:50 +0000599 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000600 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000601 if (AI.isArrayAllocation()) {
602 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000603 assert(CI && "non-constant array size");
604 ArraySize = CI->getZExtValue();
605 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000606 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000608 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000609 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000610 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000611
Anna Zaks8ed1d812015-02-27 03:12:36 +0000612 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000613 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000614
Anna Zaks8ed1d812015-02-27 03:12:36 +0000615 /// If it is an interesting memory access, return the PointerOperand
616 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000617 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
618 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000619 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000620 uint64_t *TypeSize, unsigned *Alignment,
621 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000622
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000623 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000624 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000625 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000626 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
627 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000628 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000629 void instrumentUnusualSizeOrAlignment(Instruction *I,
630 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000631 uint32_t TypeSize, bool IsWrite,
632 Value *SizeArgument, bool UseCalls,
633 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000634 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
635 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000636 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000637 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000638 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000639 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000640 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000641 bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000642 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000643 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000644 void markEscapedLocalAllocas(Function &F);
Yury Gribov3ae427d2014-12-01 08:47:58 +0000645
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000646private:
647 friend struct FunctionStackPoisoner;
648
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000649 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000650
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000651 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000652 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000653 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
654 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000655
Reid Kleckner2f907552015-07-21 17:40:14 +0000656 /// Helper to cleanup per-function state.
657 struct FunctionStateRAII {
658 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000659
Reid Kleckner2f907552015-07-21 17:40:14 +0000660 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
661 assert(Pass->ProcessedAllocas.empty() &&
662 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000663 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000664 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000665
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000666 ~FunctionStateRAII() {
667 Pass->LocalDynamicShadow = nullptr;
668 Pass->ProcessedAllocas.clear();
669 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000670 };
671
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000672 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000673 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000674 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000675 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000676 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000677 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000678 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000679 ShadowMapping Mapping;
James Y Knight13680222019-02-01 02:28:03 +0000680 FunctionCallee AsanHandleNoReturnFunc;
681 FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000682 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000683
684 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
James Y Knight13680222019-02-01 02:28:03 +0000685 FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
686 FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000687
688 // These arrays is indexed by AccessIsWrite and Experiment.
James Y Knight13680222019-02-01 02:28:03 +0000689 FunctionCallee AsanErrorCallbackSized[2][2];
690 FunctionCallee AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000691
James Y Knight13680222019-02-01 02:28:03 +0000692 FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000693 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000694 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000695 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000696 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000697};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000698
Leonard Chan436fb2b2019-02-13 22:22:48 +0000699class AddressSanitizerLegacyPass : public FunctionPass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000700public:
Leonard Chaneebecb32018-10-26 22:51:51 +0000701 static char ID;
702
Leonard Chan436fb2b2019-02-13 22:22:48 +0000703 explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
704 bool Recover = false,
705 bool UseAfterScope = false)
706 : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
707 UseAfterScope(UseAfterScope) {
708 initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
709 }
710
711 StringRef getPassName() const override {
712 return "AddressSanitizerFunctionPass";
713 }
714
715 void getAnalysisUsage(AnalysisUsage &AU) const override {
716 AU.addRequired<ASanGlobalsMetadataWrapperPass>();
717 AU.addRequired<TargetLibraryInfoWrapperPass>();
718 }
719
720 bool runOnFunction(Function &F) override {
721 GlobalsMetadata &GlobalsMD =
722 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
723 const TargetLibraryInfo *TLI =
724 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
725 AddressSanitizer ASan(*F.getParent(), GlobalsMD, CompileKernel, Recover,
726 UseAfterScope);
727 return ASan.instrumentFunction(F, TLI);
728 }
729
730private:
731 bool CompileKernel;
732 bool Recover;
733 bool UseAfterScope;
734};
735
736class ModuleAddressSanitizer {
737public:
738 ModuleAddressSanitizer(Module &M, GlobalsMetadata &GlobalsMD,
739 bool CompileKernel = false, bool Recover = false,
740 bool UseGlobalsGC = true, bool UseOdrIndicator = false)
741 : GlobalsMD(GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
Vitaly Buka8076c572018-12-05 01:44:31 +0000742 // Enable aliases as they should have no downside with ODR indicators.
743 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
744 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000745 // Not a typo: ClWithComdat is almost completely pointless without
746 // ClUseGlobalsGC (because then it only works on modules without
747 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
748 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
749 // argument is designed as workaround. Therefore, disable both
750 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
751 // do globals-gc.
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000752 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
Vitaly Buka8076c572018-12-05 01:44:31 +0000753 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
754 this->CompileKernel =
755 ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
Leonard Chan436fb2b2019-02-13 22:22:48 +0000756
757 C = &(M.getContext());
758 int LongSize = M.getDataLayout().getPointerSizeInBits();
759 IntptrTy = Type::getIntNTy(*C, LongSize);
760 TargetTriple = Triple(M.getTargetTriple());
761 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
Vitaly Buka537cfc02018-12-04 00:36:14 +0000762 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000763
Leonard Chan436fb2b2019-02-13 22:22:48 +0000764 bool instrumentModule(Module &);
Alexey Samsonov261177a2012-12-04 01:34:23 +0000765
Mehdi Amini117296c2016-10-01 02:56:57 +0000766private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000767 void initializeCallbacks(Module &M);
768
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000769 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000770 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
771 ArrayRef<GlobalVariable *> ExtendedGlobals,
772 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000773 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
774 ArrayRef<GlobalVariable *> ExtendedGlobals,
775 ArrayRef<Constant *> MetadataInitializers,
776 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000777 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
778 ArrayRef<GlobalVariable *> ExtendedGlobals,
779 ArrayRef<Constant *> MetadataInitializers);
780 void
781 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
782 ArrayRef<GlobalVariable *> ExtendedGlobals,
783 ArrayRef<Constant *> MetadataInitializers);
784
785 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
786 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000787 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
788 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000789 IRBuilder<> CreateAsanModuleDtor(Module &M);
790
Kostya Serebryany20a79972012-11-22 03:18:50 +0000791 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000792 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000793 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000794 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000795 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000796 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000797 return RedzoneSizeForScale(Mapping.Scale);
798 }
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000799 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000800
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000801 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000802 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000803 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000804 bool UseGlobalsGC;
Vitaly Buka8076c572018-12-05 01:44:31 +0000805 bool UsePrivateAlias;
806 bool UseOdrIndicator;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000807 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000808 Type *IntptrTy;
809 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000810 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000811 ShadowMapping Mapping;
James Y Knight13680222019-02-01 02:28:03 +0000812 FunctionCallee AsanPoisonGlobals;
813 FunctionCallee AsanUnpoisonGlobals;
814 FunctionCallee AsanRegisterGlobals;
815 FunctionCallee AsanUnregisterGlobals;
816 FunctionCallee AsanRegisterImageGlobals;
817 FunctionCallee AsanUnregisterImageGlobals;
818 FunctionCallee AsanRegisterElfGlobals;
819 FunctionCallee AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000820
821 Function *AsanCtorFunction = nullptr;
822 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000823};
824
Leonard Chan436fb2b2019-02-13 22:22:48 +0000825class ModuleAddressSanitizerLegacyPass : public ModulePass {
826public:
827 static char ID;
828
829 explicit ModuleAddressSanitizerLegacyPass(bool CompileKernel = false,
830 bool Recover = false,
831 bool UseGlobalGC = true,
832 bool UseOdrIndicator = false)
833 : ModulePass(ID), CompileKernel(CompileKernel), Recover(Recover),
834 UseGlobalGC(UseGlobalGC), UseOdrIndicator(UseOdrIndicator) {
835 initializeModuleAddressSanitizerLegacyPassPass(
836 *PassRegistry::getPassRegistry());
837 }
838
839 StringRef getPassName() const override { return "ModuleAddressSanitizer"; }
840
841 void getAnalysisUsage(AnalysisUsage &AU) const override {
842 AU.addRequired<ASanGlobalsMetadataWrapperPass>();
843 }
844
845 bool runOnModule(Module &M) override {
846 GlobalsMetadata &GlobalsMD =
847 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
848 ModuleAddressSanitizer ASanModule(M, GlobalsMD, CompileKernel, Recover,
849 UseGlobalGC, UseOdrIndicator);
850 return ASanModule.instrumentModule(M);
851 }
852
853private:
854 bool CompileKernel;
855 bool Recover;
856 bool UseGlobalGC;
857 bool UseOdrIndicator;
858};
859
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000860// Stack poisoning does not play well with exception handling.
861// When an exception is thrown, we essentially bypass the code
862// that unpoisones the stack. This is why the run-time library has
863// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
864// stack in the interceptor. This however does not work inside the
865// actual function which catches the exception. Most likely because the
866// compiler hoists the load of the shadow value somewhere too high.
867// This causes asan to report a non-existing bug on 453.povray.
868// It sounds like an LLVM bug.
869struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
870 Function &F;
871 AddressSanitizer &ASan;
872 DIBuilder DIB;
873 LLVMContext *C;
874 Type *IntptrTy;
875 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000876 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000877
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000878 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000879 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000880 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000881 unsigned StackAlignment;
882
James Y Knight13680222019-02-01 02:28:03 +0000883 FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
884 AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
885 FunctionCallee AsanSetShadowFunc[0x100] = {};
886 FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
887 FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000888
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000889 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
890 struct AllocaPoisonCall {
891 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000892 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000893 uint64_t Size;
894 bool DoPoison;
895 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000896 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
897 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Hans Wennborg6ae05772019-04-16 07:54:20 +0000898 bool HasUntracedLifetimeIntrinsic = false;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000899
Yury Gribov98b18592015-05-28 07:51:49 +0000900 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
901 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
902 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000903 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000904
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000905 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000906 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000907 AllocaForValueMapTy AllocaForValue;
908
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000909 bool HasNonEmptyInlineAsm = false;
910 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000911 std::unique_ptr<CallInst> EmptyInlineAsm;
912
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000913 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Leonard Chan436fb2b2019-02-13 22:22:48 +0000914 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
915 C(ASan.C), IntptrTy(ASan.IntptrTy),
916 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000917 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000918 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000919
920 bool runOnFunction() {
921 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000922
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000923 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000924 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000925
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000926 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000927 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000928
Yury Gribov55441bb2014-11-21 10:29:50 +0000929 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000930
931 initializeCallbacks(*F.getParent());
932
Hans Wennborg6ae05772019-04-16 07:54:20 +0000933 if (HasUntracedLifetimeIntrinsic) {
934 // If there are lifetime intrinsics which couldn't be traced back to an
935 // alloca, we may not know exactly when a variable enters scope, and
936 // therefore should "fail safe" by not poisoning them.
937 StaticAllocaPoisonCallVec.clear();
938 DynamicAllocaPoisonCallVec.clear();
939 }
940
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000941 processDynamicAllocas();
942 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000943
944 if (ClDebugStack) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000945 LLVM_DEBUG(dbgs() << F);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000946 }
947 return true;
948 }
949
Vitaly Buka74443f02017-07-18 22:28:03 +0000950 // Arguments marked with the "byval" attribute are implicitly copied without
951 // using an alloca instruction. To produce redzones for those arguments, we
952 // copy them a second time into memory allocated with an alloca instruction.
953 void copyArgsPassedByValToAllocas();
954
Yury Gribov55441bb2014-11-21 10:29:50 +0000955 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000956 // poisoned red zones around all of them.
957 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000958 void processStaticAllocas();
959 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000960
Yury Gribov98b18592015-05-28 07:51:49 +0000961 void createDynamicAllocasInitStorage();
962
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000963 // ----------------------- Visitors.
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000964 /// Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000965 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000966
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000967 /// Collect all Resume instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000968 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
969
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000970 /// Collect all CatchReturnInst instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000971 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
972
Yury Gribov98b18592015-05-28 07:51:49 +0000973 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
974 Value *SavedStack) {
975 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000976 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
977 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
978 // need to adjust extracted SP to compute the address of the most recent
979 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
980 // this purpose.
981 if (!isa<ReturnInst>(InstBefore)) {
982 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
983 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
984 {IntptrTy});
985
986 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
987
988 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
989 DynamicAreaOffset);
990 }
991
James Y Knight14359ef2019-02-01 20:44:24 +0000992 IRB.CreateCall(
993 AsanAllocasUnpoisonFunc,
994 {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000995 }
996
Yury Gribov55441bb2014-11-21 10:29:50 +0000997 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000998 void unpoisonDynamicAllocas() {
999 for (auto &Ret : RetVec)
1000 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +00001001
Yury Gribov98b18592015-05-28 07:51:49 +00001002 for (auto &StackRestoreInst : StackRestoreVec)
1003 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
1004 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +00001005 }
1006
Yury Gribov55441bb2014-11-21 10:29:50 +00001007 // Deploy and poison redzones around dynamic alloca call. To do this, we
1008 // should replace this call with another one with changed parameters and
1009 // replace all its uses with new address, so
1010 // addr = alloca type, old_size, align
1011 // is replaced by
1012 // new_size = (old_size + additional_size) * sizeof(type)
1013 // tmp = alloca i8, new_size, max(align, 32)
1014 // addr = tmp + 32 (first 32 bytes are for the left redzone).
1015 // Additional_size is added to make new memory allocation contain not only
1016 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +00001017 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +00001018
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001019 /// Collect Alloca instructions we want (and can) handle.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001020 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001021 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00001022 if (AI.isStaticAlloca()) {
1023 // Skip over allocas that are present *before* the first instrumented
1024 // alloca, we don't want to move those around.
1025 if (AllocaVec.empty())
1026 return;
1027
1028 StaticAllocasToMoveUp.push_back(&AI);
1029 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001030 return;
1031 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001032
1033 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +00001034 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +00001035 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +00001036 else
1037 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001038 }
1039
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001040 /// Collect lifetime intrinsic calls to check for use-after-scope
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001041 /// errors.
1042 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001043 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +00001044 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +00001045 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001046 if (!ASan.UseAfterScope)
1047 return;
Vedant Kumarb264d692018-12-21 21:49:40 +00001048 if (!II.isLifetimeStartOrEnd())
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001049 return;
1050 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1051 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
1052 // If size argument is undefined, don't do anything.
1053 if (Size->isMinusOne()) return;
1054 // Check that size doesn't saturate uint64_t and can
1055 // be stored in IntptrTy.
1056 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1057 if (SizeValue == ~0ULL ||
1058 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1059 return;
1060 // Find alloca instruction that corresponds to llvm.lifetime argument.
Alexander Potapenko6a63e5a2019-04-15 08:59:56 +00001061 AllocaInst *AI =
1062 llvm::findAllocaForValue(II.getArgOperand(1), AllocaForValue);
Hans Wennborg6ae05772019-04-16 07:54:20 +00001063 if (!AI) {
1064 HasUntracedLifetimeIntrinsic = true;
1065 return;
1066 }
Alexander Potapenko6a63e5a2019-04-15 08:59:56 +00001067 // We're interested only in allocas we can handle.
Hans Wennborg6ae05772019-04-16 07:54:20 +00001068 if (!ASan.isInterestingAlloca(*AI))
Vitaly Bukab451f1b2016-06-09 23:31:59 +00001069 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001070 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +00001071 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +00001072 if (AI->isStaticAlloca())
1073 StaticAllocaPoisonCallVec.push_back(APC);
1074 else if (ClInstrumentDynamicAllocas)
1075 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001076 }
1077
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001078 void visitCallSite(CallSite CS) {
1079 Instruction *I = CS.getInstruction();
1080 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00001081 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1082 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1083 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001084 HasReturnsTwiceCall |= CI->canReturnTwice();
1085 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001086 }
1087
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001088 // ---------------------- Helpers.
1089 void initializeCallbacks(Module &M);
1090
Vitaly Buka793913c2016-08-29 18:17:21 +00001091 // Copies bytes from ShadowBytes into shadow memory for indexes where
1092 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1093 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1094 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1095 IRBuilder<> &IRB, Value *ShadowBase);
1096 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1097 size_t Begin, size_t End, IRBuilder<> &IRB,
1098 Value *ShadowBase);
1099 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1100 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1101 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1102
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001103 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001104
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001105 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1106 bool Dynamic);
1107 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1108 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001109};
1110
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001111} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001112
Leonard Chan436fb2b2019-02-13 22:22:48 +00001113void LocationMetadata::parse(MDNode *MDN) {
1114 assert(MDN->getNumOperands() == 3);
1115 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
1116 Filename = DIFilename->getString();
1117 LineNo = mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
1118 ColumnNo =
1119 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
1120}
1121
1122// FIXME: It would be cleaner to instead attach relevant metadata to the globals
1123// we want to sanitize instead and reading this metadata on each pass over a
1124// function instead of reading module level metadata at first.
1125GlobalsMetadata::GlobalsMetadata(Module &M) {
1126 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
1127 if (!Globals)
1128 return;
1129 for (auto MDN : Globals->operands()) {
1130 // Metadata node contains the global and the fields of "Entry".
1131 assert(MDN->getNumOperands() == 5);
1132 auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
1133 // The optimizer may optimize away a global entirely.
1134 if (!V)
1135 continue;
1136 auto *StrippedV = V->stripPointerCasts();
1137 auto *GV = dyn_cast<GlobalVariable>(StrippedV);
1138 if (!GV)
1139 continue;
1140 // We can already have an entry for GV if it was merged with another
1141 // global.
1142 Entry &E = Entries[GV];
1143 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
1144 E.SourceLoc.parse(Loc);
1145 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
1146 E.Name = Name->getString();
1147 ConstantInt *IsDynInit = mdconst::extract<ConstantInt>(MDN->getOperand(3));
1148 E.IsDynInit |= IsDynInit->isOne();
1149 ConstantInt *IsBlacklisted =
1150 mdconst::extract<ConstantInt>(MDN->getOperand(4));
1151 E.IsBlacklisted |= IsBlacklisted->isOne();
1152 }
1153}
1154
1155AnalysisKey ASanGlobalsMetadataAnalysis::Key;
1156
1157GlobalsMetadata ASanGlobalsMetadataAnalysis::run(Module &M,
1158 ModuleAnalysisManager &AM) {
1159 return GlobalsMetadata(M);
1160}
1161
1162AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
1163 bool UseAfterScope)
1164 : CompileKernel(CompileKernel), Recover(Recover),
1165 UseAfterScope(UseAfterScope) {}
1166
1167PreservedAnalyses AddressSanitizerPass::run(Function &F,
1168 AnalysisManager<Function> &AM) {
1169 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1170 auto &MAM = MAMProxy.getManager();
1171 Module &M = *F.getParent();
1172 if (auto *R = MAM.getCachedResult<ASanGlobalsMetadataAnalysis>(M)) {
1173 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1174 AddressSanitizer Sanitizer(M, *R, CompileKernel, Recover, UseAfterScope);
1175 if (Sanitizer.instrumentFunction(F, TLI))
1176 return PreservedAnalyses::none();
1177 return PreservedAnalyses::all();
1178 }
1179
1180 report_fatal_error(
1181 "The ASanGlobalsMetadataAnalysis is required to run before "
1182 "AddressSanitizer can run");
1183 return PreservedAnalyses::all();
1184}
1185
1186ModuleAddressSanitizerPass::ModuleAddressSanitizerPass(bool CompileKernel,
1187 bool Recover,
1188 bool UseGlobalGC,
1189 bool UseOdrIndicator)
1190 : CompileKernel(CompileKernel), Recover(Recover), UseGlobalGC(UseGlobalGC),
1191 UseOdrIndicator(UseOdrIndicator) {}
1192
1193PreservedAnalyses ModuleAddressSanitizerPass::run(Module &M,
1194 AnalysisManager<Module> &AM) {
1195 GlobalsMetadata &GlobalsMD = AM.getResult<ASanGlobalsMetadataAnalysis>(M);
1196 ModuleAddressSanitizer Sanitizer(M, GlobalsMD, CompileKernel, Recover,
1197 UseGlobalGC, UseOdrIndicator);
1198 if (Sanitizer.instrumentModule(M))
1199 return PreservedAnalyses::none();
1200 return PreservedAnalyses::all();
1201}
1202
1203INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md",
1204 "Read metadata to mark which globals should be instrumented "
1205 "when running ASan.",
Clement Courbetc6e768f2019-02-14 12:10:49 +00001206 false, true)
Leonard Chan436fb2b2019-02-13 22:22:48 +00001207
1208char AddressSanitizerLegacyPass::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001209
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001210INITIALIZE_PASS_BEGIN(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001211 AddressSanitizerLegacyPass, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001212 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1213 false)
Leonard Chan436fb2b2019-02-13 22:22:48 +00001214INITIALIZE_PASS_DEPENDENCY(ASanGlobalsMetadataWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001215INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001216INITIALIZE_PASS_END(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001217 AddressSanitizerLegacyPass, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001218 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1219 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001220
Yury Gribovd7731982015-11-11 10:36:49 +00001221FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001222 bool Recover,
1223 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001224 assert(!CompileKernel || Recover);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001225 return new AddressSanitizerLegacyPass(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001226}
1227
Leonard Chan436fb2b2019-02-13 22:22:48 +00001228char ModuleAddressSanitizerLegacyPass::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001229
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001230INITIALIZE_PASS(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001231 ModuleAddressSanitizerLegacyPass, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001232 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001233 "ModulePass",
1234 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001235
Leonard Chan436fb2b2019-02-13 22:22:48 +00001236ModulePass *llvm::createModuleAddressSanitizerLegacyPassPass(
1237 bool CompileKernel, bool Recover, bool UseGlobalsGC, bool UseOdrIndicator) {
Yury Gribovd7731982015-11-11 10:36:49 +00001238 assert(!CompileKernel || Recover);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001239 return new ModuleAddressSanitizerLegacyPass(CompileKernel, Recover,
1240 UseGlobalsGC, UseOdrIndicator);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001241}
1242
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001243static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001244 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001245 assert(Res < kNumberOfAccessSizes);
1246 return Res;
1247}
1248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001249/// Create a global describing a source location.
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001250static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1251 LocationMetadata MD) {
1252 Constant *LocData[] = {
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00001253 createPrivateGlobalForString(M, MD.Filename, true, kAsanGenPrefix),
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001254 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1255 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1256 };
1257 auto LocStruct = ConstantStruct::getAnon(LocData);
1258 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1259 GlobalValue::PrivateLinkage, LocStruct,
1260 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001261 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001262 return GV;
1263}
1264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001265/// Check if \p G has been created by a trusted compiler pass.
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001266static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
Reid Kleckner85a8c122018-08-20 23:35:45 +00001267 // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1268 if (G->getName().startswith("llvm."))
1269 return true;
1270
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001271 // Do not instrument asan globals.
1272 if (G->getName().startswith(kAsanGenPrefix) ||
1273 G->getName().startswith(kSanCovGenPrefix) ||
1274 G->getName().startswith(kODRGenPrefix))
1275 return true;
1276
1277 // Do not instrument gcov counter arrays.
1278 if (G->getName() == "__llvm_gcov_ctr")
1279 return true;
1280
1281 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001282}
1283
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001284Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1285 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001286 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001287 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001288 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001289 Value *ShadowBase;
1290 if (LocalDynamicShadow)
1291 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001292 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001293 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1294 if (Mapping.OrShadowOffset)
1295 return IRB.CreateOr(Shadow, ShadowBase);
1296 else
1297 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001298}
1299
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001300// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001301void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1302 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001303 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001304 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001305 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001306 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1307 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1308 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001309 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001310 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001311 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001312 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1313 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1314 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001315 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001316 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001317}
1318
Anna Zaks8ed1d812015-02-27 03:12:36 +00001319/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001320bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001321 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1322
1323 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1324 return PreviouslySeenAllocaInfo->getSecond();
1325
Yury Gribov98b18592015-05-28 07:51:49 +00001326 bool IsInteresting =
1327 (AI.getAllocatedType()->isSized() &&
1328 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001329 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001330 // We are only interested in allocas not promotable to registers.
1331 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001332 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1333 // inalloca allocas are not treated as static, and we don't want
1334 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001335 !AI.isUsedWithInAlloca() &&
1336 // swifterror allocas are register promoted by ISel
1337 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001338
1339 ProcessedAllocas[&AI] = IsInteresting;
1340 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001341}
1342
Anna Zaks8ed1d812015-02-27 03:12:36 +00001343Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1344 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001345 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001346 unsigned *Alignment,
1347 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001348 // Skip memory accesses inserted by another instrumentation.
Philip Reames27820f92019-09-04 17:28:48 +00001349 if (I->hasMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001350
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001351 // Do not instrument the load fetching the dynamic shadow address.
1352 if (LocalDynamicShadow == I)
1353 return nullptr;
1354
Anna Zaks8ed1d812015-02-27 03:12:36 +00001355 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001356 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001357 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001358 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001359 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001360 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001361 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001362 PtrOperand = LI->getPointerOperand();
1363 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001364 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001365 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001366 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001367 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001368 PtrOperand = SI->getPointerOperand();
1369 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001370 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001371 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001372 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001373 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001374 PtrOperand = RMW->getPointerOperand();
1375 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001376 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001377 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001378 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001379 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001380 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001381 } else if (auto CI = dyn_cast<CallInst>(I)) {
1382 auto *F = dyn_cast<Function>(CI->getCalledValue());
1383 if (F && (F->getName().startswith("llvm.masked.load.") ||
1384 F->getName().startswith("llvm.masked.store."))) {
1385 unsigned OpOffset = 0;
1386 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001387 if (!ClInstrumentWrites)
1388 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001389 // Masked store has an initial operand for the value.
1390 OpOffset = 1;
1391 *IsWrite = true;
1392 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001393 if (!ClInstrumentReads)
1394 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001395 *IsWrite = false;
1396 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001397
1398 auto BasePtr = CI->getOperand(0 + OpOffset);
1399 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1400 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1401 if (auto AlignmentConstant =
1402 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1403 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1404 else
1405 *Alignment = 1; // No alignment guarantees. We probably got Undef
1406 if (MaybeMask)
1407 *MaybeMask = CI->getOperand(2 + OpOffset);
1408 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001409 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001410 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001411
Anna Zaks644d9d32016-06-22 00:15:52 +00001412 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001413 // Do not instrument acesses from different address spaces; we cannot deal
1414 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001415 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1416 if (PtrTy->getPointerAddressSpace() != 0)
1417 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001418
1419 // Ignore swifterror addresses.
1420 // swifterror memory addresses are mem2reg promoted by instruction
1421 // selection. As such they cannot have regular uses like an instrumentation
1422 // function and it makes no sense to track them as memory.
1423 if (PtrOperand->isSwiftError())
1424 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001425 }
1426
Anna Zaks8ed1d812015-02-27 03:12:36 +00001427 // Treat memory accesses to promotable allocas as non-interesting since they
1428 // will not cause memory violations. This greatly speeds up the instrumented
1429 // executable at -O0.
1430 if (ClSkipPromotableAllocas)
1431 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1432 return isInterestingAlloca(*AI) ? AI : nullptr;
1433
1434 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001435}
1436
Kostya Serebryany796f6552014-02-27 12:45:36 +00001437static bool isPointerOperand(Value *V) {
1438 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1439}
1440
1441// This is a rough heuristic; it may cause both false positives and
1442// false negatives. The proper implementation requires cooperation with
1443// the frontend.
Pierre Gousseaua833c2b2019-03-28 10:51:24 +00001444static bool isInterestingPointerComparison(Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001445 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Pierre Gousseaua833c2b2019-03-28 10:51:24 +00001446 if (!Cmp->isRelational())
1447 return false;
1448 } else {
1449 return false;
1450 }
1451 return isPointerOperand(I->getOperand(0)) &&
1452 isPointerOperand(I->getOperand(1));
1453}
1454
1455// This is a rough heuristic; it may cause both false positives and
1456// false negatives. The proper implementation requires cooperation with
1457// the frontend.
1458static bool isInterestingPointerSubtraction(Instruction *I) {
1459 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1460 if (BO->getOpcode() != Instruction::Sub)
1461 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001462 } else {
1463 return false;
1464 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001465 return isPointerOperand(I->getOperand(0)) &&
1466 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001467}
1468
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001469bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1470 // If a global variable does not have dynamic initialization we don't
1471 // have to instrument it. However, if a global does not have initializer
1472 // at all, we assume it has dynamic initializer (in other TU).
Leonard Chan436fb2b2019-02-13 22:22:48 +00001473 //
1474 // FIXME: Metadata should be attched directly to the global directly instead
1475 // of being added to llvm.asan.globals.
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001476 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001477}
1478
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001479void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1480 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001481 IRBuilder<> IRB(I);
James Y Knight13680222019-02-01 02:28:03 +00001482 FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001483 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001484 for (Value *&i : Param) {
1485 if (i->getType()->isPointerTy())
1486 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001487 }
David Blaikieff6409d2015-05-18 22:13:54 +00001488 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001489}
1490
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001491static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001492 Instruction *InsertBefore, Value *Addr,
1493 unsigned Alignment, unsigned Granularity,
1494 uint32_t TypeSize, bool IsWrite,
1495 Value *SizeArgument, bool UseCalls,
1496 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001497 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1498 // if the data is properly aligned.
1499 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1500 TypeSize == 128) &&
1501 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001502 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1503 nullptr, UseCalls, Exp);
1504 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1505 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001506}
1507
1508static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1509 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001510 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001511 Value *Addr, unsigned Alignment,
1512 unsigned Granularity, uint32_t TypeSize,
1513 bool IsWrite, Value *SizeArgument,
1514 bool UseCalls, uint32_t Exp) {
1515 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1516 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1517 unsigned Num = VTy->getVectorNumElements();
1518 auto Zero = ConstantInt::get(IntptrTy, 0);
1519 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001520 Value *InstrumentedAddress = nullptr;
1521 Instruction *InsertBefore = I;
1522 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1523 // dyn_cast as we might get UndefValue
1524 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001525 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001526 // Mask is constant false, so no instrumentation needed.
1527 continue;
1528 // If we have a true or undef value, fall through to doInstrumentAddress
1529 // with InsertBefore == I
1530 }
1531 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001532 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001533 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001534 Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001535 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001536 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001537
1538 IRBuilder<> IRB(InsertBefore);
1539 InstrumentedAddress =
James Y Knight77160752019-02-01 20:44:47 +00001540 IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001541 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1542 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1543 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001544 }
1545}
1546
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001547void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001548 Instruction *I, bool UseCalls,
1549 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001550 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001551 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001552 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001553 Value *MaybeMask = nullptr;
1554 Value *Addr =
1555 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001556 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001557
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001558 // Optimization experiments.
1559 // The experiments can be used to evaluate potential optimizations that remove
1560 // instrumentation (assess false negatives). Instead of completely removing
1561 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1562 // experiments that want to remove instrumentation of this instruction).
1563 // If Exp is non-zero, this pass will emit special calls into runtime
1564 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1565 // make runtime terminate the program in a special way (with a different
1566 // exit status). Then you run the new compiler on a buggy corpus, collect
1567 // the special terminations (ideally, you don't see them at all -- no false
1568 // negatives) and make the decision on the optimization.
1569 uint32_t Exp = ClForceExperiment;
1570
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001571 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001572 // If initialization order checking is disabled, a simple access to a
1573 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001574 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001575 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001576 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1577 NumOptimizedAccessesToGlobalVar++;
1578 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001579 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001580 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001581
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001582 if (ClOpt && ClOptStack) {
1583 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001584 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001585 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1586 NumOptimizedAccessesToStackVar++;
1587 return;
1588 }
1589 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001590
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001591 if (IsWrite)
1592 NumInstrumentedWrites++;
1593 else
1594 NumInstrumentedReads++;
1595
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001596 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001597 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001598 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1599 Alignment, Granularity, TypeSize, IsWrite,
1600 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001601 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001602 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001603 IsWrite, nullptr, UseCalls, Exp);
1604 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001605}
1606
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001607Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1608 Value *Addr, bool IsWrite,
1609 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001610 Value *SizeArgument,
1611 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001612 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001613 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1614 CallInst *Call = nullptr;
1615 if (SizeArgument) {
1616 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001617 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1618 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001619 else
David Blaikieff6409d2015-05-18 22:13:54 +00001620 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1621 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001622 } else {
1623 if (Exp == 0)
1624 Call =
1625 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1626 else
David Blaikieff6409d2015-05-18 22:13:54 +00001627 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1628 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001629 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001630
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001631 // We don't do Call->setDoesNotReturn() because the BB already has
1632 // UnreachableInst at the end.
1633 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001634 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001635 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001636}
1637
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001638Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001639 Value *ShadowValue,
1640 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001641 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001642 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001643 Value *LastAccessedByte =
1644 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001645 // (Addr & (Granularity - 1)) + size - 1
1646 if (TypeSize / 8 > 1)
1647 LastAccessedByte = IRB.CreateAdd(
1648 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1649 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001650 LastAccessedByte =
1651 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001652 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1653 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1654}
1655
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001656void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001657 Instruction *InsertBefore, Value *Addr,
1658 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001659 Value *SizeArgument, bool UseCalls,
1660 uint32_t Exp) {
Walter Leecdbb2072018-05-18 04:10:38 +00001661 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1662
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001663 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001664 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001665 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1666
1667 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001668 if (Exp == 0)
1669 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1670 AddrLong);
1671 else
David Blaikieff6409d2015-05-18 22:13:54 +00001672 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1673 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001674 return;
1675 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001676
Walter Leecdbb2072018-05-18 04:10:38 +00001677 if (IsMyriad) {
1678 // Strip the cache bit and do range check.
1679 // AddrLong &= ~kMyriadCacheBitMask32
1680 AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1681 // Tag = AddrLong >> kMyriadTagShift
1682 Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1683 // Tag == kMyriadDDRTag
1684 Value *TagCheck =
1685 IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1686
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001687 Instruction *TagCheckTerm =
1688 SplitBlockAndInsertIfThen(TagCheck, InsertBefore, false,
1689 MDBuilder(*C).createBranchWeights(1, 100000));
Walter Leecdbb2072018-05-18 04:10:38 +00001690 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1691 IRB.SetInsertPoint(TagCheckTerm);
1692 InsertBefore = TagCheckTerm;
1693 }
1694
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001695 Type *ShadowTy =
1696 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001697 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1698 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1699 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001700 Value *ShadowValue =
James Y Knight14359ef2019-02-01 20:44:24 +00001701 IRB.CreateLoad(ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001702
1703 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001704 size_t Granularity = 1ULL << Mapping.Scale;
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001705 Instruction *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001706
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001707 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001708 // We use branch weights for the slow path check, to indicate that the slow
1709 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001710 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001711 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001712 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001713 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001714 IRB.SetInsertPoint(CheckTerm);
1715 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001716 if (Recover) {
1717 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1718 } else {
1719 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001720 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001721 CrashTerm = new UnreachableInst(*C, CrashBlock);
1722 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1723 ReplaceInstWithInst(CheckTerm, NewTerm);
1724 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001725 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001726 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001727 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001728
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001729 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001730 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001731 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001732}
1733
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001734// Instrument unusual size or unusual alignment.
1735// We can not do it with a single check, so we do 1-byte check for the first
1736// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1737// to report the actual access size.
1738void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001739 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1740 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1741 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001742 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1743 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1744 if (UseCalls) {
1745 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001746 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1747 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001748 else
David Blaikieff6409d2015-05-18 22:13:54 +00001749 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1750 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001751 } else {
1752 Value *LastByte = IRB.CreateIntToPtr(
1753 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1754 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001755 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1756 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001757 }
1758}
1759
Leonard Chan436fb2b2019-02-13 22:22:48 +00001760void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001761 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001762 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001763 IRBuilder<> IRB(&GlobalInit.front(),
1764 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001765
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001766 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001767 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1768 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001769
1770 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001771 for (auto &BB : GlobalInit.getBasicBlockList())
1772 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001773 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001774}
1775
Leonard Chan436fb2b2019-02-13 22:22:48 +00001776void ModuleAddressSanitizer::createInitializerPoisonCalls(
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001777 Module &M, GlobalValue *ModuleName) {
1778 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001779 if (!GV)
1780 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001781
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001782 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1783 if (!CA)
1784 return;
1785
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001786 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001787 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001788 ConstantStruct *CS = cast<ConstantStruct>(OP);
1789
1790 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001791 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001792 if (F->getName() == kAsanModuleCtorName) continue;
1793 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1794 // Don't instrument CTORs that will run before asan.module_ctor.
Guanzhong Chenb3292a82019-08-06 21:52:58 +00001795 if (Priority->getLimitedValue() <= GetCtorAndDtorPriority(TargetTriple))
1796 continue;
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001797 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001798 }
1799 }
1800}
1801
Leonard Chan436fb2b2019-02-13 22:22:48 +00001802bool ModuleAddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001803 Type *Ty = G->getValueType();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001804 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001805
Leonard Chan436fb2b2019-02-13 22:22:48 +00001806 // FIXME: Metadata should be attched directly to the global directly instead
1807 // of being added to llvm.asan.globals.
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001808 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001809 if (!Ty->isSized()) return false;
1810 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001811 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001812 // Two problems with thread-locals:
1813 // - The address of the main thread's copy can't be computed at link-time.
1814 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001815 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001816 // For now, just ignore this Global if the alignment is large.
1817 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001818
Reid Kleckner85a8c122018-08-20 23:35:45 +00001819 // For non-COFF targets, only instrument globals known to be defined by this
1820 // TU.
1821 // FIXME: We can instrument comdat globals on ELF if we are using the
1822 // GC-friendly metadata scheme.
1823 if (!TargetTriple.isOSBinFormatCOFF()) {
1824 if (!G->hasExactDefinition() || G->hasComdat())
1825 return false;
1826 } else {
1827 // On COFF, don't instrument non-ODR linkages.
1828 if (G->isInterposable())
1829 return false;
1830 }
1831
1832 // If a comdat is present, it must have a selection kind that implies ODR
1833 // semantics: no duplicates, any, or exact match.
1834 if (Comdat *C = G->getComdat()) {
1835 switch (C->getSelectionKind()) {
1836 case Comdat::Any:
1837 case Comdat::ExactMatch:
1838 case Comdat::NoDuplicates:
1839 break;
1840 case Comdat::Largest:
1841 case Comdat::SameSize:
1842 return false;
1843 }
1844 }
1845
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001846 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001847 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001848
Anna Zaks11904602015-06-09 00:58:08 +00001849 // Globals from llvm.metadata aren't emitted, do not instrument them.
1850 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001851 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001852 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001853
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001854 // Do not instrument function pointers to initialization and termination
1855 // routines: dynamic linker will not properly handle redzones.
1856 if (Section.startswith(".preinit_array") ||
1857 Section.startswith(".init_array") ||
1858 Section.startswith(".fini_array")) {
1859 return false;
1860 }
1861
Reid Kleckner12395b72018-06-13 20:47:21 +00001862 // On COFF, if the section name contains '$', it is highly likely that the
1863 // user is using section sorting to create an array of globals similar to
1864 // the way initialization callbacks are registered in .init_array and
1865 // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1866 // to such globals is counterproductive, because the intent is that they
1867 // will form an array, and out-of-bounds accesses are expected.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001868 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001869 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
Reid Kleckner12395b72018-06-13 20:47:21 +00001870 if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1871 LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1872 << *G << "\n");
Anna Zaks11904602015-06-09 00:58:08 +00001873 return false;
1874 }
1875
Kuba Brecka1001bb52014-12-05 22:19:18 +00001876 if (TargetTriple.isOSBinFormatMachO()) {
1877 StringRef ParsedSegment, ParsedSection;
1878 unsigned TAA = 0, StubSize = 0;
1879 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001880 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1881 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001882 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001883
1884 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1885 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1886 // them.
1887 if (ParsedSegment == "__OBJC" ||
1888 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001889 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001890 return false;
1891 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001892 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001893 // Constant CFString instances are compiled in the following way:
1894 // -- the string buffer is emitted into
1895 // __TEXT,__cstring,cstring_literals
1896 // -- the constant NSConstantString structure referencing that buffer
1897 // is placed into __DATA,__cfstring
1898 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1899 // Moreover, it causes the linker to crash on OS X 10.7
1900 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001901 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001902 return false;
1903 }
1904 // The linker merges the contents of cstring_literals and removes the
1905 // trailing zeroes.
1906 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001907 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001908 return false;
1909 }
1910 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001911 }
1912
1913 return true;
1914}
1915
Ryan Govostes653f9d02016-03-28 20:28:57 +00001916// On Mach-O platforms, we emit global metadata in a separate section of the
1917// binary in order to allow the linker to properly dead strip. This is only
1918// supported on recent versions of ld64.
Leonard Chan436fb2b2019-02-13 22:22:48 +00001919bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
Ryan Govostes653f9d02016-03-28 20:28:57 +00001920 if (!TargetTriple.isOSBinFormatMachO())
1921 return false;
1922
1923 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1924 return true;
1925 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001926 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001927 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1928 return true;
1929
1930 return false;
1931}
1932
Leonard Chan436fb2b2019-02-13 22:22:48 +00001933StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
Reid Kleckner01660a32016-11-21 20:40:37 +00001934 switch (TargetTriple.getObjectFormat()) {
1935 case Triple::COFF: return ".ASAN$GL";
1936 case Triple::ELF: return "asan_globals";
1937 case Triple::MachO: return "__DATA,__asan_globals,regular";
Hubert Tong2711e162019-07-19 08:46:18 +00001938 case Triple::Wasm:
1939 case Triple::XCOFF:
1940 report_fatal_error(
1941 "ModuleAddressSanitizer not implemented for object file format.");
1942 case Triple::UnknownObjectFormat:
1943 break;
Reid Kleckner01660a32016-11-21 20:40:37 +00001944 }
1945 llvm_unreachable("unsupported object format");
1946}
1947
Leonard Chan436fb2b2019-02-13 22:22:48 +00001948void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
Alexey Samsonov788381b2012-12-25 12:28:20 +00001949 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001950
Alexey Samsonov788381b2012-12-25 12:28:20 +00001951 // Declare our poisoning and unpoisoning functions.
James Y Knight13680222019-02-01 02:28:03 +00001952 AsanPoisonGlobals =
1953 M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
1954 AsanUnpoisonGlobals =
1955 M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
Ryan Govostes653f9d02016-03-28 20:28:57 +00001956
Alexey Samsonov788381b2012-12-25 12:28:20 +00001957 // Declare functions that register/unregister globals.
James Y Knight13680222019-02-01 02:28:03 +00001958 AsanRegisterGlobals = M.getOrInsertFunction(
1959 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
1960 AsanUnregisterGlobals = M.getOrInsertFunction(
1961 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001962
1963 // Declare the functions that find globals in a shared object and then invoke
1964 // the (un)register function on them.
James Y Knight13680222019-02-01 02:28:03 +00001965 AsanRegisterImageGlobals = M.getOrInsertFunction(
1966 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
1967 AsanUnregisterImageGlobals = M.getOrInsertFunction(
1968 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001969
James Y Knight13680222019-02-01 02:28:03 +00001970 AsanRegisterElfGlobals =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001971 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
James Y Knight13680222019-02-01 02:28:03 +00001972 IntptrTy, IntptrTy, IntptrTy);
1973 AsanUnregisterElfGlobals =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001974 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
James Y Knight13680222019-02-01 02:28:03 +00001975 IntptrTy, IntptrTy, IntptrTy);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001976}
1977
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001978// Put the metadata and the instrumented global in the same group. This ensures
1979// that the metadata is discarded if the instrumented global is discarded.
Leonard Chan436fb2b2019-02-13 22:22:48 +00001980void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001981 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001982 Module &M = *G->getParent();
1983 Comdat *C = G->getComdat();
1984 if (!C) {
1985 if (!G->hasName()) {
1986 // If G is unnamed, it must be internal. Give it an artificial name
1987 // so we can put it in a comdat.
1988 assert(G->hasLocalLinkage());
1989 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1990 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001991
1992 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1993 std::string Name = G->getName();
1994 Name += InternalSuffix;
1995 C = M.getOrInsertComdat(Name);
1996 } else {
1997 C = M.getOrInsertComdat(G->getName());
1998 }
1999
Reid Klecknerc212cc82017-10-31 16:16:08 +00002000 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
2001 // linkage to internal linkage so that a symbol table entry is emitted. This
2002 // is necessary in order to create the comdat group.
2003 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002004 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00002005 if (G->hasPrivateLinkage())
2006 G->setLinkage(GlobalValue::InternalLinkage);
2007 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002008 G->setComdat(C);
2009 }
2010
2011 assert(G->hasComdat());
2012 Metadata->setComdat(G->getComdat());
2013}
2014
2015// Create a separate metadata global and put it in the appropriate ASan
2016// global registration section.
2017GlobalVariable *
Leonard Chan436fb2b2019-02-13 22:22:48 +00002018ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002019 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00002020 auto Linkage = TargetTriple.isOSBinFormatMachO()
2021 ? GlobalVariable::InternalLinkage
2022 : GlobalVariable::PrivateLinkage;
2023 GlobalVariable *Metadata = new GlobalVariable(
2024 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00002025 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002026 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002027 return Metadata;
2028}
2029
Leonard Chan436fb2b2019-02-13 22:22:48 +00002030IRBuilder<> ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002031 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002032 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
2033 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
2034 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002035
2036 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
2037}
2038
Leonard Chan436fb2b2019-02-13 22:22:48 +00002039void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002040 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2041 ArrayRef<Constant *> MetadataInitializers) {
2042 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00002043 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002044
2045 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00002046 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002047 GlobalVariable *G = ExtendedGlobals[i];
2048 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00002049 CreateMetadataGlobal(M, Initializer, G->getName());
2050
2051 // The MSVC linker always inserts padding when linking incrementally. We
2052 // cope with that by aligning each struct to its size, which must be a power
2053 // of two.
2054 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2055 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2056 "global metadata will not be padded appropriately");
2057 Metadata->setAlignment(SizeOfGlobalStruct);
2058
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002059 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002060 }
2061}
2062
Leonard Chan436fb2b2019-02-13 22:22:48 +00002063void ModuleAddressSanitizer::InstrumentGlobalsELF(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002064 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2065 ArrayRef<Constant *> MetadataInitializers,
2066 const std::string &UniqueModuleId) {
2067 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2068
2069 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2070 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2071 GlobalVariable *G = ExtendedGlobals[i];
2072 GlobalVariable *Metadata =
2073 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2074 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2075 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2076 MetadataGlobals[i] = Metadata;
2077
2078 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2079 }
2080
2081 // Update llvm.compiler.used, adding the new metadata globals. This is
2082 // needed so that during LTO these variables stay alive.
2083 if (!MetadataGlobals.empty())
2084 appendToCompilerUsed(M, MetadataGlobals);
2085
2086 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2087 // to look up the loaded image that contains it. Second, we can store in it
2088 // whether registration has already occurred, to prevent duplicate
2089 // registration.
2090 //
2091 // Common linkage ensures that there is only one global per shared library.
2092 GlobalVariable *RegisteredFlag = new GlobalVariable(
2093 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2094 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2095 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2096
2097 // Create start and stop symbols.
2098 GlobalVariable *StartELFMetadata = new GlobalVariable(
2099 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2100 "__start_" + getGlobalMetadataSection());
2101 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2102 GlobalVariable *StopELFMetadata = new GlobalVariable(
2103 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2104 "__stop_" + getGlobalMetadataSection());
2105 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2106
2107 // Create a call to register the globals with the runtime.
2108 IRB.CreateCall(AsanRegisterElfGlobals,
2109 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2110 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2111 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2112
2113 // We also need to unregister globals at the end, e.g., when a shared library
2114 // gets closed.
2115 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2116 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
2117 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2118 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2119 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2120}
2121
Leonard Chan436fb2b2019-02-13 22:22:48 +00002122void ModuleAddressSanitizer::InstrumentGlobalsMachO(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002123 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2124 ArrayRef<Constant *> MetadataInitializers) {
2125 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2126
2127 // On recent Mach-O platforms, use a structure which binds the liveness of
2128 // the global variable to the metadata struct. Keep the list of "Liveness" GV
2129 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00002130 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002131 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2132
2133 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2134 Constant *Initializer = MetadataInitializers[i];
2135 GlobalVariable *G = ExtendedGlobals[i];
2136 GlobalVariable *Metadata =
2137 CreateMetadataGlobal(M, Initializer, G->getName());
2138
2139 // On recent Mach-O platforms, we emit the global metadata in a way that
2140 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00002141 auto LivenessBinder =
2142 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2143 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002144 GlobalVariable *Liveness = new GlobalVariable(
2145 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2146 Twine("__asan_binder_") + G->getName());
2147 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2148 LivenessGlobals[i] = Liveness;
2149 }
2150
2151 // Update llvm.compiler.used, adding the new liveness globals. This is
2152 // needed so that during LTO these variables stay alive. The alternative
2153 // would be to have the linker handling the LTO symbols, but libLTO
2154 // current API does not expose access to the section for each symbol.
2155 if (!LivenessGlobals.empty())
2156 appendToCompilerUsed(M, LivenessGlobals);
2157
2158 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2159 // to look up the loaded image that contains it. Second, we can store in it
2160 // whether registration has already occurred, to prevent duplicate
2161 // registration.
2162 //
2163 // common linkage ensures that there is only one global per shared library.
2164 GlobalVariable *RegisteredFlag = new GlobalVariable(
2165 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2166 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2167 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2168
2169 IRB.CreateCall(AsanRegisterImageGlobals,
2170 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2171
2172 // We also need to unregister globals at the end, e.g., when a shared library
2173 // gets closed.
2174 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2175 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2176 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2177}
2178
Leonard Chan436fb2b2019-02-13 22:22:48 +00002179void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002180 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2181 ArrayRef<Constant *> MetadataInitializers) {
2182 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2183 unsigned N = ExtendedGlobals.size();
2184 assert(N > 0);
2185
2186 // On platforms that don't have a custom metadata section, we emit an array
2187 // of global metadata structures.
2188 ArrayType *ArrayOfGlobalStructTy =
2189 ArrayType::get(MetadataInitializers[0]->getType(), N);
2190 auto AllGlobals = new GlobalVariable(
2191 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2192 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00002193 if (Mapping.Scale > 3)
2194 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002195
2196 IRB.CreateCall(AsanRegisterGlobals,
2197 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2198 ConstantInt::get(IntptrTy, N)});
2199
2200 // We also need to unregister globals at the end, e.g., when a shared library
2201 // gets closed.
2202 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2203 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2204 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2205 ConstantInt::get(IntptrTy, N)});
2206}
2207
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002208// This function replaces all global variables with new variables that have
2209// trailing redzones. It also creates a function that poisons
2210// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002211// Sets *CtorComdat to true if the global registration code emitted into the
2212// asan constructor is comdat-compatible.
Leonard Chan436fb2b2019-02-13 22:22:48 +00002213bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2214 bool *CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002215 *CtorComdat = false;
Kostya Serebryany20a79972012-11-22 03:18:50 +00002216
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002217 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2218
Alexey Samsonova02e6642014-05-29 18:40:48 +00002219 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002220 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002221 }
2222
2223 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002224 if (n == 0) {
2225 *CtorComdat = true;
2226 return false;
2227 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002228
Reid Kleckner78565832016-11-29 01:32:21 +00002229 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002230
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002231 // A global is described by a structure
2232 // size_t beg;
2233 // size_t size;
2234 // size_t size_with_redzone;
2235 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002236 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002237 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002238 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002239 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002240 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002241 StructType *GlobalStructTy =
2242 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002243 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002244 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2245 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002246
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002247 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002248
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002249 // We shouldn't merge same module names, as this string serves as unique
2250 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002251 GlobalVariable *ModuleName = createPrivateGlobalForString(
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002252 M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002253
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002254 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002255 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002256 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002257
Leonard Chan436fb2b2019-02-13 22:22:48 +00002258 // FIXME: Metadata should be attched directly to the global directly instead
2259 // of being added to llvm.asan.globals.
Alexey Samsonov15c96692014-07-12 00:42:52 +00002260 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002261 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002262 // Create string holding the global name (use global name from metadata
2263 // if it's available, otherwise just write the name of global variable).
2264 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002265 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002266 /*AllowMerging*/ true, kAsanGenPrefix);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002267
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002268 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002269 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002270 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002271 // MinRZ <= RZ <= kMaxGlobalRedzone
2272 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002273 uint64_t RZ = std::max(
2274 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002275 uint64_t RightRedzoneSize = RZ;
2276 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002277 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002278 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002279 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2280
Serge Gueltone38003f2017-05-09 19:31:13 +00002281 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2282 Constant *NewInitializer = ConstantStruct::get(
2283 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002284
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002285 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002286 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2287 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2288 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002289 GlobalVariable *NewGlobal =
2290 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2291 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002292 NewGlobal->copyAttributesFrom(G);
Reid Kleckner85a8c122018-08-20 23:35:45 +00002293 NewGlobal->setComdat(G->getComdat());
Kostya Serebryany87191f62013-01-24 10:35:40 +00002294 NewGlobal->setAlignment(MinRZ);
Vitaly Bukad414e1b2018-12-20 00:30:18 +00002295 // Don't fold globals with redzones. ODR violation detector and redzone
2296 // poisoning implicitly creates a dependence on the global's address, so it
2297 // is no longer valid for it to be marked unnamed_addr.
2298 NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002299
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002300 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2301 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2302 G->isConstant()) {
2303 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2304 if (Seq && Seq->isCString())
2305 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2306 }
2307
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002308 // Transfer the debug info. The payload starts at offset zero so we can
2309 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002310 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002311 G->getDebugInfo(GVs);
2312 for (auto *GV : GVs)
2313 NewGlobal->addDebugInfo(GV);
2314
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002315 Value *Indices2[2];
2316 Indices2[0] = IRB.getInt32(0);
2317 Indices2[1] = IRB.getInt32(0);
2318
2319 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002320 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002321 NewGlobal->takeName(G);
2322 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002323 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002324
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002325 Constant *SourceLoc;
2326 if (!MD.SourceLoc.empty()) {
2327 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2328 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2329 } else {
2330 SourceLoc = ConstantInt::get(IntptrTy, 0);
2331 }
2332
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002333 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2334 GlobalValue *InstrumentedGlobal = NewGlobal;
2335
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002336 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002337 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2338 TargetTriple.isOSBinFormatWasm();
Vitaly Buka8076c572018-12-05 01:44:31 +00002339 if (CanUsePrivateAliases && UsePrivateAlias) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002340 // Create local alias for NewGlobal to avoid crash on ODR between
2341 // instrumented and non-instrumented libraries.
Vitaly Bukad6bab092018-12-04 23:17:41 +00002342 InstrumentedGlobal =
Vitaly Buka537cfc02018-12-04 00:36:14 +00002343 GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
Vitaly Bukad6bab092018-12-04 23:17:41 +00002344 }
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002345
Vitaly Buka07a55f22018-12-20 00:30:27 +00002346 // ODR should not happen for local linkage.
2347 if (NewGlobal->hasLocalLinkage()) {
Vitaly Bukaa2576392018-12-13 09:47:39 +00002348 ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2349 IRB.getInt8PtrTy());
2350 } else if (UseOdrIndicator) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002351 // With local aliases, we need to provide another externally visible
2352 // symbol __odr_asan_XXX to detect ODR violation.
2353 auto *ODRIndicatorSym =
2354 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2355 Constant::getNullValue(IRB.getInt8Ty()),
2356 kODRGenPrefix + NameForGlobal, nullptr,
2357 NewGlobal->getThreadLocalMode());
2358
2359 // Set meaningful attributes for indicator symbol.
2360 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2361 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2362 ODRIndicatorSym->setAlignment(1);
2363 ODRIndicator = ODRIndicatorSym;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002364 }
2365
Reid Kleckner01660a32016-11-21 20:40:37 +00002366 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002367 GlobalStructTy,
2368 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002369 ConstantInt::get(IntptrTy, SizeInBytes),
2370 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2371 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002372 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002373 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002374 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002375
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002376 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002377
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002378 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002379
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002380 Initializers[i] = Initializer;
2381 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002382
Kuba Mracek8842da82018-03-08 21:02:18 +00002383 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2384 // ConstantMerge'ing them.
2385 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2386 for (size_t i = 0; i < n; i++) {
2387 GlobalVariable *G = NewGlobals[i];
2388 if (G->getName().empty()) continue;
2389 GlobalsToAddToUsedList.push_back(G);
2390 }
2391 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2392
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002393 std::string ELFUniqueModuleId =
2394 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2395 : "";
2396
2397 if (!ELFUniqueModuleId.empty()) {
2398 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2399 *CtorComdat = true;
2400 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002401 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002402 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002403 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2404 } else {
2405 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002406 }
2407
Reid Kleckner01660a32016-11-21 20:40:37 +00002408 // Create calls for poisoning before initializers run and unpoisoning after.
2409 if (HasDynamicallyInitializedGlobals)
2410 createInitializerPoisonCalls(M, ModuleName);
2411
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002412 LLVM_DEBUG(dbgs() << M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002413 return true;
2414}
2415
Leonard Chan436fb2b2019-02-13 22:22:48 +00002416int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002417 int LongSize = M.getDataLayout().getPointerSizeInBits();
2418 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2419 int Version = 8;
2420 // 32-bit Android is one version ahead because of the switch to dynamic
2421 // shadow.
2422 Version += (LongSize == 32 && isAndroid);
2423 return Version;
2424}
2425
Leonard Chan436fb2b2019-02-13 22:22:48 +00002426bool ModuleAddressSanitizer::instrumentModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002427 initializeCallbacks(M);
2428
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002429 if (CompileKernel)
2430 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002431
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002432 // Create a module constructor. A destructor is created lazily because not all
2433 // platforms, and not all modules need it.
Julian Lettner3ae9b9d2019-08-28 20:40:55 +00002434 std::string AsanVersion = std::to_string(GetAsanVersion(M));
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002435 std::string VersionCheckName =
Julian Lettner3ae9b9d2019-08-28 20:40:55 +00002436 ClInsertVersionCheck ? (kAsanVersionCheckNamePrefix + AsanVersion) : "";
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002437 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2438 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002439 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002440
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002441 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002442 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002443 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002444 if (ClGlobals) {
2445 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002446 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2447 }
2448
Guanzhong Chenb3292a82019-08-06 21:52:58 +00002449 const uint64_t Priority = GetCtorAndDtorPriority(TargetTriple);
2450
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002451 // Put the constructor and destructor in comdat if both
2452 // (1) global instrumentation is not TU-specific
2453 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002454 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002455 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
Guanzhong Chenb3292a82019-08-06 21:52:58 +00002456 appendToGlobalCtors(M, AsanCtorFunction, Priority, AsanCtorFunction);
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002457 if (AsanDtorFunction) {
2458 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
Guanzhong Chenb3292a82019-08-06 21:52:58 +00002459 appendToGlobalDtors(M, AsanDtorFunction, Priority, AsanDtorFunction);
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002460 }
2461 } else {
Guanzhong Chenb3292a82019-08-06 21:52:58 +00002462 appendToGlobalCtors(M, AsanCtorFunction, Priority);
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002463 if (AsanDtorFunction)
Guanzhong Chenb3292a82019-08-06 21:52:58 +00002464 appendToGlobalDtors(M, AsanDtorFunction, Priority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002465 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002466
2467 return Changed;
2468}
2469
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002470void AddressSanitizer::initializeCallbacks(Module &M) {
2471 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002472 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002473 // IsWrite, TypeSize and Exp are encoded in the function name.
2474 for (int Exp = 0; Exp < 2; Exp++) {
2475 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2476 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2477 const std::string ExpStr = Exp ? "exp_" : "";
Yury Gribovd7731982015-11-11 10:36:49 +00002478 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002479
2480 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2481 SmallVector<Type *, 2> Args1{1, IntptrTy};
2482 if (Exp) {
2483 Type *ExpType = Type::getInt32Ty(*C);
2484 Args2.push_back(ExpType);
2485 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002486 }
James Y Knight13680222019-02-01 02:28:03 +00002487 AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2488 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2489 FunctionType::get(IRB.getVoidTy(), Args2, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002490
James Y Knight13680222019-02-01 02:28:03 +00002491 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2492 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2493 FunctionType::get(IRB.getVoidTy(), Args2, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002494
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002495 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2496 AccessSizeIndex++) {
2497 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2498 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
James Y Knight13680222019-02-01 02:28:03 +00002499 M.getOrInsertFunction(
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002500 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
James Y Knight13680222019-02-01 02:28:03 +00002501 FunctionType::get(IRB.getVoidTy(), Args1, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002502
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002503 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
James Y Knight13680222019-02-01 02:28:03 +00002504 M.getOrInsertFunction(
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002505 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
James Y Knight13680222019-02-01 02:28:03 +00002506 FunctionType::get(IRB.getVoidTy(), Args1, false));
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002507 }
2508 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002509 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002510
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002511 const std::string MemIntrinCallbackPrefix =
2512 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
James Y Knight13680222019-02-01 02:28:03 +00002513 AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2514 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2515 IRB.getInt8PtrTy(), IntptrTy);
2516 AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2517 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2518 IRB.getInt8PtrTy(), IntptrTy);
2519 AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2520 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2521 IRB.getInt32Ty(), IntptrTy);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002522
James Y Knight13680222019-02-01 02:28:03 +00002523 AsanHandleNoReturnFunc =
2524 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002525
James Y Knight13680222019-02-01 02:28:03 +00002526 AsanPtrCmpFunction =
2527 M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2528 AsanPtrSubFunction =
2529 M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002530 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2531 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2532 StringRef(""), StringRef(""),
2533 /*hasSideEffects=*/true);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002534 if (Mapping.InGlobal)
2535 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2536 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002537}
2538
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002539bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2540 // For each NSObject descendant having a +load method, this method is invoked
2541 // by the ObjC runtime before any of the static constructors is called.
2542 // Therefore we need to instrument such methods with a call to __asan_init
2543 // at the beginning in order to initialize our runtime before any access to
2544 // the shadow memory.
2545 // We cannot just ignore these methods, because they may call other
2546 // instrumented functions.
2547 if (F.getName().find(" load]") != std::string::npos) {
James Y Knight13680222019-02-01 02:28:03 +00002548 FunctionCallee AsanInitFunction =
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002549 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002550 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002551 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002552 return true;
2553 }
2554 return false;
2555}
2556
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002557void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2558 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002559 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002560 return;
2561
2562 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002563 if (Mapping.InGlobal) {
2564 if (ClWithIfuncSuppressRemat) {
2565 // An empty inline asm with input reg == output reg.
2566 // An opaque pointer-to-int cast, basically.
2567 InlineAsm *Asm = InlineAsm::get(
2568 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2569 StringRef(""), StringRef("=r,0"),
2570 /*hasSideEffects=*/false);
2571 LocalDynamicShadow =
2572 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2573 } else {
2574 LocalDynamicShadow =
2575 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2576 }
2577 } else {
2578 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2579 kAsanShadowMemoryDynamicAddress, IntptrTy);
James Y Knight14359ef2019-02-01 20:44:24 +00002580 LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002581 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002582}
2583
Reid Kleckner2f907552015-07-21 17:40:14 +00002584void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2585 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2586 // to it as uninteresting. This assumes we haven't started processing allocas
2587 // yet. This check is done up front because iterating the use list in
2588 // isInterestingAlloca would be algorithmically slower.
2589 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2590
2591 // Try to get the declaration of llvm.localescape. If it's not in the module,
2592 // we can exit early.
2593 if (!F.getParent()->getFunction("llvm.localescape")) return;
2594
2595 // Look for a call to llvm.localescape call in the entry block. It can't be in
2596 // any other block.
2597 for (Instruction &I : F.getEntryBlock()) {
2598 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2599 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2600 // We found a call. Mark all the allocas passed in as uninteresting.
2601 for (Value *Arg : II->arg_operands()) {
2602 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2603 assert(AI && AI->isStaticAlloca() &&
2604 "non-static alloca arg to localescape");
2605 ProcessedAllocas[AI] = false;
2606 }
2607 break;
2608 }
2609 }
2610}
2611
Leonard Chan436fb2b2019-02-13 22:22:48 +00002612bool AddressSanitizer::instrumentFunction(Function &F,
2613 const TargetLibraryInfo *TLI) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002614 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002615 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002616 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002617
Etienne Bergeron78582b22016-09-15 15:45:05 +00002618 bool FunctionModified = false;
2619
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002620 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002621 // This function needs to be called even if the function body is not
Fangrui Songf78650a2018-07-30 19:41:25 +00002622 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002623 if (maybeInsertAsanInitAtFunctionEntry(F))
2624 FunctionModified = true;
Fangrui Songf78650a2018-07-30 19:41:25 +00002625
Etienne Bergeron752f8832016-09-14 17:18:37 +00002626 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002627 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002628
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002629 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Etienne Bergeron752f8832016-09-14 17:18:37 +00002630
2631 initializeCallbacks(*F.getParent());
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002632
Reid Kleckner2f907552015-07-21 17:40:14 +00002633 FunctionStateRAII CleanupObj(this);
2634
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002635 maybeInsertDynamicShadowAtFunctionEntry(F);
2636
Reid Kleckner2f907552015-07-21 17:40:14 +00002637 // We can't instrument allocas used with llvm.localescape. Only static allocas
2638 // can be passed to that intrinsic.
2639 markEscapedLocalAllocas(F);
2640
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002641 // We want to instrument every address only once per basic block (unless there
2642 // are calls between uses).
Florian Hahna1cc8482018-06-12 11:16:56 +00002643 SmallPtrSet<Value *, 16> TempsToInstrument;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002644 SmallVector<Instruction *, 16> ToInstrument;
2645 SmallVector<Instruction *, 8> NoReturnCalls;
2646 SmallVector<BasicBlock *, 16> AllBlocks;
2647 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002648 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002649 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002650 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002651 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002652
2653 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002654 for (auto &BB : F) {
2655 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002656 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002657 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002658 for (auto &Inst : BB) {
2659 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002660 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002661 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002662 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002663 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002664 // If we have a mask, skip instrumentation if we've already
2665 // instrumented the full object. But don't add to TempsToInstrument
2666 // because we might get another load/store with a different mask.
2667 if (MaybeMask) {
2668 if (TempsToInstrument.count(Addr))
2669 continue; // We've seen this (whole) temp in the current BB.
2670 } else {
2671 if (!TempsToInstrument.insert(Addr).second)
2672 continue; // We've seen this temp in the current BB.
2673 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002674 }
Pierre Gousseaua833c2b2019-03-28 10:51:24 +00002675 } else if (((ClInvalidPointerPairs || ClInvalidPointerCmp) &&
2676 isInterestingPointerComparison(&Inst)) ||
2677 ((ClInvalidPointerPairs || ClInvalidPointerSub) &&
2678 isInterestingPointerSubtraction(&Inst))) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00002679 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002680 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002681 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002682 // ok, take it.
2683 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002684 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002685 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002686 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002687 // A call inside BB.
2688 TempsToInstrument.clear();
Philip Reames27820f92019-09-04 17:28:48 +00002689 if (CS.doesNotReturn() && !CS->hasMetadata("nosanitize"))
Julian Lettnerf82d8922019-02-02 02:05:16 +00002690 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002691 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002692 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2693 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002694 continue;
2695 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002696 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002697 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002698 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002699 }
2700 }
2701
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002702 bool UseCalls =
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002703 (ClInstrumentationWithCallsThreshold >= 0 &&
2704 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002705 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002706 ObjectSizeOpts ObjSizeOpts;
2707 ObjSizeOpts.RoundToAlign = true;
2708 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002709
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002710 // Instrument.
2711 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002712 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002713 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2714 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002715 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002716 instrumentMop(ObjSizeVis, Inst, UseCalls,
2717 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002718 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002719 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002720 }
2721 NumInstrumented++;
2722 }
2723
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002724 FunctionStackPoisoner FSP(F, *this);
2725 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002726
Julian Lettnerf82d8922019-02-02 02:05:16 +00002727 // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002728 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002729 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002730 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002731 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002732 }
2733
Alexey Samsonova02e6642014-05-29 18:40:48 +00002734 for (auto Inst : PointerComparisonsOrSubtracts) {
2735 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002736 NumInstrumented++;
2737 }
2738
Etienne Bergeron78582b22016-09-15 15:45:05 +00002739 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2740 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002741
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002742 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2743 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002744
Etienne Bergeron78582b22016-09-15 15:45:05 +00002745 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002746}
2747
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002748// Workaround for bug 11395: we don't want to instrument stack in functions
2749// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2750// FIXME: remove once the bug 11395 is fixed.
2751bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2752 if (LongSize != 32) return false;
2753 CallInst *CI = dyn_cast<CallInst>(I);
2754 if (!CI || !CI->isInlineAsm()) return false;
2755 if (CI->getNumArgOperands() <= 5) return false;
2756 // We have inline assembly with quite a few arguments.
2757 return true;
2758}
2759
2760void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2761 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002762 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2763 std::string Suffix = itostr(i);
James Y Knight13680222019-02-01 02:28:03 +00002764 AsanStackMallocFunc[i] = M.getOrInsertFunction(
2765 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2766 AsanStackFreeFunc[i] =
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002767 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
James Y Knight13680222019-02-01 02:28:03 +00002768 IRB.getVoidTy(), IntptrTy, IntptrTy);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002769 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002770 if (ASan.UseAfterScope) {
James Y Knight13680222019-02-01 02:28:03 +00002771 AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
2772 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2773 AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
2774 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002775 }
2776
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002777 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2778 std::ostringstream Name;
2779 Name << kAsanSetShadowPrefix;
2780 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002781 AsanSetShadowFunc[Val] =
James Y Knight13680222019-02-01 02:28:03 +00002782 M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002783 }
2784
James Y Knight13680222019-02-01 02:28:03 +00002785 AsanAllocaPoisonFunc = M.getOrInsertFunction(
2786 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2787 AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
2788 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002789}
2790
Vitaly Buka793913c2016-08-29 18:17:21 +00002791void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2792 ArrayRef<uint8_t> ShadowBytes,
2793 size_t Begin, size_t End,
2794 IRBuilder<> &IRB,
2795 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002796 if (Begin >= End)
2797 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002798
2799 const size_t LargestStoreSizeInBytes =
2800 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2801
2802 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2803
2804 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002805 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2806 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2807 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002808 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002809 if (!ShadowMask[i]) {
2810 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002811 ++i;
2812 continue;
2813 }
2814
2815 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2816 // Fit store size into the range.
2817 while (StoreSizeInBytes > End - i)
2818 StoreSizeInBytes /= 2;
2819
2820 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002821 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002822 while (j <= StoreSizeInBytes / 2)
2823 StoreSizeInBytes /= 2;
2824 }
2825
2826 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002827 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2828 if (IsLittleEndian)
2829 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2830 else
2831 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002832 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002833
2834 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2835 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002836 IRB.CreateAlignedStore(
2837 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002838
2839 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002840 }
2841}
2842
Vitaly Buka793913c2016-08-29 18:17:21 +00002843void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2844 ArrayRef<uint8_t> ShadowBytes,
2845 IRBuilder<> &IRB, Value *ShadowBase) {
2846 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2847}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002848
Vitaly Buka793913c2016-08-29 18:17:21 +00002849void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2850 ArrayRef<uint8_t> ShadowBytes,
2851 size_t Begin, size_t End,
2852 IRBuilder<> &IRB, Value *ShadowBase) {
2853 assert(ShadowMask.size() == ShadowBytes.size());
2854 size_t Done = Begin;
2855 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2856 if (!ShadowMask[i]) {
2857 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002858 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002859 }
2860 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002861 if (!AsanSetShadowFunc[Val])
2862 continue;
2863
2864 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002865 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002866 }
2867
2868 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002869 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002870 IRB.CreateCall(AsanSetShadowFunc[Val],
2871 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2872 ConstantInt::get(IntptrTy, j - i)});
2873 Done = j;
2874 }
2875 }
2876
Vitaly Buka793913c2016-08-29 18:17:21 +00002877 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002878}
2879
Kostya Serebryany6805de52013-09-10 13:16:56 +00002880// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2881// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2882static int StackMallocSizeClass(uint64_t LocalStackSize) {
2883 assert(LocalStackSize <= kMaxStackMallocSize);
2884 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002885 for (int i = 0;; i++, MaxSize *= 2)
2886 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002887 llvm_unreachable("impossible LocalStackSize");
2888}
2889
Vitaly Buka74443f02017-07-18 22:28:03 +00002890void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002891 Instruction *CopyInsertPoint = &F.front().front();
2892 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2893 // Insert after the dynamic shadow location is determined
2894 CopyInsertPoint = CopyInsertPoint->getNextNode();
2895 assert(CopyInsertPoint);
2896 }
2897 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002898 const DataLayout &DL = F.getParent()->getDataLayout();
2899 for (Argument &Arg : F.args()) {
2900 if (Arg.hasByValAttr()) {
2901 Type *Ty = Arg.getType()->getPointerElementType();
2902 unsigned Align = Arg.getParamAlignment();
2903 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2904
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002905 AllocaInst *AI = IRB.CreateAlloca(
2906 Ty, nullptr,
2907 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2908 ".byval");
Vitaly Buka74443f02017-07-18 22:28:03 +00002909 AI->setAlignment(Align);
2910 Arg.replaceAllUsesWith(AI);
2911
2912 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
Daniel Neilsona98d9d92018-02-08 21:26:12 +00002913 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
Vitaly Buka74443f02017-07-18 22:28:03 +00002914 }
2915 }
2916}
2917
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002918PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2919 Value *ValueIfTrue,
2920 Instruction *ThenTerm,
2921 Value *ValueIfFalse) {
2922 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2923 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2924 PHI->addIncoming(ValueIfFalse, CondBlock);
2925 BasicBlock *ThenBlock = ThenTerm->getParent();
2926 PHI->addIncoming(ValueIfTrue, ThenBlock);
2927 return PHI;
2928}
2929
2930Value *FunctionStackPoisoner::createAllocaForLayout(
2931 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2932 AllocaInst *Alloca;
2933 if (Dynamic) {
2934 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2935 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2936 "MyAlloca");
2937 } else {
2938 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2939 nullptr, "MyAlloca");
2940 assert(Alloca->isStaticAlloca());
2941 }
2942 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2943 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2944 Alloca->setAlignment(FrameAlignment);
2945 return IRB.CreatePointerCast(Alloca, IntptrTy);
2946}
2947
Yury Gribov98b18592015-05-28 07:51:49 +00002948void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2949 BasicBlock &FirstBB = *F.begin();
2950 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2951 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2952 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2953 DynamicAllocaLayout->setAlignment(32);
2954}
2955
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002956void FunctionStackPoisoner::processDynamicAllocas() {
2957 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2958 assert(DynamicAllocaPoisonCallVec.empty());
2959 return;
2960 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002961
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002962 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2963 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002964 assert(APC.InsBefore);
2965 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002966 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002967 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002968
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002969 IRBuilder<> IRB(APC.InsBefore);
2970 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002971 // Dynamic allocas will be unpoisoned unconditionally below in
2972 // unpoisonDynamicAllocas.
2973 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002974 }
2975
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002976 // Handle dynamic allocas.
2977 createDynamicAllocasInitStorage();
2978 for (auto &AI : DynamicAllocaVec)
2979 handleDynamicAllocaCall(AI);
2980 unpoisonDynamicAllocas();
2981}
Yury Gribov98b18592015-05-28 07:51:49 +00002982
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002983void FunctionStackPoisoner::processStaticAllocas() {
2984 if (AllocaVec.empty()) {
2985 assert(StaticAllocaPoisonCallVec.empty());
2986 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002987 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002988
Kostya Serebryany6805de52013-09-10 13:16:56 +00002989 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002990 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002991 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002992 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002993
2994 Instruction *InsBefore = AllocaVec[0];
2995 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002996 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002997
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002998 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2999 // debug info is broken, because only entry-block allocas are treated as
3000 // regular stack slots.
3001 auto InsBeforeB = InsBefore->getParent();
3002 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00003003 for (auto *AI : StaticAllocasToMoveUp)
3004 if (AI->getParent() == InsBeforeB)
3005 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00003006
Reid Kleckner2f907552015-07-21 17:40:14 +00003007 // If we have a call to llvm.localescape, keep it in the entry block.
3008 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
3009
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003010 SmallVector<ASanStackVariableDescription, 16> SVD;
3011 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00003012 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003013 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00003014 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00003015 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00003016 AI->getAlignment(),
3017 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00003018 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00003019 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003020 SVD.push_back(D);
3021 }
Vitaly Buka5910a922016-10-18 23:29:52 +00003022
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003023 // Minimal header size (left redzone) is 4 pointers,
3024 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00003025 size_t Granularity = 1ULL << Mapping.Scale;
3026 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00003027 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00003028 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00003029
Vitaly Buka5910a922016-10-18 23:29:52 +00003030 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
3031 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
3032 for (auto &Desc : SVD)
3033 AllocaToSVDMap[Desc.AI] = &Desc;
3034
3035 // Update SVD with information from lifetime intrinsics.
3036 for (const auto &APC : StaticAllocaPoisonCallVec) {
3037 assert(APC.InsBefore);
3038 assert(APC.AI);
3039 assert(ASan.isInterestingAlloca(*APC.AI));
3040 assert(APC.AI->isStaticAlloca());
3041
3042 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
3043 Desc.LifetimeSize = Desc.Size;
3044 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
3045 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
3046 if (LifetimeLoc->getFile() == FnLoc->getFile())
3047 if (unsigned Line = LifetimeLoc->getLine())
3048 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
3049 }
3050 }
3051 }
3052
3053 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003054 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003055 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003056 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
3057 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00003058 bool DoDynamicAlloca = ClDynamicAllocaStack;
3059 // Don't do dynamic alloca or stack malloc if:
3060 // 1) There is inline asm: too often it makes assumptions on which registers
3061 // are available.
3062 // 2) There is a returns_twice call (typically setjmp), which is
3063 // optimization-hostile, and doesn't play well with introduced indirect
3064 // register-relative calculation of local variable addresses.
3065 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3066 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003067
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003068 Value *StaticAlloca =
3069 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3070
3071 Value *FakeStack;
3072 Value *LocalStackBase;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003073 Value *LocalStackBaseAlloca;
Petar Jovanovice85bbf52019-05-20 10:35:57 +00003074 uint8_t DIExprFlags = DIExpression::ApplyOffset;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003075
3076 if (DoStackMalloc) {
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003077 LocalStackBaseAlloca =
3078 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003079 // void *FakeStack = __asan_option_detect_stack_use_after_return
3080 // ? __asan_stack_malloc_N(LocalStackSize)
3081 // : nullptr;
3082 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003083 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3084 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
James Y Knight14359ef2019-02-01 20:44:24 +00003085 Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3086 IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3087 Constant::getNullValue(IRB.getInt32Ty()));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003088 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003089 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00003090 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00003091 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003092 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3093 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3094 Value *FakeStackValue =
3095 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3096 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00003097 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00003098 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003099 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003100 ConstantInt::get(IntptrTy, 0));
3101
3102 Value *NoFakeStack =
3103 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3104 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3105 IRBIf.SetInsertPoint(Term);
3106 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
3107 Value *AllocaValue =
3108 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003109
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003110 IRB.SetInsertPoint(InsBefore);
3111 IRB.SetCurrentDebugLocation(EntryDebugLocation);
3112 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003113 IRB.SetCurrentDebugLocation(EntryDebugLocation);
3114 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
Petar Jovanovice85bbf52019-05-20 10:35:57 +00003115 DIExprFlags |= DIExpression::DerefBefore;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003116 } else {
3117 // void *FakeStack = nullptr;
3118 // void *LocalStackBase = alloca(LocalStackSize);
3119 FakeStack = ConstantInt::get(IntptrTy, 0);
3120 LocalStackBase =
3121 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003122 LocalStackBaseAlloca = LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003123 }
3124
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003125 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003126 for (const auto &Desc : SVD) {
3127 AllocaInst *AI = Desc.AI;
Petar Jovanovice85bbf52019-05-20 10:35:57 +00003128 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, DIExprFlags,
3129 Desc.Offset);
Alexey Samsonov261177a2012-12-04 01:34:23 +00003130 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00003131 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003132 AI->getType());
Alexey Samsonov261177a2012-12-04 01:34:23 +00003133 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003134 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003135
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003136 // The left-most redzone has enough space for at least 4 pointers.
3137 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003138 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3139 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3140 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003141 // Write the frame description constant to redzone[1].
3142 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003143 IRB.CreateAdd(LocalStackBase,
3144 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3145 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00003146 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00003147 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00003148 /*AllowMerging*/ true, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003149 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003150 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003151 // Write the PC to redzone[2].
3152 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003153 IRB.CreateAdd(LocalStackBase,
3154 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3155 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003156 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003157
Vitaly Buka793913c2016-08-29 18:17:21 +00003158 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3159
3160 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003161 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00003162 // As mask we must use most poisoned case: red zones and after scope.
3163 // As bytes we can use either the same or just red zones only.
3164 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3165
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003166 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00003167 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3168
3169 // Poison static allocas near lifetime intrinsics.
3170 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00003171 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00003172 assert(Desc.Offset % L.Granularity == 0);
3173 size_t Begin = Desc.Offset / L.Granularity;
3174 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3175
3176 IRBuilder<> IRB(APC.InsBefore);
3177 copyToShadow(ShadowAfterScope,
3178 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3179 IRB, ShadowBase);
3180 }
3181 }
3182
3183 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00003184 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00003185
Kostya Serebryany530e2072013-12-23 14:15:08 +00003186 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003187 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003188 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003189 // Mark the current frame as retired.
3190 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3191 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003192 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00003193 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003194 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00003195 // // In use-after-return mode, poison the whole stack frame.
3196 // if StackMallocIdx <= 4
3197 // // For small sizes inline the whole thing:
3198 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003199 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00003200 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003201 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00003202 // else
3203 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003204 Value *Cmp =
3205 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00003206 Instruction *ThenTerm, *ElseTerm;
Kostya Serebryany530e2072013-12-23 14:15:08 +00003207 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3208
3209 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003210 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003211 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003212 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3213 kAsanStackUseAfterReturnMagic);
3214 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3215 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003216 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003217 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003218 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3219 Value *SavedFlagPtr = IRBPoison.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003220 IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003221 IRBPoison.CreateStore(
3222 Constant::getNullValue(IRBPoison.getInt8Ty()),
3223 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3224 } else {
3225 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003226 IRBPoison.CreateCall(
3227 AsanStackFreeFunc[StackMallocIdx],
3228 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003229 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003230
3231 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003232 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003233 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003234 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003235 }
3236 }
3237
Kostya Serebryany09959942012-10-19 06:20:53 +00003238 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003239 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003240}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003241
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003242void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003243 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003244 // For now just insert the call to ASan runtime.
3245 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3246 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003247 IRB.CreateCall(
3248 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3249 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003250}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003251
3252// Handling llvm.lifetime intrinsics for a given %alloca:
3253// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3254// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3255// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3256// could be poisoned by previous llvm.lifetime.end instruction, as the
3257// variable may go in and out of scope several times, e.g. in loops).
3258// (3) if we poisoned at least one %alloca in a function,
3259// unpoison the whole stack frame at function exit.
Yury Gribov98b18592015-05-28 07:51:49 +00003260void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003261 IRBuilder<> IRB(AI);
3262
Yury Gribov55441bb2014-11-21 10:29:50 +00003263 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3264 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3265
3266 Value *Zero = Constant::getNullValue(IntptrTy);
3267 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3268 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003269
3270 // Since we need to extend alloca with additional memory to locate
3271 // redzones, and OldSize is number of allocated blocks with
3272 // ElementSize size, get allocated memory size in bytes by
3273 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003274 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003275 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003276 Value *OldSize =
3277 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3278 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003279
3280 // PartialSize = OldSize % 32
3281 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3282
3283 // Misalign = kAllocaRzSize - PartialSize;
3284 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3285
3286 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3287 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3288 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3289
3290 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3291 // Align is added to locate left redzone, PartialPadding for possible
3292 // partial redzone and kAllocaRzSize for right redzone respectively.
3293 Value *AdditionalChunkSize = IRB.CreateAdd(
3294 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3295
3296 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3297
3298 // Insert new alloca with new NewSize and Align params.
3299 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3300 NewAlloca->setAlignment(Align);
3301
3302 // NewAddress = Address + Align
3303 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3304 ConstantInt::get(IntptrTy, Align));
3305
Yury Gribov98b18592015-05-28 07:51:49 +00003306 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003307 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003308
3309 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3310 // for unpoisoning stuff.
3311 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3312
Yury Gribov55441bb2014-11-21 10:29:50 +00003313 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3314
Yury Gribov98b18592015-05-28 07:51:49 +00003315 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003316 AI->replaceAllUsesWith(NewAddressPtr);
3317
Yury Gribov98b18592015-05-28 07:51:49 +00003318 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003319 AI->eraseFromParent();
3320}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003321
3322// isSafeAccess returns true if Addr is always inbounds with respect to its
3323// base object. For example, it is a field access or an array access with
3324// constant inbounds index.
3325bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3326 Value *Addr, uint64_t TypeSize) const {
3327 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3328 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003329 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003330 int64_t Offset = SizeOffset.second.getSExtValue();
3331 // Three checks are required to ensure safety:
3332 // . Offset >= 0 (since the offset is given from the base ptr)
3333 // . Size >= Offset (unsigned)
3334 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003335 return Offset >= 0 && Size >= uint64_t(Offset) &&
3336 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003337}