blob: 5a3f6a12bf0f51bdb08abad6943af625c021bef1 [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();
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000098static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Walter Lee8f1545c2017-11-16 17:03:00 +0000100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
101static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Bill Seurer957a0762017-12-07 22:53:33 +0000103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000104static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000105static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000106static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000107static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000108static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
109static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000110static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000111static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000112static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000113static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000114static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000115
Walter Leecdbb2072018-05-18 04:10:38 +0000116static const uint64_t kMyriadShadowScale = 5;
117static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
118static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
119static const uint64_t kMyriadTagShift = 29;
120static const uint64_t kMyriadDDRTag = 4;
121static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
122
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000123// The shadow memory space is dynamically allocated.
124static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000126static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000127static const size_t kMaxStackMallocSize = 1 << 16; // 64K
128static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
129static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
130
Craig Topperd3a34f82013-07-16 01:17:10 +0000131static const char *const kAsanModuleCtorName = "asan.module_ctor";
132static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000133static const uint64_t kAsanCtorAndDtorPriority = 1;
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
196// This flag may need to be replaced with -f[no-]asan-reads.
197static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198 cl::desc("instrument read instructions"),
199 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000200
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000201static cl::opt<bool> ClInstrumentWrites(
202 "asan-instrument-writes", cl::desc("instrument write instructions"),
203 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000204
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000205static cl::opt<bool> ClInstrumentAtomics(
206 "asan-instrument-atomics",
207 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
208 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000209
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000210static cl::opt<bool> ClAlwaysSlowPath(
211 "asan-always-slow-path",
212 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
213 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000214
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000215static cl::opt<bool> ClForceDynamicShadow(
216 "asan-force-dynamic-shadow",
217 cl::desc("Load shadow address into a local variable for each function"),
218 cl::Hidden, cl::init(false));
219
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000220static cl::opt<bool>
221 ClWithIfunc("asan-with-ifunc",
222 cl::desc("Access dynamic shadow through an ifunc global on "
223 "platforms that support this"),
224 cl::Hidden, cl::init(true));
225
226static cl::opt<bool> ClWithIfuncSuppressRemat(
227 "asan-with-ifunc-suppress-remat",
228 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
229 "it through inline asm in prologue."),
230 cl::Hidden, cl::init(true));
231
Kostya Serebryany874dae62012-07-16 16:15:40 +0000232// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000233// in any given BB. Normally, this should be set to unlimited (INT_MAX),
234// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
235// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000236static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
237 "asan-max-ins-per-bb", cl::init(10000),
238 cl::desc("maximal number of instructions to instrument in any given BB"),
239 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000242static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
243 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000244static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
245 "asan-max-inline-poisoning-size",
246 cl::desc(
247 "Inline shadow poisoning for blocks up to the given size in bytes."),
248 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000249
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000250static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000251 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000252 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000253
Vitaly Buka74443f02017-07-18 22:28:03 +0000254static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
255 cl::desc("Create redzones for byval "
256 "arguments (extra copy "
257 "required)"), cl::Hidden,
258 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000259
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000260static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
261 cl::desc("Check stack-use-after-scope"),
262 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000263
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000264// This flag may need to be replaced with -f[no]asan-globals.
265static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000266 cl::desc("Handle global objects"), cl::Hidden,
267 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000268
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000269static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000270 cl::desc("Handle C++ initializer order"),
271 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000272
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000273static cl::opt<bool> ClInvalidPointerPairs(
274 "asan-detect-invalid-pointer-pair",
275 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
276 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000277
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000278static cl::opt<unsigned> ClRealignStack(
279 "asan-realign-stack",
280 cl::desc("Realign stack to the value of this flag (power of two)"),
281 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000282
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000283static cl::opt<int> ClInstrumentationWithCallsThreshold(
284 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000285 cl::desc(
286 "If the function being instrumented contains more than "
287 "this number of memory accesses, use callbacks instead of "
288 "inline checks (-1 means never use callbacks)."),
289 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000290
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000291static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000292 "asan-memory-access-callback-prefix",
293 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
294 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000295
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000296static cl::opt<bool>
297 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
298 cl::desc("instrument dynamic allocas"),
299 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000300
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000301static cl::opt<bool> ClSkipPromotableAllocas(
302 "asan-skip-promotable-allocas",
303 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
304 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000305
306// These flags allow to change the shadow mapping.
307// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000308// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000309
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000310static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311 cl::desc("scale of asan shadow mapping"),
312 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000313
Ryan Govostes6194ae62016-05-06 11:22:11 +0000314static cl::opt<unsigned long long> ClMappingOffset(
315 "asan-mapping-offset",
316 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
317 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000318
319// Optimization flags. Not user visible, used mostly for testing
320// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000321
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000322static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
323 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000324
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000325static cl::opt<bool> ClOptSameTemp(
326 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
327 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000328
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000329static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000330 cl::desc("Don't instrument scalar globals"),
331 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000332
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000333static cl::opt<bool> ClOptStack(
334 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
335 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000336
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000337static cl::opt<bool> ClDynamicAllocaStack(
338 "asan-stack-dynamic-alloca",
339 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000340 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000341
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000342static cl::opt<uint32_t> ClForceExperiment(
343 "asan-force-experiment",
344 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
345 cl::init(0));
346
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000347static cl::opt<bool>
Vitaly Bukad6bab092018-12-04 23:17:41 +0000348 ClUsePrivateAlias("asan-use-private-alias",
349 cl::desc("Use private aliases for global variables"),
350 cl::Hidden, cl::init(false));
351
352static cl::opt<bool>
353 ClUseOdrIndicator("asan-use-odr-indicator",
354 cl::desc("Use odr indicators to improve ODR reporting"),
355 cl::Hidden, cl::init(false));
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000356
Ryan Govostese51401b2016-07-05 21:53:08 +0000357static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000358 ClUseGlobalsGC("asan-globals-live-support",
359 cl::desc("Use linker features to support dead "
360 "code stripping of globals"),
361 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000362
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000363// This is on by default even though there is a bug in gold:
364// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
365static cl::opt<bool>
366 ClWithComdat("asan-with-comdat",
367 cl::desc("Place ASan constructors in comdat sections"),
368 cl::Hidden, cl::init(true));
369
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000370// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000371
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000372static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
373 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000374
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000375static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
376 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000377
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000378static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
379 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000380
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000381static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
382 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000383
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000384static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385 cl::Hidden, cl::init(-1));
386
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000387STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
388STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000389STATISTIC(NumOptimizedAccessesToGlobalVar,
390 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000391STATISTIC(NumOptimizedAccessesToStackVar,
392 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000393
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000394namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000395
Alexey Samsonov1345d352013-01-16 13:23:28 +0000396/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000397/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000398/// If InGlobal is true, then
399/// extern char __asan_shadow[];
400/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000401struct ShadowMapping {
402 int Scale;
403 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000404 bool OrShadowOffset;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000405 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000406};
407
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000408} // end anonymous namespace
409
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000410static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
411 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000412 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000413 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000414 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000415 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000416 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000417 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000418 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
419 TargetTriple.getArch() == Triple::ppc64le;
420 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
421 bool IsX86 = TargetTriple.getArch() == Triple::x86;
422 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000423 bool IsMIPS32 = TargetTriple.isMIPS32();
424 bool IsMIPS64 = TargetTriple.isMIPS64();
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000425 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000426 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000427 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000428 bool IsFuchsia = TargetTriple.isOSFuchsia();
Walter Leecdbb2072018-05-18 04:10:38 +0000429 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000430
431 ShadowMapping Mapping;
432
Walter Leecdbb2072018-05-18 04:10:38 +0000433 Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
Walter Lee8f1545c2017-11-16 17:03:00 +0000434 if (ClMappingScale.getNumOccurrences() > 0) {
435 Mapping.Scale = ClMappingScale;
436 }
437
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000438 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000439 if (IsAndroid)
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000440 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000441 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000442 Mapping.Offset = kMIPS32_ShadowOffset32;
443 else if (IsFreeBSD)
444 Mapping.Offset = kFreeBSD_ShadowOffset32;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000445 else if (IsNetBSD)
446 Mapping.Offset = kNetBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000447 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000448 // If we're targeting iOS and x86, the binary is built for iOS simulator.
449 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000450 else if (IsWindows)
451 Mapping.Offset = kWindowsShadowOffset32;
Walter Leecdbb2072018-05-18 04:10:38 +0000452 else if (IsMyriad) {
453 uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
454 (kMyriadMemorySize32 >> Mapping.Scale));
455 Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
456 }
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000457 else
458 Mapping.Offset = kDefaultShadowOffset32;
459 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000460 // Fuchsia is always PIE, which means that the beginning of the address
461 // space is always available.
462 if (IsFuchsia)
463 Mapping.Offset = 0;
464 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000465 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000466 else if (IsSystemZ)
467 Mapping.Offset = kSystemZ_ShadowOffset64;
John Baldwinc5d7e042018-08-01 22:51:13 +0000468 else if (IsFreeBSD && !IsMIPS64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000469 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000470 else if (IsNetBSD) {
471 if (IsKasan)
472 Mapping.Offset = kNetBSDKasan_ShadowOffset64;
473 else
474 Mapping.Offset = kNetBSD_ShadowOffset64;
475 } else if (IsPS4CPU)
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000476 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000477 else if (IsLinux && IsX86_64) {
478 if (IsKasan)
479 Mapping.Offset = kLinuxKasan_ShadowOffset64;
480 else
Walter Lee8f1545c2017-11-16 17:03:00 +0000481 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
482 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
Etienne Bergeron70684f92016-06-21 15:07:29 +0000483 } else if (IsWindows && IsX86_64) {
484 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000485 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000486 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000487 else if (IsIOS)
488 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000489 // We are using dynamic shadow offset on the 64-bit devices.
490 Mapping.Offset =
491 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000492 else if (IsAArch64)
493 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000494 else
495 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000496 }
497
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000498 if (ClForceDynamicShadow) {
499 Mapping.Offset = kDynamicShadowSentinel;
500 }
501
Ryan Govostes3f37df02016-05-06 10:25:22 +0000502 if (ClMappingOffset.getNumOccurrences() > 0) {
503 Mapping.Offset = ClMappingOffset;
504 }
505
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000506 // OR-ing shadow offset if more efficient (at least on x86) if the offset
507 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000508 // offset is not necessary 1/8-th of the address space. On SystemZ,
509 // we could OR the constant in a single instruction, but it's more
510 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000511 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
512 !(Mapping.Offset & (Mapping.Offset - 1)) &&
513 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000514 bool IsAndroidWithIfuncSupport =
515 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
516 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000517
Alexey Samsonov1345d352013-01-16 13:23:28 +0000518 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000519}
520
Alexey Samsonov1345d352013-01-16 13:23:28 +0000521static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000522 // Redzone used for stack and globals is at least 32 bytes.
523 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000524 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000525}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000526
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000527namespace {
528
Leonard Chan436fb2b2019-02-13 22:22:48 +0000529/// Module analysis for getting various metadata about the module.
530class ASanGlobalsMetadataWrapperPass : public ModulePass {
531public:
Leonard Chaneebecb32018-10-26 22:51:51 +0000532 static char ID;
533
Leonard Chan436fb2b2019-02-13 22:22:48 +0000534 ASanGlobalsMetadataWrapperPass() : ModulePass(ID) {
535 initializeASanGlobalsMetadataWrapperPassPass(
536 *PassRegistry::getPassRegistry());
537 }
538
539 bool runOnModule(Module &M) override {
540 GlobalsMD = GlobalsMetadata(M);
541 return false;
Leonard Chaneebecb32018-10-26 22:51:51 +0000542 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000543
Leonard Chaneebecb32018-10-26 22:51:51 +0000544 StringRef getPassName() const override {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000545 return "ASanGlobalsMetadataWrapperPass";
Leonard Chaneebecb32018-10-26 22:51:51 +0000546 }
547
548 void getAnalysisUsage(AnalysisUsage &AU) const override {
Leonard Chan436fb2b2019-02-13 22:22:48 +0000549 AU.setPreservesAll();
550 }
551
552 GlobalsMetadata &getGlobalsMD() { return GlobalsMD; }
553
554private:
555 GlobalsMetadata GlobalsMD;
556};
557
558char ASanGlobalsMetadataWrapperPass::ID = 0;
559
560/// AddressSanitizer: instrument the code in module to find memory bugs.
561struct AddressSanitizer {
562 AddressSanitizer(Module &M, GlobalsMetadata &GlobalsMD,
563 bool CompileKernel = false, bool Recover = false,
564 bool UseAfterScope = false)
565 : UseAfterScope(UseAfterScope || ClUseAfterScope), GlobalsMD(GlobalsMD) {
566 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
567 this->CompileKernel =
568 ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
569
570 C = &(M.getContext());
571 LongSize = M.getDataLayout().getPointerSizeInBits();
572 IntptrTy = Type::getIntNTy(*C, LongSize);
573 TargetTriple = Triple(M.getTargetTriple());
574
575 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
Yury Gribov3ae427d2014-12-01 08:47:58 +0000576 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000577
Vitaly Buka21a9e572016-07-28 22:50:50 +0000578 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000579 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000580 if (AI.isArrayAllocation()) {
581 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000582 assert(CI && "non-constant array size");
583 ArraySize = CI->getZExtValue();
584 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000585 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000586 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000587 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000588 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000589 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000590
Anna Zaks8ed1d812015-02-27 03:12:36 +0000591 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000592 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000593
Anna Zaks8ed1d812015-02-27 03:12:36 +0000594 /// If it is an interesting memory access, return the PointerOperand
595 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000596 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
597 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000598 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000599 uint64_t *TypeSize, unsigned *Alignment,
600 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000601
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000602 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000603 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000604 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000605 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
606 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000607 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000608 void instrumentUnusualSizeOrAlignment(Instruction *I,
609 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000610 uint32_t TypeSize, bool IsWrite,
611 Value *SizeArgument, bool UseCalls,
612 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000613 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
614 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000615 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000616 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000617 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000618 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000619 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Leonard Chan436fb2b2019-02-13 22:22:48 +0000620 bool instrumentFunction(Function &F, const TargetLibraryInfo *TLI);
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000621 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000622 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000623 void markEscapedLocalAllocas(Function &F);
Yury Gribov3ae427d2014-12-01 08:47:58 +0000624
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000625private:
626 friend struct FunctionStackPoisoner;
627
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000628 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000629
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000630 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000631 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000632 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
633 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000634
Reid Kleckner2f907552015-07-21 17:40:14 +0000635 /// Helper to cleanup per-function state.
636 struct FunctionStateRAII {
637 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000638
Reid Kleckner2f907552015-07-21 17:40:14 +0000639 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
640 assert(Pass->ProcessedAllocas.empty() &&
641 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000642 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000643 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000644
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000645 ~FunctionStateRAII() {
646 Pass->LocalDynamicShadow = nullptr;
647 Pass->ProcessedAllocas.clear();
648 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000649 };
650
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000651 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000652 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000653 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000654 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000655 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000656 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000657 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000658 ShadowMapping Mapping;
James Y Knight13680222019-02-01 02:28:03 +0000659 FunctionCallee AsanHandleNoReturnFunc;
660 FunctionCallee AsanPtrCmpFunction, AsanPtrSubFunction;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000661 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000662
663 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
James Y Knight13680222019-02-01 02:28:03 +0000664 FunctionCallee AsanErrorCallback[2][2][kNumberOfAccessSizes];
665 FunctionCallee AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000666
667 // These arrays is indexed by AccessIsWrite and Experiment.
James Y Knight13680222019-02-01 02:28:03 +0000668 FunctionCallee AsanErrorCallbackSized[2][2];
669 FunctionCallee AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000670
James Y Knight13680222019-02-01 02:28:03 +0000671 FunctionCallee AsanMemmove, AsanMemcpy, AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000672 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000673 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000674 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000675 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000676};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000677
Leonard Chan436fb2b2019-02-13 22:22:48 +0000678class AddressSanitizerLegacyPass : public FunctionPass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000679public:
Leonard Chaneebecb32018-10-26 22:51:51 +0000680 static char ID;
681
Leonard Chan436fb2b2019-02-13 22:22:48 +0000682 explicit AddressSanitizerLegacyPass(bool CompileKernel = false,
683 bool Recover = false,
684 bool UseAfterScope = false)
685 : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
686 UseAfterScope(UseAfterScope) {
687 initializeAddressSanitizerLegacyPassPass(*PassRegistry::getPassRegistry());
688 }
689
690 StringRef getPassName() const override {
691 return "AddressSanitizerFunctionPass";
692 }
693
694 void getAnalysisUsage(AnalysisUsage &AU) const override {
695 AU.addRequired<ASanGlobalsMetadataWrapperPass>();
696 AU.addRequired<TargetLibraryInfoWrapperPass>();
697 }
698
699 bool runOnFunction(Function &F) override {
700 GlobalsMetadata &GlobalsMD =
701 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
702 const TargetLibraryInfo *TLI =
703 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
704 AddressSanitizer ASan(*F.getParent(), GlobalsMD, CompileKernel, Recover,
705 UseAfterScope);
706 return ASan.instrumentFunction(F, TLI);
707 }
708
709private:
710 bool CompileKernel;
711 bool Recover;
712 bool UseAfterScope;
713};
714
715class ModuleAddressSanitizer {
716public:
717 ModuleAddressSanitizer(Module &M, GlobalsMetadata &GlobalsMD,
718 bool CompileKernel = false, bool Recover = false,
719 bool UseGlobalsGC = true, bool UseOdrIndicator = false)
720 : GlobalsMD(GlobalsMD), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
Vitaly Buka8076c572018-12-05 01:44:31 +0000721 // Enable aliases as they should have no downside with ODR indicators.
722 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
723 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000724 // Not a typo: ClWithComdat is almost completely pointless without
725 // ClUseGlobalsGC (because then it only works on modules without
726 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
727 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
728 // argument is designed as workaround. Therefore, disable both
729 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
730 // do globals-gc.
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000731 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
Vitaly Buka8076c572018-12-05 01:44:31 +0000732 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
733 this->CompileKernel =
734 ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
Leonard Chan436fb2b2019-02-13 22:22:48 +0000735
736 C = &(M.getContext());
737 int LongSize = M.getDataLayout().getPointerSizeInBits();
738 IntptrTy = Type::getIntNTy(*C, LongSize);
739 TargetTriple = Triple(M.getTargetTriple());
740 Mapping = getShadowMapping(TargetTriple, LongSize, this->CompileKernel);
Vitaly Buka537cfc02018-12-04 00:36:14 +0000741 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000742
Leonard Chan436fb2b2019-02-13 22:22:48 +0000743 bool instrumentModule(Module &);
Alexey Samsonov261177a2012-12-04 01:34:23 +0000744
Mehdi Amini117296c2016-10-01 02:56:57 +0000745private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000746 void initializeCallbacks(Module &M);
747
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000748 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000749 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
750 ArrayRef<GlobalVariable *> ExtendedGlobals,
751 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000752 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
753 ArrayRef<GlobalVariable *> ExtendedGlobals,
754 ArrayRef<Constant *> MetadataInitializers,
755 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000756 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
757 ArrayRef<GlobalVariable *> ExtendedGlobals,
758 ArrayRef<Constant *> MetadataInitializers);
759 void
760 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
761 ArrayRef<GlobalVariable *> ExtendedGlobals,
762 ArrayRef<Constant *> MetadataInitializers);
763
764 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
765 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000766 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
767 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000768 IRBuilder<> CreateAsanModuleDtor(Module &M);
769
Kostya Serebryany20a79972012-11-22 03:18:50 +0000770 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000771 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000772 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000773 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000774 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000775 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000776 return RedzoneSizeForScale(Mapping.Scale);
777 }
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000778 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000779
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000780 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000781 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000782 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000783 bool UseGlobalsGC;
Vitaly Buka8076c572018-12-05 01:44:31 +0000784 bool UsePrivateAlias;
785 bool UseOdrIndicator;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000786 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000787 Type *IntptrTy;
788 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000789 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000790 ShadowMapping Mapping;
James Y Knight13680222019-02-01 02:28:03 +0000791 FunctionCallee AsanPoisonGlobals;
792 FunctionCallee AsanUnpoisonGlobals;
793 FunctionCallee AsanRegisterGlobals;
794 FunctionCallee AsanUnregisterGlobals;
795 FunctionCallee AsanRegisterImageGlobals;
796 FunctionCallee AsanUnregisterImageGlobals;
797 FunctionCallee AsanRegisterElfGlobals;
798 FunctionCallee AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000799
800 Function *AsanCtorFunction = nullptr;
801 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000802};
803
Leonard Chan436fb2b2019-02-13 22:22:48 +0000804class ModuleAddressSanitizerLegacyPass : public ModulePass {
805public:
806 static char ID;
807
808 explicit ModuleAddressSanitizerLegacyPass(bool CompileKernel = false,
809 bool Recover = false,
810 bool UseGlobalGC = true,
811 bool UseOdrIndicator = false)
812 : ModulePass(ID), CompileKernel(CompileKernel), Recover(Recover),
813 UseGlobalGC(UseGlobalGC), UseOdrIndicator(UseOdrIndicator) {
814 initializeModuleAddressSanitizerLegacyPassPass(
815 *PassRegistry::getPassRegistry());
816 }
817
818 StringRef getPassName() const override { return "ModuleAddressSanitizer"; }
819
820 void getAnalysisUsage(AnalysisUsage &AU) const override {
821 AU.addRequired<ASanGlobalsMetadataWrapperPass>();
822 }
823
824 bool runOnModule(Module &M) override {
825 GlobalsMetadata &GlobalsMD =
826 getAnalysis<ASanGlobalsMetadataWrapperPass>().getGlobalsMD();
827 ModuleAddressSanitizer ASanModule(M, GlobalsMD, CompileKernel, Recover,
828 UseGlobalGC, UseOdrIndicator);
829 return ASanModule.instrumentModule(M);
830 }
831
832private:
833 bool CompileKernel;
834 bool Recover;
835 bool UseGlobalGC;
836 bool UseOdrIndicator;
837};
838
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000839// Stack poisoning does not play well with exception handling.
840// When an exception is thrown, we essentially bypass the code
841// that unpoisones the stack. This is why the run-time library has
842// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
843// stack in the interceptor. This however does not work inside the
844// actual function which catches the exception. Most likely because the
845// compiler hoists the load of the shadow value somewhere too high.
846// This causes asan to report a non-existing bug on 453.povray.
847// It sounds like an LLVM bug.
848struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
849 Function &F;
850 AddressSanitizer &ASan;
851 DIBuilder DIB;
852 LLVMContext *C;
853 Type *IntptrTy;
854 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000855 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000856
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000857 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000858 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000859 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000860 unsigned StackAlignment;
861
James Y Knight13680222019-02-01 02:28:03 +0000862 FunctionCallee AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
863 AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
864 FunctionCallee AsanSetShadowFunc[0x100] = {};
865 FunctionCallee AsanPoisonStackMemoryFunc, AsanUnpoisonStackMemoryFunc;
866 FunctionCallee AsanAllocaPoisonFunc, AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000867
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000868 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
869 struct AllocaPoisonCall {
870 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000871 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000872 uint64_t Size;
873 bool DoPoison;
874 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000875 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
876 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000877
Yury Gribov98b18592015-05-28 07:51:49 +0000878 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
879 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
880 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000881 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000882
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000883 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000884 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000885 AllocaForValueMapTy AllocaForValue;
886
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000887 bool HasNonEmptyInlineAsm = false;
888 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000889 std::unique_ptr<CallInst> EmptyInlineAsm;
890
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000891 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Leonard Chan436fb2b2019-02-13 22:22:48 +0000892 : F(F), ASan(ASan), DIB(*F.getParent(), /*AllowUnresolved*/ false),
893 C(ASan.C), IntptrTy(ASan.IntptrTy),
894 IntptrPtrTy(PointerType::get(IntptrTy, 0)), Mapping(ASan.Mapping),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000895 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000896 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000897
898 bool runOnFunction() {
899 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000900
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000901 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000902 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000903
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000904 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000905 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000906
Yury Gribov55441bb2014-11-21 10:29:50 +0000907 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000908
909 initializeCallbacks(*F.getParent());
910
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000911 processDynamicAllocas();
912 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000913
914 if (ClDebugStack) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000915 LLVM_DEBUG(dbgs() << F);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000916 }
917 return true;
918 }
919
Vitaly Buka74443f02017-07-18 22:28:03 +0000920 // Arguments marked with the "byval" attribute are implicitly copied without
921 // using an alloca instruction. To produce redzones for those arguments, we
922 // copy them a second time into memory allocated with an alloca instruction.
923 void copyArgsPassedByValToAllocas();
924
Yury Gribov55441bb2014-11-21 10:29:50 +0000925 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000926 // poisoned red zones around all of them.
927 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000928 void processStaticAllocas();
929 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000930
Yury Gribov98b18592015-05-28 07:51:49 +0000931 void createDynamicAllocasInitStorage();
932
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000933 // ----------------------- Visitors.
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000934 /// Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000935 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000936
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000937 /// Collect all Resume instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000938 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
939
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000940 /// Collect all CatchReturnInst instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000941 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
942
Yury Gribov98b18592015-05-28 07:51:49 +0000943 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
944 Value *SavedStack) {
945 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000946 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
947 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
948 // need to adjust extracted SP to compute the address of the most recent
949 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
950 // this purpose.
951 if (!isa<ReturnInst>(InstBefore)) {
952 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
953 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
954 {IntptrTy});
955
956 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
957
958 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
959 DynamicAreaOffset);
960 }
961
James Y Knight14359ef2019-02-01 20:44:24 +0000962 IRB.CreateCall(
963 AsanAllocasUnpoisonFunc,
964 {IRB.CreateLoad(IntptrTy, DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000965 }
966
Yury Gribov55441bb2014-11-21 10:29:50 +0000967 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000968 void unpoisonDynamicAllocas() {
969 for (auto &Ret : RetVec)
970 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000971
Yury Gribov98b18592015-05-28 07:51:49 +0000972 for (auto &StackRestoreInst : StackRestoreVec)
973 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
974 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000975 }
976
Yury Gribov55441bb2014-11-21 10:29:50 +0000977 // Deploy and poison redzones around dynamic alloca call. To do this, we
978 // should replace this call with another one with changed parameters and
979 // replace all its uses with new address, so
980 // addr = alloca type, old_size, align
981 // is replaced by
982 // new_size = (old_size + additional_size) * sizeof(type)
983 // tmp = alloca i8, new_size, max(align, 32)
984 // addr = tmp + 32 (first 32 bytes are for the left redzone).
985 // Additional_size is added to make new memory allocation contain not only
986 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000987 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000988
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000989 /// Collect Alloca instructions we want (and can) handle.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000990 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000991 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000992 if (AI.isStaticAlloca()) {
993 // Skip over allocas that are present *before* the first instrumented
994 // alloca, we don't want to move those around.
995 if (AllocaVec.empty())
996 return;
997
998 StaticAllocasToMoveUp.push_back(&AI);
999 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001000 return;
1001 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001002
1003 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +00001004 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +00001005 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +00001006 else
1007 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001008 }
1009
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001010 /// Collect lifetime intrinsic calls to check for use-after-scope
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001011 /// errors.
1012 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001013 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +00001014 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +00001015 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001016 if (!ASan.UseAfterScope)
1017 return;
Vedant Kumarb264d692018-12-21 21:49:40 +00001018 if (!II.isLifetimeStartOrEnd())
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001019 return;
1020 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1021 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
1022 // If size argument is undefined, don't do anything.
1023 if (Size->isMinusOne()) return;
1024 // Check that size doesn't saturate uint64_t and can
1025 // be stored in IntptrTy.
1026 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1027 if (SizeValue == ~0ULL ||
1028 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1029 return;
1030 // Find alloca instruction that corresponds to llvm.lifetime argument.
1031 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +00001032 if (!AI || !ASan.isInterestingAlloca(*AI))
1033 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001034 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +00001035 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +00001036 if (AI->isStaticAlloca())
1037 StaticAllocaPoisonCallVec.push_back(APC);
1038 else if (ClInstrumentDynamicAllocas)
1039 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001040 }
1041
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001042 void visitCallSite(CallSite CS) {
1043 Instruction *I = CS.getInstruction();
1044 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00001045 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1046 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1047 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001048 HasReturnsTwiceCall |= CI->canReturnTwice();
1049 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001050 }
1051
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001052 // ---------------------- Helpers.
1053 void initializeCallbacks(Module &M);
1054
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001055 /// Finds alloca where the value comes from.
1056 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001057
1058 // Copies bytes from ShadowBytes into shadow memory for indexes where
1059 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1060 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1061 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1062 IRBuilder<> &IRB, Value *ShadowBase);
1063 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1064 size_t Begin, size_t End, IRBuilder<> &IRB,
1065 Value *ShadowBase);
1066 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1067 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1068 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1069
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001070 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001071
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001072 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1073 bool Dynamic);
1074 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1075 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001076};
1077
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001078} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001079
Leonard Chan436fb2b2019-02-13 22:22:48 +00001080void LocationMetadata::parse(MDNode *MDN) {
1081 assert(MDN->getNumOperands() == 3);
1082 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
1083 Filename = DIFilename->getString();
1084 LineNo = mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
1085 ColumnNo =
1086 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
1087}
1088
1089// FIXME: It would be cleaner to instead attach relevant metadata to the globals
1090// we want to sanitize instead and reading this metadata on each pass over a
1091// function instead of reading module level metadata at first.
1092GlobalsMetadata::GlobalsMetadata(Module &M) {
1093 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
1094 if (!Globals)
1095 return;
1096 for (auto MDN : Globals->operands()) {
1097 // Metadata node contains the global and the fields of "Entry".
1098 assert(MDN->getNumOperands() == 5);
1099 auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
1100 // The optimizer may optimize away a global entirely.
1101 if (!V)
1102 continue;
1103 auto *StrippedV = V->stripPointerCasts();
1104 auto *GV = dyn_cast<GlobalVariable>(StrippedV);
1105 if (!GV)
1106 continue;
1107 // We can already have an entry for GV if it was merged with another
1108 // global.
1109 Entry &E = Entries[GV];
1110 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
1111 E.SourceLoc.parse(Loc);
1112 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
1113 E.Name = Name->getString();
1114 ConstantInt *IsDynInit = mdconst::extract<ConstantInt>(MDN->getOperand(3));
1115 E.IsDynInit |= IsDynInit->isOne();
1116 ConstantInt *IsBlacklisted =
1117 mdconst::extract<ConstantInt>(MDN->getOperand(4));
1118 E.IsBlacklisted |= IsBlacklisted->isOne();
1119 }
1120}
1121
1122AnalysisKey ASanGlobalsMetadataAnalysis::Key;
1123
1124GlobalsMetadata ASanGlobalsMetadataAnalysis::run(Module &M,
1125 ModuleAnalysisManager &AM) {
1126 return GlobalsMetadata(M);
1127}
1128
1129AddressSanitizerPass::AddressSanitizerPass(bool CompileKernel, bool Recover,
1130 bool UseAfterScope)
1131 : CompileKernel(CompileKernel), Recover(Recover),
1132 UseAfterScope(UseAfterScope) {}
1133
1134PreservedAnalyses AddressSanitizerPass::run(Function &F,
1135 AnalysisManager<Function> &AM) {
1136 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
1137 auto &MAM = MAMProxy.getManager();
1138 Module &M = *F.getParent();
1139 if (auto *R = MAM.getCachedResult<ASanGlobalsMetadataAnalysis>(M)) {
1140 const TargetLibraryInfo *TLI = &AM.getResult<TargetLibraryAnalysis>(F);
1141 AddressSanitizer Sanitizer(M, *R, CompileKernel, Recover, UseAfterScope);
1142 if (Sanitizer.instrumentFunction(F, TLI))
1143 return PreservedAnalyses::none();
1144 return PreservedAnalyses::all();
1145 }
1146
1147 report_fatal_error(
1148 "The ASanGlobalsMetadataAnalysis is required to run before "
1149 "AddressSanitizer can run");
1150 return PreservedAnalyses::all();
1151}
1152
1153ModuleAddressSanitizerPass::ModuleAddressSanitizerPass(bool CompileKernel,
1154 bool Recover,
1155 bool UseGlobalGC,
1156 bool UseOdrIndicator)
1157 : CompileKernel(CompileKernel), Recover(Recover), UseGlobalGC(UseGlobalGC),
1158 UseOdrIndicator(UseOdrIndicator) {}
1159
1160PreservedAnalyses ModuleAddressSanitizerPass::run(Module &M,
1161 AnalysisManager<Module> &AM) {
1162 GlobalsMetadata &GlobalsMD = AM.getResult<ASanGlobalsMetadataAnalysis>(M);
1163 ModuleAddressSanitizer Sanitizer(M, GlobalsMD, CompileKernel, Recover,
1164 UseGlobalGC, UseOdrIndicator);
1165 if (Sanitizer.instrumentModule(M))
1166 return PreservedAnalyses::none();
1167 return PreservedAnalyses::all();
1168}
1169
1170INITIALIZE_PASS(ASanGlobalsMetadataWrapperPass, "asan-globals-md",
1171 "Read metadata to mark which globals should be instrumented "
1172 "when running ASan.",
1173 false, true);
1174
1175char AddressSanitizerLegacyPass::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001176
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001177INITIALIZE_PASS_BEGIN(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001178 AddressSanitizerLegacyPass, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001179 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1180 false)
Leonard Chan436fb2b2019-02-13 22:22:48 +00001181INITIALIZE_PASS_DEPENDENCY(ASanGlobalsMetadataWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001182INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001183INITIALIZE_PASS_END(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001184 AddressSanitizerLegacyPass, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001185 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1186 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001187
Yury Gribovd7731982015-11-11 10:36:49 +00001188FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001189 bool Recover,
1190 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001191 assert(!CompileKernel || Recover);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001192 return new AddressSanitizerLegacyPass(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001193}
1194
Leonard Chan436fb2b2019-02-13 22:22:48 +00001195char ModuleAddressSanitizerLegacyPass::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001196
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001197INITIALIZE_PASS(
Leonard Chan436fb2b2019-02-13 22:22:48 +00001198 ModuleAddressSanitizerLegacyPass, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001199 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001200 "ModulePass",
1201 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001202
Leonard Chan436fb2b2019-02-13 22:22:48 +00001203ModulePass *llvm::createModuleAddressSanitizerLegacyPassPass(
1204 bool CompileKernel, bool Recover, bool UseGlobalsGC, bool UseOdrIndicator) {
Yury Gribovd7731982015-11-11 10:36:49 +00001205 assert(!CompileKernel || Recover);
Leonard Chan436fb2b2019-02-13 22:22:48 +00001206 return new ModuleAddressSanitizerLegacyPass(CompileKernel, Recover,
1207 UseGlobalsGC, UseOdrIndicator);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001208}
1209
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001210static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001211 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001212 assert(Res < kNumberOfAccessSizes);
1213 return Res;
1214}
1215
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001216/// Create a global describing a source location.
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001217static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1218 LocationMetadata MD) {
1219 Constant *LocData[] = {
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00001220 createPrivateGlobalForString(M, MD.Filename, true, kAsanGenPrefix),
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001221 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1222 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1223 };
1224 auto LocStruct = ConstantStruct::getAnon(LocData);
1225 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1226 GlobalValue::PrivateLinkage, LocStruct,
1227 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001228 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001229 return GV;
1230}
1231
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001232/// Check if \p G has been created by a trusted compiler pass.
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001233static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
Reid Kleckner85a8c122018-08-20 23:35:45 +00001234 // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1235 if (G->getName().startswith("llvm."))
1236 return true;
1237
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001238 // Do not instrument asan globals.
1239 if (G->getName().startswith(kAsanGenPrefix) ||
1240 G->getName().startswith(kSanCovGenPrefix) ||
1241 G->getName().startswith(kODRGenPrefix))
1242 return true;
1243
1244 // Do not instrument gcov counter arrays.
1245 if (G->getName() == "__llvm_gcov_ctr")
1246 return true;
1247
1248 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001249}
1250
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001251Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1252 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001253 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001254 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001255 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001256 Value *ShadowBase;
1257 if (LocalDynamicShadow)
1258 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001259 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001260 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1261 if (Mapping.OrShadowOffset)
1262 return IRB.CreateOr(Shadow, ShadowBase);
1263 else
1264 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001265}
1266
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001267// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001268void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1269 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001270 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001271 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001272 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001273 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1274 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1275 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001276 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001277 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001278 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001279 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1280 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1281 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001282 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001283 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001284}
1285
Anna Zaks8ed1d812015-02-27 03:12:36 +00001286/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001287bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001288 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1289
1290 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1291 return PreviouslySeenAllocaInfo->getSecond();
1292
Yury Gribov98b18592015-05-28 07:51:49 +00001293 bool IsInteresting =
1294 (AI.getAllocatedType()->isSized() &&
1295 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001296 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001297 // We are only interested in allocas not promotable to registers.
1298 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001299 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1300 // inalloca allocas are not treated as static, and we don't want
1301 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001302 !AI.isUsedWithInAlloca() &&
1303 // swifterror allocas are register promoted by ISel
1304 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001305
1306 ProcessedAllocas[&AI] = IsInteresting;
1307 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001308}
1309
Anna Zaks8ed1d812015-02-27 03:12:36 +00001310Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1311 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001312 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001313 unsigned *Alignment,
1314 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001315 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001316 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001317
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001318 // Do not instrument the load fetching the dynamic shadow address.
1319 if (LocalDynamicShadow == I)
1320 return nullptr;
1321
Anna Zaks8ed1d812015-02-27 03:12:36 +00001322 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001323 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001324 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001325 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001326 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001327 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001328 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001329 PtrOperand = LI->getPointerOperand();
1330 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001331 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001332 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001333 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001334 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001335 PtrOperand = SI->getPointerOperand();
1336 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001337 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001338 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001339 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001340 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001341 PtrOperand = RMW->getPointerOperand();
1342 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001343 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001344 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001345 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001346 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001347 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001348 } else if (auto CI = dyn_cast<CallInst>(I)) {
1349 auto *F = dyn_cast<Function>(CI->getCalledValue());
1350 if (F && (F->getName().startswith("llvm.masked.load.") ||
1351 F->getName().startswith("llvm.masked.store."))) {
1352 unsigned OpOffset = 0;
1353 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001354 if (!ClInstrumentWrites)
1355 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001356 // Masked store has an initial operand for the value.
1357 OpOffset = 1;
1358 *IsWrite = true;
1359 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001360 if (!ClInstrumentReads)
1361 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001362 *IsWrite = false;
1363 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001364
1365 auto BasePtr = CI->getOperand(0 + OpOffset);
1366 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1367 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1368 if (auto AlignmentConstant =
1369 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1370 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1371 else
1372 *Alignment = 1; // No alignment guarantees. We probably got Undef
1373 if (MaybeMask)
1374 *MaybeMask = CI->getOperand(2 + OpOffset);
1375 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001376 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001377 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001378
Anna Zaks644d9d32016-06-22 00:15:52 +00001379 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001380 // Do not instrument acesses from different address spaces; we cannot deal
1381 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001382 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1383 if (PtrTy->getPointerAddressSpace() != 0)
1384 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001385
1386 // Ignore swifterror addresses.
1387 // swifterror memory addresses are mem2reg promoted by instruction
1388 // selection. As such they cannot have regular uses like an instrumentation
1389 // function and it makes no sense to track them as memory.
1390 if (PtrOperand->isSwiftError())
1391 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001392 }
1393
Anna Zaks8ed1d812015-02-27 03:12:36 +00001394 // Treat memory accesses to promotable allocas as non-interesting since they
1395 // will not cause memory violations. This greatly speeds up the instrumented
1396 // executable at -O0.
1397 if (ClSkipPromotableAllocas)
1398 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1399 return isInterestingAlloca(*AI) ? AI : nullptr;
1400
1401 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001402}
1403
Kostya Serebryany796f6552014-02-27 12:45:36 +00001404static bool isPointerOperand(Value *V) {
1405 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1406}
1407
1408// This is a rough heuristic; it may cause both false positives and
1409// false negatives. The proper implementation requires cooperation with
1410// the frontend.
1411static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1412 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001413 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001414 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001415 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001416 } else {
1417 return false;
1418 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001419 return isPointerOperand(I->getOperand(0)) &&
1420 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001421}
1422
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001423bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1424 // If a global variable does not have dynamic initialization we don't
1425 // have to instrument it. However, if a global does not have initializer
1426 // at all, we assume it has dynamic initializer (in other TU).
Leonard Chan436fb2b2019-02-13 22:22:48 +00001427 //
1428 // FIXME: Metadata should be attched directly to the global directly instead
1429 // of being added to llvm.asan.globals.
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001430 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001431}
1432
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001433void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1434 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001435 IRBuilder<> IRB(I);
James Y Knight13680222019-02-01 02:28:03 +00001436 FunctionCallee F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001437 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001438 for (Value *&i : Param) {
1439 if (i->getType()->isPointerTy())
1440 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001441 }
David Blaikieff6409d2015-05-18 22:13:54 +00001442 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001443}
1444
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001445static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001446 Instruction *InsertBefore, Value *Addr,
1447 unsigned Alignment, unsigned Granularity,
1448 uint32_t TypeSize, bool IsWrite,
1449 Value *SizeArgument, bool UseCalls,
1450 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001451 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1452 // if the data is properly aligned.
1453 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1454 TypeSize == 128) &&
1455 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001456 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1457 nullptr, UseCalls, Exp);
1458 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1459 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001460}
1461
1462static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1463 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001464 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001465 Value *Addr, unsigned Alignment,
1466 unsigned Granularity, uint32_t TypeSize,
1467 bool IsWrite, Value *SizeArgument,
1468 bool UseCalls, uint32_t Exp) {
1469 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1470 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1471 unsigned Num = VTy->getVectorNumElements();
1472 auto Zero = ConstantInt::get(IntptrTy, 0);
1473 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001474 Value *InstrumentedAddress = nullptr;
1475 Instruction *InsertBefore = I;
1476 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1477 // dyn_cast as we might get UndefValue
1478 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001479 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001480 // Mask is constant false, so no instrumentation needed.
1481 continue;
1482 // If we have a true or undef value, fall through to doInstrumentAddress
1483 // with InsertBefore == I
1484 }
1485 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001486 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001487 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001488 Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001489 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001490 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001491
1492 IRBuilder<> IRB(InsertBefore);
1493 InstrumentedAddress =
James Y Knight77160752019-02-01 20:44:47 +00001494 IRB.CreateGEP(VTy, Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001495 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1496 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1497 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001498 }
1499}
1500
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001501void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001502 Instruction *I, bool UseCalls,
1503 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001504 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001505 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001506 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001507 Value *MaybeMask = nullptr;
1508 Value *Addr =
1509 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001510 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001511
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001512 // Optimization experiments.
1513 // The experiments can be used to evaluate potential optimizations that remove
1514 // instrumentation (assess false negatives). Instead of completely removing
1515 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1516 // experiments that want to remove instrumentation of this instruction).
1517 // If Exp is non-zero, this pass will emit special calls into runtime
1518 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1519 // make runtime terminate the program in a special way (with a different
1520 // exit status). Then you run the new compiler on a buggy corpus, collect
1521 // the special terminations (ideally, you don't see them at all -- no false
1522 // negatives) and make the decision on the optimization.
1523 uint32_t Exp = ClForceExperiment;
1524
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001525 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001526 // If initialization order checking is disabled, a simple access to a
1527 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001528 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001529 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001530 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1531 NumOptimizedAccessesToGlobalVar++;
1532 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001533 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001534 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001535
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001536 if (ClOpt && ClOptStack) {
1537 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001538 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001539 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1540 NumOptimizedAccessesToStackVar++;
1541 return;
1542 }
1543 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001544
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001545 if (IsWrite)
1546 NumInstrumentedWrites++;
1547 else
1548 NumInstrumentedReads++;
1549
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001550 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001551 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001552 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1553 Alignment, Granularity, TypeSize, IsWrite,
1554 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001555 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001556 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001557 IsWrite, nullptr, UseCalls, Exp);
1558 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001559}
1560
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001561Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1562 Value *Addr, bool IsWrite,
1563 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001564 Value *SizeArgument,
1565 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001566 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001567 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1568 CallInst *Call = nullptr;
1569 if (SizeArgument) {
1570 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001571 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1572 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001573 else
David Blaikieff6409d2015-05-18 22:13:54 +00001574 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1575 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001576 } else {
1577 if (Exp == 0)
1578 Call =
1579 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1580 else
David Blaikieff6409d2015-05-18 22:13:54 +00001581 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1582 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001583 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001584
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001585 // We don't do Call->setDoesNotReturn() because the BB already has
1586 // UnreachableInst at the end.
1587 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001588 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001589 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001590}
1591
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001592Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001593 Value *ShadowValue,
1594 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001595 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001596 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001597 Value *LastAccessedByte =
1598 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001599 // (Addr & (Granularity - 1)) + size - 1
1600 if (TypeSize / 8 > 1)
1601 LastAccessedByte = IRB.CreateAdd(
1602 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1603 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001604 LastAccessedByte =
1605 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001606 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1607 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1608}
1609
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001610void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001611 Instruction *InsertBefore, Value *Addr,
1612 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001613 Value *SizeArgument, bool UseCalls,
1614 uint32_t Exp) {
Walter Leecdbb2072018-05-18 04:10:38 +00001615 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1616
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001617 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001618 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001619 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1620
1621 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001622 if (Exp == 0)
1623 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1624 AddrLong);
1625 else
David Blaikieff6409d2015-05-18 22:13:54 +00001626 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1627 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001628 return;
1629 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001630
Walter Leecdbb2072018-05-18 04:10:38 +00001631 if (IsMyriad) {
1632 // Strip the cache bit and do range check.
1633 // AddrLong &= ~kMyriadCacheBitMask32
1634 AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1635 // Tag = AddrLong >> kMyriadTagShift
1636 Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1637 // Tag == kMyriadDDRTag
1638 Value *TagCheck =
1639 IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1640
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001641 Instruction *TagCheckTerm =
1642 SplitBlockAndInsertIfThen(TagCheck, InsertBefore, false,
1643 MDBuilder(*C).createBranchWeights(1, 100000));
Walter Leecdbb2072018-05-18 04:10:38 +00001644 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1645 IRB.SetInsertPoint(TagCheckTerm);
1646 InsertBefore = TagCheckTerm;
1647 }
1648
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001649 Type *ShadowTy =
1650 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001651 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1652 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1653 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001654 Value *ShadowValue =
James Y Knight14359ef2019-02-01 20:44:24 +00001655 IRB.CreateLoad(ShadowTy, IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001656
1657 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001658 size_t Granularity = 1ULL << Mapping.Scale;
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001659 Instruction *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001660
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001661 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001662 // We use branch weights for the slow path check, to indicate that the slow
1663 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001664 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001665 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001666 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001667 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001668 IRB.SetInsertPoint(CheckTerm);
1669 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001670 if (Recover) {
1671 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1672 } else {
1673 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001674 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001675 CrashTerm = new UnreachableInst(*C, CrashBlock);
1676 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1677 ReplaceInstWithInst(CheckTerm, NewTerm);
1678 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001679 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001680 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001681 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001682
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001683 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001684 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001685 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001686}
1687
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001688// Instrument unusual size or unusual alignment.
1689// We can not do it with a single check, so we do 1-byte check for the first
1690// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1691// to report the actual access size.
1692void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001693 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1694 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1695 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001696 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1697 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1698 if (UseCalls) {
1699 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001700 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1701 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001702 else
David Blaikieff6409d2015-05-18 22:13:54 +00001703 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1704 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001705 } else {
1706 Value *LastByte = IRB.CreateIntToPtr(
1707 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1708 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001709 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1710 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001711 }
1712}
1713
Leonard Chan436fb2b2019-02-13 22:22:48 +00001714void ModuleAddressSanitizer::poisonOneInitializer(Function &GlobalInit,
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001715 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001716 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001717 IRBuilder<> IRB(&GlobalInit.front(),
1718 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001719
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001720 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001721 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1722 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001723
1724 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001725 for (auto &BB : GlobalInit.getBasicBlockList())
1726 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001727 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001728}
1729
Leonard Chan436fb2b2019-02-13 22:22:48 +00001730void ModuleAddressSanitizer::createInitializerPoisonCalls(
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001731 Module &M, GlobalValue *ModuleName) {
1732 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001733 if (!GV)
1734 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001735
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001736 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1737 if (!CA)
1738 return;
1739
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001740 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001741 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001742 ConstantStruct *CS = cast<ConstantStruct>(OP);
1743
1744 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001745 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001746 if (F->getName() == kAsanModuleCtorName) continue;
1747 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1748 // Don't instrument CTORs that will run before asan.module_ctor.
1749 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1750 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001751 }
1752 }
1753}
1754
Leonard Chan436fb2b2019-02-13 22:22:48 +00001755bool ModuleAddressSanitizer::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001756 Type *Ty = G->getValueType();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001757 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001758
Leonard Chan436fb2b2019-02-13 22:22:48 +00001759 // FIXME: Metadata should be attched directly to the global directly instead
1760 // of being added to llvm.asan.globals.
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001761 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001762 if (!Ty->isSized()) return false;
1763 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001764 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001765 // Two problems with thread-locals:
1766 // - The address of the main thread's copy can't be computed at link-time.
1767 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001768 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001769 // For now, just ignore this Global if the alignment is large.
1770 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001771
Reid Kleckner85a8c122018-08-20 23:35:45 +00001772 // For non-COFF targets, only instrument globals known to be defined by this
1773 // TU.
1774 // FIXME: We can instrument comdat globals on ELF if we are using the
1775 // GC-friendly metadata scheme.
1776 if (!TargetTriple.isOSBinFormatCOFF()) {
1777 if (!G->hasExactDefinition() || G->hasComdat())
1778 return false;
1779 } else {
1780 // On COFF, don't instrument non-ODR linkages.
1781 if (G->isInterposable())
1782 return false;
1783 }
1784
1785 // If a comdat is present, it must have a selection kind that implies ODR
1786 // semantics: no duplicates, any, or exact match.
1787 if (Comdat *C = G->getComdat()) {
1788 switch (C->getSelectionKind()) {
1789 case Comdat::Any:
1790 case Comdat::ExactMatch:
1791 case Comdat::NoDuplicates:
1792 break;
1793 case Comdat::Largest:
1794 case Comdat::SameSize:
1795 return false;
1796 }
1797 }
1798
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001799 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001800 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001801
Anna Zaks11904602015-06-09 00:58:08 +00001802 // Globals from llvm.metadata aren't emitted, do not instrument them.
1803 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001804 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001805 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001806
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001807 // Do not instrument function pointers to initialization and termination
1808 // routines: dynamic linker will not properly handle redzones.
1809 if (Section.startswith(".preinit_array") ||
1810 Section.startswith(".init_array") ||
1811 Section.startswith(".fini_array")) {
1812 return false;
1813 }
1814
Reid Kleckner12395b72018-06-13 20:47:21 +00001815 // On COFF, if the section name contains '$', it is highly likely that the
1816 // user is using section sorting to create an array of globals similar to
1817 // the way initialization callbacks are registered in .init_array and
1818 // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1819 // to such globals is counterproductive, because the intent is that they
1820 // will form an array, and out-of-bounds accesses are expected.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001821 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001822 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
Reid Kleckner12395b72018-06-13 20:47:21 +00001823 if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1824 LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1825 << *G << "\n");
Anna Zaks11904602015-06-09 00:58:08 +00001826 return false;
1827 }
1828
Kuba Brecka1001bb52014-12-05 22:19:18 +00001829 if (TargetTriple.isOSBinFormatMachO()) {
1830 StringRef ParsedSegment, ParsedSection;
1831 unsigned TAA = 0, StubSize = 0;
1832 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001833 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1834 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001835 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001836
1837 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1838 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1839 // them.
1840 if (ParsedSegment == "__OBJC" ||
1841 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001842 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001843 return false;
1844 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001845 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001846 // Constant CFString instances are compiled in the following way:
1847 // -- the string buffer is emitted into
1848 // __TEXT,__cstring,cstring_literals
1849 // -- the constant NSConstantString structure referencing that buffer
1850 // is placed into __DATA,__cfstring
1851 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1852 // Moreover, it causes the linker to crash on OS X 10.7
1853 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001854 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001855 return false;
1856 }
1857 // The linker merges the contents of cstring_literals and removes the
1858 // trailing zeroes.
1859 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001860 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001861 return false;
1862 }
1863 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001864 }
1865
1866 return true;
1867}
1868
Ryan Govostes653f9d02016-03-28 20:28:57 +00001869// On Mach-O platforms, we emit global metadata in a separate section of the
1870// binary in order to allow the linker to properly dead strip. This is only
1871// supported on recent versions of ld64.
Leonard Chan436fb2b2019-02-13 22:22:48 +00001872bool ModuleAddressSanitizer::ShouldUseMachOGlobalsSection() const {
Ryan Govostes653f9d02016-03-28 20:28:57 +00001873 if (!TargetTriple.isOSBinFormatMachO())
1874 return false;
1875
1876 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1877 return true;
1878 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001879 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001880 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1881 return true;
1882
1883 return false;
1884}
1885
Leonard Chan436fb2b2019-02-13 22:22:48 +00001886StringRef ModuleAddressSanitizer::getGlobalMetadataSection() const {
Reid Kleckner01660a32016-11-21 20:40:37 +00001887 switch (TargetTriple.getObjectFormat()) {
1888 case Triple::COFF: return ".ASAN$GL";
1889 case Triple::ELF: return "asan_globals";
1890 case Triple::MachO: return "__DATA,__asan_globals,regular";
1891 default: break;
1892 }
1893 llvm_unreachable("unsupported object format");
1894}
1895
Leonard Chan436fb2b2019-02-13 22:22:48 +00001896void ModuleAddressSanitizer::initializeCallbacks(Module &M) {
Alexey Samsonov788381b2012-12-25 12:28:20 +00001897 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001898
Alexey Samsonov788381b2012-12-25 12:28:20 +00001899 // Declare our poisoning and unpoisoning functions.
James Y Knight13680222019-02-01 02:28:03 +00001900 AsanPoisonGlobals =
1901 M.getOrInsertFunction(kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy);
1902 AsanUnpoisonGlobals =
1903 M.getOrInsertFunction(kAsanUnpoisonGlobalsName, IRB.getVoidTy());
Ryan Govostes653f9d02016-03-28 20:28:57 +00001904
Alexey Samsonov788381b2012-12-25 12:28:20 +00001905 // Declare functions that register/unregister globals.
James Y Knight13680222019-02-01 02:28:03 +00001906 AsanRegisterGlobals = M.getOrInsertFunction(
1907 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
1908 AsanUnregisterGlobals = M.getOrInsertFunction(
1909 kAsanUnregisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001910
1911 // Declare the functions that find globals in a shared object and then invoke
1912 // the (un)register function on them.
James Y Knight13680222019-02-01 02:28:03 +00001913 AsanRegisterImageGlobals = M.getOrInsertFunction(
1914 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
1915 AsanUnregisterImageGlobals = M.getOrInsertFunction(
1916 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001917
James Y Knight13680222019-02-01 02:28:03 +00001918 AsanRegisterElfGlobals =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001919 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
James Y Knight13680222019-02-01 02:28:03 +00001920 IntptrTy, IntptrTy, IntptrTy);
1921 AsanUnregisterElfGlobals =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001922 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
James Y Knight13680222019-02-01 02:28:03 +00001923 IntptrTy, IntptrTy, IntptrTy);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001924}
1925
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001926// Put the metadata and the instrumented global in the same group. This ensures
1927// that the metadata is discarded if the instrumented global is discarded.
Leonard Chan436fb2b2019-02-13 22:22:48 +00001928void ModuleAddressSanitizer::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001929 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001930 Module &M = *G->getParent();
1931 Comdat *C = G->getComdat();
1932 if (!C) {
1933 if (!G->hasName()) {
1934 // If G is unnamed, it must be internal. Give it an artificial name
1935 // so we can put it in a comdat.
1936 assert(G->hasLocalLinkage());
1937 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1938 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001939
1940 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1941 std::string Name = G->getName();
1942 Name += InternalSuffix;
1943 C = M.getOrInsertComdat(Name);
1944 } else {
1945 C = M.getOrInsertComdat(G->getName());
1946 }
1947
Reid Klecknerc212cc82017-10-31 16:16:08 +00001948 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1949 // linkage to internal linkage so that a symbol table entry is emitted. This
1950 // is necessary in order to create the comdat group.
1951 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001952 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001953 if (G->hasPrivateLinkage())
1954 G->setLinkage(GlobalValue::InternalLinkage);
1955 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001956 G->setComdat(C);
1957 }
1958
1959 assert(G->hasComdat());
1960 Metadata->setComdat(G->getComdat());
1961}
1962
1963// Create a separate metadata global and put it in the appropriate ASan
1964// global registration section.
1965GlobalVariable *
Leonard Chan436fb2b2019-02-13 22:22:48 +00001966ModuleAddressSanitizer::CreateMetadataGlobal(Module &M, Constant *Initializer,
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001967 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001968 auto Linkage = TargetTriple.isOSBinFormatMachO()
1969 ? GlobalVariable::InternalLinkage
1970 : GlobalVariable::PrivateLinkage;
1971 GlobalVariable *Metadata = new GlobalVariable(
1972 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001973 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001974 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001975 return Metadata;
1976}
1977
Leonard Chan436fb2b2019-02-13 22:22:48 +00001978IRBuilder<> ModuleAddressSanitizer::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001979 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001980 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1981 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1982 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001983
1984 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1985}
1986
Leonard Chan436fb2b2019-02-13 22:22:48 +00001987void ModuleAddressSanitizer::InstrumentGlobalsCOFF(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001988 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1989 ArrayRef<Constant *> MetadataInitializers) {
1990 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001991 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001992
1993 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001994 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001995 GlobalVariable *G = ExtendedGlobals[i];
1996 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001997 CreateMetadataGlobal(M, Initializer, G->getName());
1998
1999 // The MSVC linker always inserts padding when linking incrementally. We
2000 // cope with that by aligning each struct to its size, which must be a power
2001 // of two.
2002 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
2003 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
2004 "global metadata will not be padded appropriately");
2005 Metadata->setAlignment(SizeOfGlobalStruct);
2006
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002007 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002008 }
2009}
2010
Leonard Chan436fb2b2019-02-13 22:22:48 +00002011void ModuleAddressSanitizer::InstrumentGlobalsELF(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002012 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2013 ArrayRef<Constant *> MetadataInitializers,
2014 const std::string &UniqueModuleId) {
2015 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2016
2017 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
2018 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2019 GlobalVariable *G = ExtendedGlobals[i];
2020 GlobalVariable *Metadata =
2021 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
2022 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
2023 Metadata->setMetadata(LLVMContext::MD_associated, MD);
2024 MetadataGlobals[i] = Metadata;
2025
2026 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
2027 }
2028
2029 // Update llvm.compiler.used, adding the new metadata globals. This is
2030 // needed so that during LTO these variables stay alive.
2031 if (!MetadataGlobals.empty())
2032 appendToCompilerUsed(M, MetadataGlobals);
2033
2034 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2035 // to look up the loaded image that contains it. Second, we can store in it
2036 // whether registration has already occurred, to prevent duplicate
2037 // registration.
2038 //
2039 // Common linkage ensures that there is only one global per shared library.
2040 GlobalVariable *RegisteredFlag = new GlobalVariable(
2041 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2042 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2043 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2044
2045 // Create start and stop symbols.
2046 GlobalVariable *StartELFMetadata = new GlobalVariable(
2047 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2048 "__start_" + getGlobalMetadataSection());
2049 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2050 GlobalVariable *StopELFMetadata = new GlobalVariable(
2051 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
2052 "__stop_" + getGlobalMetadataSection());
2053 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
2054
2055 // Create a call to register the globals with the runtime.
2056 IRB.CreateCall(AsanRegisterElfGlobals,
2057 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2058 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2059 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2060
2061 // We also need to unregister globals at the end, e.g., when a shared library
2062 // gets closed.
2063 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2064 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
2065 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
2066 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
2067 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
2068}
2069
Leonard Chan436fb2b2019-02-13 22:22:48 +00002070void ModuleAddressSanitizer::InstrumentGlobalsMachO(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002071 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2072 ArrayRef<Constant *> MetadataInitializers) {
2073 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2074
2075 // On recent Mach-O platforms, use a structure which binds the liveness of
2076 // the global variable to the metadata struct. Keep the list of "Liveness" GV
2077 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00002078 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002079 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
2080
2081 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
2082 Constant *Initializer = MetadataInitializers[i];
2083 GlobalVariable *G = ExtendedGlobals[i];
2084 GlobalVariable *Metadata =
2085 CreateMetadataGlobal(M, Initializer, G->getName());
2086
2087 // On recent Mach-O platforms, we emit the global metadata in a way that
2088 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00002089 auto LivenessBinder =
2090 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2091 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002092 GlobalVariable *Liveness = new GlobalVariable(
2093 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2094 Twine("__asan_binder_") + G->getName());
2095 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2096 LivenessGlobals[i] = Liveness;
2097 }
2098
2099 // Update llvm.compiler.used, adding the new liveness globals. This is
2100 // needed so that during LTO these variables stay alive. The alternative
2101 // would be to have the linker handling the LTO symbols, but libLTO
2102 // current API does not expose access to the section for each symbol.
2103 if (!LivenessGlobals.empty())
2104 appendToCompilerUsed(M, LivenessGlobals);
2105
2106 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2107 // to look up the loaded image that contains it. Second, we can store in it
2108 // whether registration has already occurred, to prevent duplicate
2109 // registration.
2110 //
2111 // common linkage ensures that there is only one global per shared library.
2112 GlobalVariable *RegisteredFlag = new GlobalVariable(
2113 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2114 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2115 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2116
2117 IRB.CreateCall(AsanRegisterImageGlobals,
2118 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2119
2120 // We also need to unregister globals at the end, e.g., when a shared library
2121 // gets closed.
2122 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2123 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2124 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2125}
2126
Leonard Chan436fb2b2019-02-13 22:22:48 +00002127void ModuleAddressSanitizer::InstrumentGlobalsWithMetadataArray(
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002128 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2129 ArrayRef<Constant *> MetadataInitializers) {
2130 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2131 unsigned N = ExtendedGlobals.size();
2132 assert(N > 0);
2133
2134 // On platforms that don't have a custom metadata section, we emit an array
2135 // of global metadata structures.
2136 ArrayType *ArrayOfGlobalStructTy =
2137 ArrayType::get(MetadataInitializers[0]->getType(), N);
2138 auto AllGlobals = new GlobalVariable(
2139 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2140 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00002141 if (Mapping.Scale > 3)
2142 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002143
2144 IRB.CreateCall(AsanRegisterGlobals,
2145 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2146 ConstantInt::get(IntptrTy, N)});
2147
2148 // We also need to unregister globals at the end, e.g., when a shared library
2149 // gets closed.
2150 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2151 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2152 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2153 ConstantInt::get(IntptrTy, N)});
2154}
2155
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002156// This function replaces all global variables with new variables that have
2157// trailing redzones. It also creates a function that poisons
2158// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002159// Sets *CtorComdat to true if the global registration code emitted into the
2160// asan constructor is comdat-compatible.
Leonard Chan436fb2b2019-02-13 22:22:48 +00002161bool ModuleAddressSanitizer::InstrumentGlobals(IRBuilder<> &IRB, Module &M,
2162 bool *CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002163 *CtorComdat = false;
Kostya Serebryany20a79972012-11-22 03:18:50 +00002164
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002165 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2166
Alexey Samsonova02e6642014-05-29 18:40:48 +00002167 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002168 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002169 }
2170
2171 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002172 if (n == 0) {
2173 *CtorComdat = true;
2174 return false;
2175 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002176
Reid Kleckner78565832016-11-29 01:32:21 +00002177 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002178
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002179 // A global is described by a structure
2180 // size_t beg;
2181 // size_t size;
2182 // size_t size_with_redzone;
2183 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002184 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002185 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002186 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002187 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002188 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002189 StructType *GlobalStructTy =
2190 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002191 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002192 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2193 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002194
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002195 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002196
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002197 // We shouldn't merge same module names, as this string serves as unique
2198 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002199 GlobalVariable *ModuleName = createPrivateGlobalForString(
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002200 M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002201
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002202 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002203 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002204 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002205
Leonard Chan436fb2b2019-02-13 22:22:48 +00002206 // FIXME: Metadata should be attched directly to the global directly instead
2207 // of being added to llvm.asan.globals.
Alexey Samsonov15c96692014-07-12 00:42:52 +00002208 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002209 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002210 // Create string holding the global name (use global name from metadata
2211 // if it's available, otherwise just write the name of global variable).
2212 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002213 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002214 /*AllowMerging*/ true, kAsanGenPrefix);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002215
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002216 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002217 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002218 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002219 // MinRZ <= RZ <= kMaxGlobalRedzone
2220 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002221 uint64_t RZ = std::max(
2222 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002223 uint64_t RightRedzoneSize = RZ;
2224 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002225 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002226 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002227 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2228
Serge Gueltone38003f2017-05-09 19:31:13 +00002229 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2230 Constant *NewInitializer = ConstantStruct::get(
2231 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002232
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002233 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002234 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2235 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2236 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002237 GlobalVariable *NewGlobal =
2238 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2239 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002240 NewGlobal->copyAttributesFrom(G);
Reid Kleckner85a8c122018-08-20 23:35:45 +00002241 NewGlobal->setComdat(G->getComdat());
Kostya Serebryany87191f62013-01-24 10:35:40 +00002242 NewGlobal->setAlignment(MinRZ);
Vitaly Bukad414e1b2018-12-20 00:30:18 +00002243 // Don't fold globals with redzones. ODR violation detector and redzone
2244 // poisoning implicitly creates a dependence on the global's address, so it
2245 // is no longer valid for it to be marked unnamed_addr.
2246 NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002247
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002248 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2249 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2250 G->isConstant()) {
2251 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2252 if (Seq && Seq->isCString())
2253 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2254 }
2255
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002256 // Transfer the debug info. The payload starts at offset zero so we can
2257 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002258 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002259 G->getDebugInfo(GVs);
2260 for (auto *GV : GVs)
2261 NewGlobal->addDebugInfo(GV);
2262
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002263 Value *Indices2[2];
2264 Indices2[0] = IRB.getInt32(0);
2265 Indices2[1] = IRB.getInt32(0);
2266
2267 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002268 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002269 NewGlobal->takeName(G);
2270 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002271 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002272
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002273 Constant *SourceLoc;
2274 if (!MD.SourceLoc.empty()) {
2275 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2276 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2277 } else {
2278 SourceLoc = ConstantInt::get(IntptrTy, 0);
2279 }
2280
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002281 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2282 GlobalValue *InstrumentedGlobal = NewGlobal;
2283
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002284 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002285 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2286 TargetTriple.isOSBinFormatWasm();
Vitaly Buka8076c572018-12-05 01:44:31 +00002287 if (CanUsePrivateAliases && UsePrivateAlias) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002288 // Create local alias for NewGlobal to avoid crash on ODR between
2289 // instrumented and non-instrumented libraries.
Vitaly Bukad6bab092018-12-04 23:17:41 +00002290 InstrumentedGlobal =
Vitaly Buka537cfc02018-12-04 00:36:14 +00002291 GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
Vitaly Bukad6bab092018-12-04 23:17:41 +00002292 }
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002293
Vitaly Buka07a55f22018-12-20 00:30:27 +00002294 // ODR should not happen for local linkage.
2295 if (NewGlobal->hasLocalLinkage()) {
Vitaly Bukaa2576392018-12-13 09:47:39 +00002296 ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2297 IRB.getInt8PtrTy());
2298 } else if (UseOdrIndicator) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002299 // With local aliases, we need to provide another externally visible
2300 // symbol __odr_asan_XXX to detect ODR violation.
2301 auto *ODRIndicatorSym =
2302 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2303 Constant::getNullValue(IRB.getInt8Ty()),
2304 kODRGenPrefix + NameForGlobal, nullptr,
2305 NewGlobal->getThreadLocalMode());
2306
2307 // Set meaningful attributes for indicator symbol.
2308 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2309 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2310 ODRIndicatorSym->setAlignment(1);
2311 ODRIndicator = ODRIndicatorSym;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002312 }
2313
Reid Kleckner01660a32016-11-21 20:40:37 +00002314 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002315 GlobalStructTy,
2316 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002317 ConstantInt::get(IntptrTy, SizeInBytes),
2318 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2319 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002320 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002321 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002322 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002323
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002324 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002325
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002326 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002327
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002328 Initializers[i] = Initializer;
2329 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002330
Kuba Mracek8842da82018-03-08 21:02:18 +00002331 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2332 // ConstantMerge'ing them.
2333 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2334 for (size_t i = 0; i < n; i++) {
2335 GlobalVariable *G = NewGlobals[i];
2336 if (G->getName().empty()) continue;
2337 GlobalsToAddToUsedList.push_back(G);
2338 }
2339 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2340
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002341 std::string ELFUniqueModuleId =
2342 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2343 : "";
2344
2345 if (!ELFUniqueModuleId.empty()) {
2346 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2347 *CtorComdat = true;
2348 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002349 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002350 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002351 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2352 } else {
2353 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002354 }
2355
Reid Kleckner01660a32016-11-21 20:40:37 +00002356 // Create calls for poisoning before initializers run and unpoisoning after.
2357 if (HasDynamicallyInitializedGlobals)
2358 createInitializerPoisonCalls(M, ModuleName);
2359
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002360 LLVM_DEBUG(dbgs() << M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002361 return true;
2362}
2363
Leonard Chan436fb2b2019-02-13 22:22:48 +00002364int ModuleAddressSanitizer::GetAsanVersion(const Module &M) const {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002365 int LongSize = M.getDataLayout().getPointerSizeInBits();
2366 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2367 int Version = 8;
2368 // 32-bit Android is one version ahead because of the switch to dynamic
2369 // shadow.
2370 Version += (LongSize == 32 && isAndroid);
2371 return Version;
2372}
2373
Leonard Chan436fb2b2019-02-13 22:22:48 +00002374bool ModuleAddressSanitizer::instrumentModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002375 initializeCallbacks(M);
2376
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002377 if (CompileKernel)
2378 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002379
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002380 // Create a module constructor. A destructor is created lazily because not all
2381 // platforms, and not all modules need it.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002382 std::string VersionCheckName =
2383 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002384 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2385 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002386 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002387
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002388 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002389 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002390 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002391 if (ClGlobals) {
2392 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002393 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2394 }
2395
2396 // Put the constructor and destructor in comdat if both
2397 // (1) global instrumentation is not TU-specific
2398 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002399 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002400 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2401 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2402 AsanCtorFunction);
2403 if (AsanDtorFunction) {
2404 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2405 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2406 AsanDtorFunction);
2407 }
2408 } else {
2409 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2410 if (AsanDtorFunction)
2411 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002412 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002413
2414 return Changed;
2415}
2416
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002417void AddressSanitizer::initializeCallbacks(Module &M) {
2418 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002419 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002420 // IsWrite, TypeSize and Exp are encoded in the function name.
2421 for (int Exp = 0; Exp < 2; Exp++) {
2422 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2423 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2424 const std::string ExpStr = Exp ? "exp_" : "";
Yury Gribovd7731982015-11-11 10:36:49 +00002425 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002426
2427 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2428 SmallVector<Type *, 2> Args1{1, IntptrTy};
2429 if (Exp) {
2430 Type *ExpType = Type::getInt32Ty(*C);
2431 Args2.push_back(ExpType);
2432 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002433 }
James Y Knight13680222019-02-01 02:28:03 +00002434 AsanErrorCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2435 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
2436 FunctionType::get(IRB.getVoidTy(), Args2, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002437
James Y Knight13680222019-02-01 02:28:03 +00002438 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] = M.getOrInsertFunction(
2439 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2440 FunctionType::get(IRB.getVoidTy(), Args2, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002441
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002442 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2443 AccessSizeIndex++) {
2444 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2445 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
James Y Knight13680222019-02-01 02:28:03 +00002446 M.getOrInsertFunction(
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002447 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
James Y Knight13680222019-02-01 02:28:03 +00002448 FunctionType::get(IRB.getVoidTy(), Args1, false));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002449
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002450 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
James Y Knight13680222019-02-01 02:28:03 +00002451 M.getOrInsertFunction(
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002452 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
James Y Knight13680222019-02-01 02:28:03 +00002453 FunctionType::get(IRB.getVoidTy(), Args1, false));
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002454 }
2455 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002456 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002457
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002458 const std::string MemIntrinCallbackPrefix =
2459 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
James Y Knight13680222019-02-01 02:28:03 +00002460 AsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
2461 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2462 IRB.getInt8PtrTy(), IntptrTy);
2463 AsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
2464 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2465 IRB.getInt8PtrTy(), IntptrTy);
2466 AsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
2467 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
2468 IRB.getInt32Ty(), IntptrTy);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002469
James Y Knight13680222019-02-01 02:28:03 +00002470 AsanHandleNoReturnFunc =
2471 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy());
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002472
James Y Knight13680222019-02-01 02:28:03 +00002473 AsanPtrCmpFunction =
2474 M.getOrInsertFunction(kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy);
2475 AsanPtrSubFunction =
2476 M.getOrInsertFunction(kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002477 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2478 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2479 StringRef(""), StringRef(""),
2480 /*hasSideEffects=*/true);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002481 if (Mapping.InGlobal)
2482 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2483 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002484}
2485
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002486bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2487 // For each NSObject descendant having a +load method, this method is invoked
2488 // by the ObjC runtime before any of the static constructors is called.
2489 // Therefore we need to instrument such methods with a call to __asan_init
2490 // at the beginning in order to initialize our runtime before any access to
2491 // the shadow memory.
2492 // We cannot just ignore these methods, because they may call other
2493 // instrumented functions.
2494 if (F.getName().find(" load]") != std::string::npos) {
James Y Knight13680222019-02-01 02:28:03 +00002495 FunctionCallee AsanInitFunction =
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002496 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002497 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002498 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002499 return true;
2500 }
2501 return false;
2502}
2503
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002504void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2505 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002506 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002507 return;
2508
2509 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002510 if (Mapping.InGlobal) {
2511 if (ClWithIfuncSuppressRemat) {
2512 // An empty inline asm with input reg == output reg.
2513 // An opaque pointer-to-int cast, basically.
2514 InlineAsm *Asm = InlineAsm::get(
2515 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2516 StringRef(""), StringRef("=r,0"),
2517 /*hasSideEffects=*/false);
2518 LocalDynamicShadow =
2519 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2520 } else {
2521 LocalDynamicShadow =
2522 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2523 }
2524 } else {
2525 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2526 kAsanShadowMemoryDynamicAddress, IntptrTy);
James Y Knight14359ef2019-02-01 20:44:24 +00002527 LocalDynamicShadow = IRB.CreateLoad(IntptrTy, GlobalDynamicAddress);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002528 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002529}
2530
Reid Kleckner2f907552015-07-21 17:40:14 +00002531void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2532 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2533 // to it as uninteresting. This assumes we haven't started processing allocas
2534 // yet. This check is done up front because iterating the use list in
2535 // isInterestingAlloca would be algorithmically slower.
2536 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2537
2538 // Try to get the declaration of llvm.localescape. If it's not in the module,
2539 // we can exit early.
2540 if (!F.getParent()->getFunction("llvm.localescape")) return;
2541
2542 // Look for a call to llvm.localescape call in the entry block. It can't be in
2543 // any other block.
2544 for (Instruction &I : F.getEntryBlock()) {
2545 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2546 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2547 // We found a call. Mark all the allocas passed in as uninteresting.
2548 for (Value *Arg : II->arg_operands()) {
2549 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2550 assert(AI && AI->isStaticAlloca() &&
2551 "non-static alloca arg to localescape");
2552 ProcessedAllocas[AI] = false;
2553 }
2554 break;
2555 }
2556 }
2557}
2558
Leonard Chan436fb2b2019-02-13 22:22:48 +00002559bool AddressSanitizer::instrumentFunction(Function &F,
2560 const TargetLibraryInfo *TLI) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002561 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002562 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002563 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002564
Etienne Bergeron78582b22016-09-15 15:45:05 +00002565 bool FunctionModified = false;
2566
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002567 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002568 // This function needs to be called even if the function body is not
Fangrui Songf78650a2018-07-30 19:41:25 +00002569 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002570 if (maybeInsertAsanInitAtFunctionEntry(F))
2571 FunctionModified = true;
Fangrui Songf78650a2018-07-30 19:41:25 +00002572
Etienne Bergeron752f8832016-09-14 17:18:37 +00002573 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002574 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002575
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002576 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Etienne Bergeron752f8832016-09-14 17:18:37 +00002577
2578 initializeCallbacks(*F.getParent());
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002579
Reid Kleckner2f907552015-07-21 17:40:14 +00002580 FunctionStateRAII CleanupObj(this);
2581
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002582 maybeInsertDynamicShadowAtFunctionEntry(F);
2583
Reid Kleckner2f907552015-07-21 17:40:14 +00002584 // We can't instrument allocas used with llvm.localescape. Only static allocas
2585 // can be passed to that intrinsic.
2586 markEscapedLocalAllocas(F);
2587
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002588 // We want to instrument every address only once per basic block (unless there
2589 // are calls between uses).
Florian Hahna1cc8482018-06-12 11:16:56 +00002590 SmallPtrSet<Value *, 16> TempsToInstrument;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002591 SmallVector<Instruction *, 16> ToInstrument;
2592 SmallVector<Instruction *, 8> NoReturnCalls;
2593 SmallVector<BasicBlock *, 16> AllBlocks;
2594 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002595 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002596 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002597 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002598 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002599
2600 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002601 for (auto &BB : F) {
2602 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002603 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002604 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002605 for (auto &Inst : BB) {
2606 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002607 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002608 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002609 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002610 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002611 // If we have a mask, skip instrumentation if we've already
2612 // instrumented the full object. But don't add to TempsToInstrument
2613 // because we might get another load/store with a different mask.
2614 if (MaybeMask) {
2615 if (TempsToInstrument.count(Addr))
2616 continue; // We've seen this (whole) temp in the current BB.
2617 } else {
2618 if (!TempsToInstrument.insert(Addr).second)
2619 continue; // We've seen this temp in the current BB.
2620 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002621 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002622 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002623 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2624 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002625 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002626 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002627 // ok, take it.
2628 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002629 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002630 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002631 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002632 // A call inside BB.
2633 TempsToInstrument.clear();
Julian Lettnerf82d8922019-02-02 02:05:16 +00002634 if (CS.doesNotReturn() && !CS->getMetadata("nosanitize"))
2635 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002636 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002637 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2638 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002639 continue;
2640 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002641 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002642 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002643 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002644 }
2645 }
2646
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002647 bool UseCalls =
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002648 (ClInstrumentationWithCallsThreshold >= 0 &&
2649 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002650 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002651 ObjectSizeOpts ObjSizeOpts;
2652 ObjSizeOpts.RoundToAlign = true;
2653 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002654
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002655 // Instrument.
2656 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002657 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002658 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2659 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002660 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002661 instrumentMop(ObjSizeVis, Inst, UseCalls,
2662 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002663 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002664 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002665 }
2666 NumInstrumented++;
2667 }
2668
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002669 FunctionStackPoisoner FSP(F, *this);
2670 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002671
Julian Lettnerf82d8922019-02-02 02:05:16 +00002672 // We must unpoison the stack before NoReturn calls (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002673 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002674 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002675 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002676 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002677 }
2678
Alexey Samsonova02e6642014-05-29 18:40:48 +00002679 for (auto Inst : PointerComparisonsOrSubtracts) {
2680 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002681 NumInstrumented++;
2682 }
2683
Etienne Bergeron78582b22016-09-15 15:45:05 +00002684 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2685 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002686
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002687 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2688 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002689
Etienne Bergeron78582b22016-09-15 15:45:05 +00002690 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002691}
2692
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002693// Workaround for bug 11395: we don't want to instrument stack in functions
2694// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2695// FIXME: remove once the bug 11395 is fixed.
2696bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2697 if (LongSize != 32) return false;
2698 CallInst *CI = dyn_cast<CallInst>(I);
2699 if (!CI || !CI->isInlineAsm()) return false;
2700 if (CI->getNumArgOperands() <= 5) return false;
2701 // We have inline assembly with quite a few arguments.
2702 return true;
2703}
2704
2705void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2706 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002707 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2708 std::string Suffix = itostr(i);
James Y Knight13680222019-02-01 02:28:03 +00002709 AsanStackMallocFunc[i] = M.getOrInsertFunction(
2710 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy);
2711 AsanStackFreeFunc[i] =
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002712 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
James Y Knight13680222019-02-01 02:28:03 +00002713 IRB.getVoidTy(), IntptrTy, IntptrTy);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002714 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002715 if (ASan.UseAfterScope) {
James Y Knight13680222019-02-01 02:28:03 +00002716 AsanPoisonStackMemoryFunc = M.getOrInsertFunction(
2717 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
2718 AsanUnpoisonStackMemoryFunc = M.getOrInsertFunction(
2719 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy);
Vitaly Buka79b75d32016-06-09 23:05:35 +00002720 }
2721
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002722 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2723 std::ostringstream Name;
2724 Name << kAsanSetShadowPrefix;
2725 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002726 AsanSetShadowFunc[Val] =
James Y Knight13680222019-02-01 02:28:03 +00002727 M.getOrInsertFunction(Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy);
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002728 }
2729
James Y Knight13680222019-02-01 02:28:03 +00002730 AsanAllocaPoisonFunc = M.getOrInsertFunction(
2731 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
2732 AsanAllocasUnpoisonFunc = M.getOrInsertFunction(
2733 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002734}
2735
Vitaly Buka793913c2016-08-29 18:17:21 +00002736void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2737 ArrayRef<uint8_t> ShadowBytes,
2738 size_t Begin, size_t End,
2739 IRBuilder<> &IRB,
2740 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002741 if (Begin >= End)
2742 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002743
2744 const size_t LargestStoreSizeInBytes =
2745 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2746
2747 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2748
2749 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002750 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2751 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2752 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002753 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002754 if (!ShadowMask[i]) {
2755 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002756 ++i;
2757 continue;
2758 }
2759
2760 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2761 // Fit store size into the range.
2762 while (StoreSizeInBytes > End - i)
2763 StoreSizeInBytes /= 2;
2764
2765 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002766 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002767 while (j <= StoreSizeInBytes / 2)
2768 StoreSizeInBytes /= 2;
2769 }
2770
2771 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002772 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2773 if (IsLittleEndian)
2774 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2775 else
2776 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002777 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002778
2779 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2780 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002781 IRB.CreateAlignedStore(
2782 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002783
2784 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002785 }
2786}
2787
Vitaly Buka793913c2016-08-29 18:17:21 +00002788void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2789 ArrayRef<uint8_t> ShadowBytes,
2790 IRBuilder<> &IRB, Value *ShadowBase) {
2791 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2792}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002793
Vitaly Buka793913c2016-08-29 18:17:21 +00002794void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2795 ArrayRef<uint8_t> ShadowBytes,
2796 size_t Begin, size_t End,
2797 IRBuilder<> &IRB, Value *ShadowBase) {
2798 assert(ShadowMask.size() == ShadowBytes.size());
2799 size_t Done = Begin;
2800 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2801 if (!ShadowMask[i]) {
2802 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002803 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002804 }
2805 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002806 if (!AsanSetShadowFunc[Val])
2807 continue;
2808
2809 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002810 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002811 }
2812
2813 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002814 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002815 IRB.CreateCall(AsanSetShadowFunc[Val],
2816 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2817 ConstantInt::get(IntptrTy, j - i)});
2818 Done = j;
2819 }
2820 }
2821
Vitaly Buka793913c2016-08-29 18:17:21 +00002822 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002823}
2824
Kostya Serebryany6805de52013-09-10 13:16:56 +00002825// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2826// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2827static int StackMallocSizeClass(uint64_t LocalStackSize) {
2828 assert(LocalStackSize <= kMaxStackMallocSize);
2829 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002830 for (int i = 0;; i++, MaxSize *= 2)
2831 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002832 llvm_unreachable("impossible LocalStackSize");
2833}
2834
Vitaly Buka74443f02017-07-18 22:28:03 +00002835void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002836 Instruction *CopyInsertPoint = &F.front().front();
2837 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2838 // Insert after the dynamic shadow location is determined
2839 CopyInsertPoint = CopyInsertPoint->getNextNode();
2840 assert(CopyInsertPoint);
2841 }
2842 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002843 const DataLayout &DL = F.getParent()->getDataLayout();
2844 for (Argument &Arg : F.args()) {
2845 if (Arg.hasByValAttr()) {
2846 Type *Ty = Arg.getType()->getPointerElementType();
2847 unsigned Align = Arg.getParamAlignment();
2848 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2849
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002850 AllocaInst *AI = IRB.CreateAlloca(
2851 Ty, nullptr,
2852 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2853 ".byval");
Vitaly Buka74443f02017-07-18 22:28:03 +00002854 AI->setAlignment(Align);
2855 Arg.replaceAllUsesWith(AI);
2856
2857 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
Daniel Neilsona98d9d92018-02-08 21:26:12 +00002858 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
Vitaly Buka74443f02017-07-18 22:28:03 +00002859 }
2860 }
2861}
2862
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002863PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2864 Value *ValueIfTrue,
2865 Instruction *ThenTerm,
2866 Value *ValueIfFalse) {
2867 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2868 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2869 PHI->addIncoming(ValueIfFalse, CondBlock);
2870 BasicBlock *ThenBlock = ThenTerm->getParent();
2871 PHI->addIncoming(ValueIfTrue, ThenBlock);
2872 return PHI;
2873}
2874
2875Value *FunctionStackPoisoner::createAllocaForLayout(
2876 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2877 AllocaInst *Alloca;
2878 if (Dynamic) {
2879 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2880 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2881 "MyAlloca");
2882 } else {
2883 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2884 nullptr, "MyAlloca");
2885 assert(Alloca->isStaticAlloca());
2886 }
2887 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2888 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2889 Alloca->setAlignment(FrameAlignment);
2890 return IRB.CreatePointerCast(Alloca, IntptrTy);
2891}
2892
Yury Gribov98b18592015-05-28 07:51:49 +00002893void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2894 BasicBlock &FirstBB = *F.begin();
2895 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2896 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2897 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2898 DynamicAllocaLayout->setAlignment(32);
2899}
2900
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002901void FunctionStackPoisoner::processDynamicAllocas() {
2902 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2903 assert(DynamicAllocaPoisonCallVec.empty());
2904 return;
2905 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002906
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002907 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2908 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002909 assert(APC.InsBefore);
2910 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002911 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002912 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002913
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002914 IRBuilder<> IRB(APC.InsBefore);
2915 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002916 // Dynamic allocas will be unpoisoned unconditionally below in
2917 // unpoisonDynamicAllocas.
2918 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002919 }
2920
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002921 // Handle dynamic allocas.
2922 createDynamicAllocasInitStorage();
2923 for (auto &AI : DynamicAllocaVec)
2924 handleDynamicAllocaCall(AI);
2925 unpoisonDynamicAllocas();
2926}
Yury Gribov98b18592015-05-28 07:51:49 +00002927
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002928void FunctionStackPoisoner::processStaticAllocas() {
2929 if (AllocaVec.empty()) {
2930 assert(StaticAllocaPoisonCallVec.empty());
2931 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002932 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002933
Kostya Serebryany6805de52013-09-10 13:16:56 +00002934 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002935 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002936 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002937 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002938
2939 Instruction *InsBefore = AllocaVec[0];
2940 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002941 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002942
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002943 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2944 // debug info is broken, because only entry-block allocas are treated as
2945 // regular stack slots.
2946 auto InsBeforeB = InsBefore->getParent();
2947 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002948 for (auto *AI : StaticAllocasToMoveUp)
2949 if (AI->getParent() == InsBeforeB)
2950 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002951
Reid Kleckner2f907552015-07-21 17:40:14 +00002952 // If we have a call to llvm.localescape, keep it in the entry block.
2953 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2954
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002955 SmallVector<ASanStackVariableDescription, 16> SVD;
2956 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002957 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002958 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002959 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002960 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002961 AI->getAlignment(),
2962 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002963 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002964 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002965 SVD.push_back(D);
2966 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002967
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002968 // Minimal header size (left redzone) is 4 pointers,
2969 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00002970 size_t Granularity = 1ULL << Mapping.Scale;
2971 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00002972 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00002973 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002974
Vitaly Buka5910a922016-10-18 23:29:52 +00002975 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2976 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2977 for (auto &Desc : SVD)
2978 AllocaToSVDMap[Desc.AI] = &Desc;
2979
2980 // Update SVD with information from lifetime intrinsics.
2981 for (const auto &APC : StaticAllocaPoisonCallVec) {
2982 assert(APC.InsBefore);
2983 assert(APC.AI);
2984 assert(ASan.isInterestingAlloca(*APC.AI));
2985 assert(APC.AI->isStaticAlloca());
2986
2987 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2988 Desc.LifetimeSize = Desc.Size;
2989 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2990 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2991 if (LifetimeLoc->getFile() == FnLoc->getFile())
2992 if (unsigned Line = LifetimeLoc->getLine())
2993 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2994 }
2995 }
2996 }
2997
2998 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002999 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003000 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00003001 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
3002 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00003003 bool DoDynamicAlloca = ClDynamicAllocaStack;
3004 // Don't do dynamic alloca or stack malloc if:
3005 // 1) There is inline asm: too often it makes assumptions on which registers
3006 // are available.
3007 // 2) There is a returns_twice call (typically setjmp), which is
3008 // optimization-hostile, and doesn't play well with introduced indirect
3009 // register-relative calculation of local variable addresses.
3010 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
3011 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003012
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003013 Value *StaticAlloca =
3014 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
3015
3016 Value *FakeStack;
3017 Value *LocalStackBase;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003018 Value *LocalStackBaseAlloca;
3019 bool Deref;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003020
3021 if (DoStackMalloc) {
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003022 LocalStackBaseAlloca =
3023 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003024 // void *FakeStack = __asan_option_detect_stack_use_after_return
3025 // ? __asan_stack_malloc_N(LocalStackSize)
3026 // : nullptr;
3027 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003028 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
3029 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
James Y Knight14359ef2019-02-01 20:44:24 +00003030 Value *UseAfterReturnIsEnabled = IRB.CreateICmpNE(
3031 IRB.CreateLoad(IRB.getInt32Ty(), OptionDetectUseAfterReturn),
3032 Constant::getNullValue(IRB.getInt32Ty()));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003033 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003034 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00003035 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00003036 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003037 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
3038 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
3039 Value *FakeStackValue =
3040 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
3041 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00003042 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00003043 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00003044 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003045 ConstantInt::get(IntptrTy, 0));
3046
3047 Value *NoFakeStack =
3048 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
3049 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
3050 IRBIf.SetInsertPoint(Term);
3051 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
3052 Value *AllocaValue =
3053 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003054
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003055 IRB.SetInsertPoint(InsBefore);
3056 IRB.SetCurrentDebugLocation(EntryDebugLocation);
3057 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003058 IRB.SetCurrentDebugLocation(EntryDebugLocation);
3059 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3060 Deref = true;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003061 } else {
3062 // void *FakeStack = nullptr;
3063 // void *LocalStackBase = alloca(LocalStackSize);
3064 FakeStack = ConstantInt::get(IntptrTy, 0);
3065 LocalStackBase =
3066 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003067 LocalStackBaseAlloca = LocalStackBase;
3068 Deref = false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003069 }
3070
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003071 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003072 for (const auto &Desc : SVD) {
3073 AllocaInst *AI = Desc.AI;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003074 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
3075 Desc.Offset, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00003076 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00003077 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003078 AI->getType());
Alexey Samsonov261177a2012-12-04 01:34:23 +00003079 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003080 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003081
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003082 // The left-most redzone has enough space for at least 4 pointers.
3083 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003084 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3085 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3086 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003087 // Write the frame description constant to redzone[1].
3088 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003089 IRB.CreateAdd(LocalStackBase,
3090 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3091 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00003092 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00003093 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00003094 /*AllowMerging*/ true, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003095 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003096 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003097 // Write the PC to redzone[2].
3098 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003099 IRB.CreateAdd(LocalStackBase,
3100 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3101 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003102 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003103
Vitaly Buka793913c2016-08-29 18:17:21 +00003104 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3105
3106 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003107 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00003108 // As mask we must use most poisoned case: red zones and after scope.
3109 // As bytes we can use either the same or just red zones only.
3110 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3111
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003112 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00003113 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3114
3115 // Poison static allocas near lifetime intrinsics.
3116 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00003117 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00003118 assert(Desc.Offset % L.Granularity == 0);
3119 size_t Begin = Desc.Offset / L.Granularity;
3120 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3121
3122 IRBuilder<> IRB(APC.InsBefore);
3123 copyToShadow(ShadowAfterScope,
3124 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3125 IRB, ShadowBase);
3126 }
3127 }
3128
3129 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00003130 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00003131
Kostya Serebryany530e2072013-12-23 14:15:08 +00003132 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003133 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003134 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003135 // Mark the current frame as retired.
3136 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3137 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003138 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00003139 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003140 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00003141 // // In use-after-return mode, poison the whole stack frame.
3142 // if StackMallocIdx <= 4
3143 // // For small sizes inline the whole thing:
3144 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003145 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00003146 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003147 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00003148 // else
3149 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003150 Value *Cmp =
3151 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00003152 Instruction *ThenTerm, *ElseTerm;
Kostya Serebryany530e2072013-12-23 14:15:08 +00003153 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3154
3155 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003156 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003157 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003158 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3159 kAsanStackUseAfterReturnMagic);
3160 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3161 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003162 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003163 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003164 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3165 Value *SavedFlagPtr = IRBPoison.CreateLoad(
James Y Knight14359ef2019-02-01 20:44:24 +00003166 IntptrTy, IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003167 IRBPoison.CreateStore(
3168 Constant::getNullValue(IRBPoison.getInt8Ty()),
3169 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3170 } else {
3171 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003172 IRBPoison.CreateCall(
3173 AsanStackFreeFunc[StackMallocIdx],
3174 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003175 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003176
3177 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003178 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003179 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003180 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003181 }
3182 }
3183
Kostya Serebryany09959942012-10-19 06:20:53 +00003184 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003185 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003186}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003187
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003188void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003189 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003190 // For now just insert the call to ASan runtime.
3191 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3192 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003193 IRB.CreateCall(
3194 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3195 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003196}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003197
3198// Handling llvm.lifetime intrinsics for a given %alloca:
3199// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3200// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3201// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3202// could be poisoned by previous llvm.lifetime.end instruction, as the
3203// variable may go in and out of scope several times, e.g. in loops).
3204// (3) if we poisoned at least one %alloca in a function,
3205// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003206
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003207AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3208 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003209 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003210 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003211 // See if we've already calculated (or started to calculate) alloca for a
3212 // given value.
3213 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003214 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003215 // Store 0 while we're calculating alloca for value V to avoid
3216 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003217 AllocaForValue[V] = nullptr;
3218 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003219 if (CastInst *CI = dyn_cast<CastInst>(V))
3220 Res = findAllocaForValue(CI->getOperand(0));
3221 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003222 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003223 // Allow self-referencing phi-nodes.
3224 if (IncValue == PN) continue;
3225 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3226 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003227 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3228 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003229 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003230 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003231 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3232 Res = findAllocaForValue(EP->getPointerOperand());
3233 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003234 LLVM_DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V
3235 << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003236 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003237 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003238 return Res;
3239}
Yury Gribov55441bb2014-11-21 10:29:50 +00003240
Yury Gribov98b18592015-05-28 07:51:49 +00003241void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003242 IRBuilder<> IRB(AI);
3243
Yury Gribov55441bb2014-11-21 10:29:50 +00003244 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3245 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3246
3247 Value *Zero = Constant::getNullValue(IntptrTy);
3248 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3249 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003250
3251 // Since we need to extend alloca with additional memory to locate
3252 // redzones, and OldSize is number of allocated blocks with
3253 // ElementSize size, get allocated memory size in bytes by
3254 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003255 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003256 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003257 Value *OldSize =
3258 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3259 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003260
3261 // PartialSize = OldSize % 32
3262 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3263
3264 // Misalign = kAllocaRzSize - PartialSize;
3265 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3266
3267 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3268 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3269 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3270
3271 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3272 // Align is added to locate left redzone, PartialPadding for possible
3273 // partial redzone and kAllocaRzSize for right redzone respectively.
3274 Value *AdditionalChunkSize = IRB.CreateAdd(
3275 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3276
3277 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3278
3279 // Insert new alloca with new NewSize and Align params.
3280 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3281 NewAlloca->setAlignment(Align);
3282
3283 // NewAddress = Address + Align
3284 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3285 ConstantInt::get(IntptrTy, Align));
3286
Yury Gribov98b18592015-05-28 07:51:49 +00003287 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003288 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003289
3290 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3291 // for unpoisoning stuff.
3292 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3293
Yury Gribov55441bb2014-11-21 10:29:50 +00003294 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3295
Yury Gribov98b18592015-05-28 07:51:49 +00003296 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003297 AI->replaceAllUsesWith(NewAddressPtr);
3298
Yury Gribov98b18592015-05-28 07:51:49 +00003299 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003300 AI->eraseFromParent();
3301}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003302
3303// isSafeAccess returns true if Addr is always inbounds with respect to its
3304// base object. For example, it is a field access or an array access with
3305// constant inbounds index.
3306bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3307 Value *Addr, uint64_t TypeSize) const {
3308 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3309 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003310 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003311 int64_t Offset = SizeOffset.second.getSExtValue();
3312 // Three checks are required to ensure safety:
3313 // . Offset >= 0 (since the offset is given from the base ptr)
3314 // . Size >= Offset (unsigned)
3315 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003316 return Offset >= 0 && Size >= uint64_t(Offset) &&
3317 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003318}