blob: 1a007b4258f32646ce5d9ac7ac0997b184b207ad [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
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000015#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000016#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000017#include "llvm/ADT/DepthFirstIterator.h"
Florian Hahna1cc8482018-06-12 11:16:56 +000018#include "llvm/ADT/SmallPtrSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000019#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000020#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000022#include "llvm/ADT/StringRef.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000023#include "llvm/ADT/Triple.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000024#include "llvm/ADT/Twine.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
Leonard Chaneebecb32018-10-26 22:51:51 +000027#include "llvm/Transforms/Utils/Local.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000028#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"
74#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000075#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000076#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000077#include <cassert>
78#include <cstddef>
79#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000080#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000081#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000082#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000083#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000084#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000085#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000086
87using namespace llvm;
88
Chandler Carruth964daaa2014-04-22 02:55:47 +000089#define DEBUG_TYPE "asan"
90
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000091static const uint64_t kDefaultShadowScale = 3;
92static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
93static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000094static const uint64_t kDynamicShadowSentinel =
95 std::numeric_limits<uint64_t>::max();
Anna Zaks3b50e702016-02-02 22:05:07 +000096static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
98static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Walter Lee8f1545c2017-11-16 17:03:00 +000099static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
100static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000101static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Bill Seurer957a0762017-12-07 22:53:33 +0000102static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000103static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000104static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000105static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000106static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000107static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
108static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000109static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000110static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000111static const uint64_t kNetBSDKasan_ShadowOffset64 = 0xdfff900000000000;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000112static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000113static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000114
Walter Leecdbb2072018-05-18 04:10:38 +0000115static const uint64_t kMyriadShadowScale = 5;
116static const uint64_t kMyriadMemoryOffset32 = 0x80000000ULL;
117static const uint64_t kMyriadMemorySize32 = 0x20000000ULL;
118static const uint64_t kMyriadTagShift = 29;
119static const uint64_t kMyriadDDRTag = 4;
120static const uint64_t kMyriadCacheBitMask32 = 0x40000000ULL;
121
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000122// The shadow memory space is dynamically allocated.
123static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000124
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000125static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000126static const size_t kMaxStackMallocSize = 1 << 16; // 64K
127static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
128static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
129
Craig Topperd3a34f82013-07-16 01:17:10 +0000130static const char *const kAsanModuleCtorName = "asan.module_ctor";
131static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000132static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000133static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000134static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000135static const char *const kAsanUnregisterGlobalsName =
136 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000137static const char *const kAsanRegisterImageGlobalsName =
138 "__asan_register_image_globals";
139static const char *const kAsanUnregisterImageGlobalsName =
140 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000141static const char *const kAsanRegisterElfGlobalsName =
142 "__asan_register_elf_globals";
143static const char *const kAsanUnregisterElfGlobalsName =
144 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000145static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
146static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000147static const char *const kAsanInitName = "__asan_init";
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000148static const char *const kAsanVersionCheckNamePrefix =
149 "__asan_version_mismatch_check_v";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000150static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
151static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000152static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000153static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000154static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
155static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Peter Collingbourne4a653fa2018-07-18 22:23:14 +0000156static const char *const kAsanGenPrefix = "___asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000157static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000158static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000159static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000160static const char *const kAsanPoisonStackMemoryName =
161 "__asan_poison_stack_memory";
162static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000163 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000164
165// ASan version script has __asan_* wildcard. Triple underscore prevents a
166// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000167static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000168 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000169
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000170static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000171 "__asan_option_detect_stack_use_after_return";
172
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000173static const char *const kAsanShadowMemoryDynamicAddress =
174 "__asan_shadow_memory_dynamic_address";
175
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000176static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
177static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000178
Kostya Serebryany874dae62012-07-16 16:15:40 +0000179// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
180static const size_t kNumberOfAccessSizes = 5;
181
Yury Gribov55441bb2014-11-21 10:29:50 +0000182static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000183
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000184// Command-line flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000185
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000186static cl::opt<bool> ClEnableKasan(
187 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
188 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000189
Yury Gribovd7731982015-11-11 10:36:49 +0000190static cl::opt<bool> ClRecover(
191 "asan-recover",
192 cl::desc("Enable recovery mode (continue-after-error)."),
193 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000194
195// This flag may need to be replaced with -f[no-]asan-reads.
196static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::desc("instrument read instructions"),
198 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000199
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200static cl::opt<bool> ClInstrumentWrites(
201 "asan-instrument-writes", cl::desc("instrument write instructions"),
202 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000203
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000204static cl::opt<bool> ClInstrumentAtomics(
205 "asan-instrument-atomics",
206 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
207 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000208
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209static cl::opt<bool> ClAlwaysSlowPath(
210 "asan-always-slow-path",
211 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
212 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000213
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000214static cl::opt<bool> ClForceDynamicShadow(
215 "asan-force-dynamic-shadow",
216 cl::desc("Load shadow address into a local variable for each function"),
217 cl::Hidden, cl::init(false));
218
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000219static cl::opt<bool>
220 ClWithIfunc("asan-with-ifunc",
221 cl::desc("Access dynamic shadow through an ifunc global on "
222 "platforms that support this"),
223 cl::Hidden, cl::init(true));
224
225static cl::opt<bool> ClWithIfuncSuppressRemat(
226 "asan-with-ifunc-suppress-remat",
227 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
228 "it through inline asm in prologue."),
229 cl::Hidden, cl::init(true));
230
Kostya Serebryany874dae62012-07-16 16:15:40 +0000231// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000232// in any given BB. Normally, this should be set to unlimited (INT_MAX),
233// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
234// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000235static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
236 "asan-max-ins-per-bb", cl::init(10000),
237 cl::desc("maximal number of instructions to instrument in any given BB"),
238 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000239
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000240// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000241static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
242 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000243static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
244 "asan-max-inline-poisoning-size",
245 cl::desc(
246 "Inline shadow poisoning for blocks up to the given size in bytes."),
247 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000248
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000249static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000250 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000251 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000252
Vitaly Buka74443f02017-07-18 22:28:03 +0000253static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
254 cl::desc("Create redzones for byval "
255 "arguments (extra copy "
256 "required)"), cl::Hidden,
257 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000258
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000259static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
260 cl::desc("Check stack-use-after-scope"),
261 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000262
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000263// This flag may need to be replaced with -f[no]asan-globals.
264static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000265 cl::desc("Handle global objects"), cl::Hidden,
266 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000267
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000268static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000269 cl::desc("Handle C++ initializer order"),
270 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000271
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000272static cl::opt<bool> ClInvalidPointerPairs(
273 "asan-detect-invalid-pointer-pair",
274 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
275 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000276
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000277static cl::opt<unsigned> ClRealignStack(
278 "asan-realign-stack",
279 cl::desc("Realign stack to the value of this flag (power of two)"),
280 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000281
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000282static cl::opt<int> ClInstrumentationWithCallsThreshold(
283 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284 cl::desc(
285 "If the function being instrumented contains more than "
286 "this number of memory accesses, use callbacks instead of "
287 "inline checks (-1 means never use callbacks)."),
288 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000289
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000290static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000291 "asan-memory-access-callback-prefix",
292 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
293 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000294
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000295static cl::opt<bool>
296 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
297 cl::desc("instrument dynamic allocas"),
298 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000299
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300static cl::opt<bool> ClSkipPromotableAllocas(
301 "asan-skip-promotable-allocas",
302 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
303 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000304
305// These flags allow to change the shadow mapping.
306// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000307// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000308
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000309static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000310 cl::desc("scale of asan shadow mapping"),
311 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000312
Ryan Govostes6194ae62016-05-06 11:22:11 +0000313static cl::opt<unsigned long long> ClMappingOffset(
314 "asan-mapping-offset",
315 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
316 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000317
318// Optimization flags. Not user visible, used mostly for testing
319// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000320
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000321static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
322 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000323
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000324static cl::opt<bool> ClOptSameTemp(
325 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
326 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000327
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000328static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000329 cl::desc("Don't instrument scalar globals"),
330 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000331
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000332static cl::opt<bool> ClOptStack(
333 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
334 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000335
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000336static cl::opt<bool> ClDynamicAllocaStack(
337 "asan-stack-dynamic-alloca",
338 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000339 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000340
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000341static cl::opt<uint32_t> ClForceExperiment(
342 "asan-force-experiment",
343 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
344 cl::init(0));
345
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000346static cl::opt<bool>
Vitaly Bukad6bab092018-12-04 23:17:41 +0000347 ClUsePrivateAlias("asan-use-private-alias",
348 cl::desc("Use private aliases for global variables"),
349 cl::Hidden, cl::init(false));
350
351static cl::opt<bool>
352 ClUseOdrIndicator("asan-use-odr-indicator",
353 cl::desc("Use odr indicators to improve ODR reporting"),
354 cl::Hidden, cl::init(false));
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000355
Ryan Govostese51401b2016-07-05 21:53:08 +0000356static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000357 ClUseGlobalsGC("asan-globals-live-support",
358 cl::desc("Use linker features to support dead "
359 "code stripping of globals"),
360 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000361
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000362// This is on by default even though there is a bug in gold:
363// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
364static cl::opt<bool>
365 ClWithComdat("asan-with-comdat",
366 cl::desc("Place ASan constructors in comdat sections"),
367 cl::Hidden, cl::init(true));
368
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000369// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000370
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000371static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
372 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000373
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000374static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
375 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000376
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000377static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
378 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000379
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000380static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
381 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000382
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000383static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000384 cl::Hidden, cl::init(-1));
385
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000386STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
387STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000388STATISTIC(NumOptimizedAccessesToGlobalVar,
389 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000390STATISTIC(NumOptimizedAccessesToStackVar,
391 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000392
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000393namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000394
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000395/// Frontend-provided metadata for source location.
396struct LocationMetadata {
397 StringRef Filename;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000398 int LineNo = 0;
399 int ColumnNo = 0;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000400
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000401 LocationMetadata() = default;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000402
403 bool empty() const { return Filename.empty(); }
404
405 void parse(MDNode *MDN) {
406 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000407 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
408 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000409 LineNo =
410 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
411 ColumnNo =
412 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000413 }
414};
415
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000416/// Frontend-provided metadata for global variables.
417class GlobalsMetadata {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000418public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000419 struct Entry {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000420 LocationMetadata SourceLoc;
421 StringRef Name;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000422 bool IsDynInit = false;
423 bool IsBlacklisted = false;
424
425 Entry() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000426 };
427
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000428 GlobalsMetadata() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000429
Keno Fischere03fae42015-12-05 14:42:34 +0000430 void reset() {
431 inited_ = false;
432 Entries.clear();
433 }
434
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000435 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000436 assert(!inited_);
437 inited_ = true;
438 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000439 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000440 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000441 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000442 assert(MDN->getNumOperands() == 5);
Kuba Mracek3760fc92018-12-18 21:20:17 +0000443 auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000444 // The optimizer may optimize away a global entirely.
Kuba Mracek3760fc92018-12-18 21:20:17 +0000445 if (!V) continue;
446 auto *StrippedV = V->stripPointerCasts();
447 auto *GV = dyn_cast<GlobalVariable>(StrippedV);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000448 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000449 // We can already have an entry for GV if it was merged with another
450 // global.
451 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000452 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
453 E.SourceLoc.parse(Loc);
454 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
455 E.Name = Name->getString();
456 ConstantInt *IsDynInit =
457 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000458 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000459 ConstantInt *IsBlacklisted =
460 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000461 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000462 }
463 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000464
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000465 /// Returns metadata entry for a given global.
466 Entry get(GlobalVariable *G) const {
467 auto Pos = Entries.find(G);
468 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000469 }
470
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000471private:
472 bool inited_ = false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000473 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000474};
475
Alexey Samsonov1345d352013-01-16 13:23:28 +0000476/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000477/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000478/// If InGlobal is true, then
479/// extern char __asan_shadow[];
480/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000481struct ShadowMapping {
482 int Scale;
483 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000484 bool OrShadowOffset;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000485 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000486};
487
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000488} // end anonymous namespace
489
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000490static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
491 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000492 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000493 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000494 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000495 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000496 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000497 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000498 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
499 TargetTriple.getArch() == Triple::ppc64le;
500 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
501 bool IsX86 = TargetTriple.getArch() == Triple::x86;
502 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
Alexander Richardson85e200e2018-06-25 16:49:20 +0000503 bool IsMIPS32 = TargetTriple.isMIPS32();
504 bool IsMIPS64 = TargetTriple.isMIPS64();
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000505 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000506 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000507 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000508 bool IsFuchsia = TargetTriple.isOSFuchsia();
Walter Leecdbb2072018-05-18 04:10:38 +0000509 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000510
511 ShadowMapping Mapping;
512
Walter Leecdbb2072018-05-18 04:10:38 +0000513 Mapping.Scale = IsMyriad ? kMyriadShadowScale : kDefaultShadowScale;
Walter Lee8f1545c2017-11-16 17:03:00 +0000514 if (ClMappingScale.getNumOccurrences() > 0) {
515 Mapping.Scale = ClMappingScale;
516 }
517
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000518 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000519 if (IsAndroid)
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000520 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000521 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000522 Mapping.Offset = kMIPS32_ShadowOffset32;
523 else if (IsFreeBSD)
524 Mapping.Offset = kFreeBSD_ShadowOffset32;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000525 else if (IsNetBSD)
526 Mapping.Offset = kNetBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000527 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000528 // If we're targeting iOS and x86, the binary is built for iOS simulator.
529 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000530 else if (IsWindows)
531 Mapping.Offset = kWindowsShadowOffset32;
Walter Leecdbb2072018-05-18 04:10:38 +0000532 else if (IsMyriad) {
533 uint64_t ShadowOffset = (kMyriadMemoryOffset32 + kMyriadMemorySize32 -
534 (kMyriadMemorySize32 >> Mapping.Scale));
535 Mapping.Offset = ShadowOffset - (kMyriadMemoryOffset32 >> Mapping.Scale);
536 }
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000537 else
538 Mapping.Offset = kDefaultShadowOffset32;
539 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000540 // Fuchsia is always PIE, which means that the beginning of the address
541 // space is always available.
542 if (IsFuchsia)
543 Mapping.Offset = 0;
544 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000545 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000546 else if (IsSystemZ)
547 Mapping.Offset = kSystemZ_ShadowOffset64;
John Baldwinc5d7e042018-08-01 22:51:13 +0000548 else if (IsFreeBSD && !IsMIPS64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000549 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowski15ae7382018-12-15 16:32:41 +0000550 else if (IsNetBSD) {
551 if (IsKasan)
552 Mapping.Offset = kNetBSDKasan_ShadowOffset64;
553 else
554 Mapping.Offset = kNetBSD_ShadowOffset64;
555 } else if (IsPS4CPU)
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000556 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000557 else if (IsLinux && IsX86_64) {
558 if (IsKasan)
559 Mapping.Offset = kLinuxKasan_ShadowOffset64;
560 else
Walter Lee8f1545c2017-11-16 17:03:00 +0000561 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
562 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
Etienne Bergeron70684f92016-06-21 15:07:29 +0000563 } else if (IsWindows && IsX86_64) {
564 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000565 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000566 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000567 else if (IsIOS)
568 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000569 // We are using dynamic shadow offset on the 64-bit devices.
570 Mapping.Offset =
571 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000572 else if (IsAArch64)
573 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000574 else
575 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000576 }
577
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000578 if (ClForceDynamicShadow) {
579 Mapping.Offset = kDynamicShadowSentinel;
580 }
581
Ryan Govostes3f37df02016-05-06 10:25:22 +0000582 if (ClMappingOffset.getNumOccurrences() > 0) {
583 Mapping.Offset = ClMappingOffset;
584 }
585
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000586 // OR-ing shadow offset if more efficient (at least on x86) if the offset
587 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000588 // offset is not necessary 1/8-th of the address space. On SystemZ,
589 // we could OR the constant in a single instruction, but it's more
590 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000591 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
592 !(Mapping.Offset & (Mapping.Offset - 1)) &&
593 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000594 bool IsAndroidWithIfuncSupport =
595 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
596 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000597
Alexey Samsonov1345d352013-01-16 13:23:28 +0000598 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000599}
600
Alexey Samsonov1345d352013-01-16 13:23:28 +0000601static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000602 // Redzone used for stack and globals is at least 32 bytes.
603 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000604 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000605}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000606
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000607namespace {
608
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000609/// AddressSanitizer: instrument the code in module to find memory bugs.
Leonard Chaneebecb32018-10-26 22:51:51 +0000610struct AddressSanitizer : public FunctionPass {
611 // Pass identification, replacement for typeid
612 static char ID;
613
614 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000615 bool UseAfterScope = false)
Leonard Chaneebecb32018-10-26 22:51:51 +0000616 : FunctionPass(ID), UseAfterScope(UseAfterScope || ClUseAfterScope) {
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000617 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
618 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
619 ClEnableKasan : CompileKernel;
Leonard Chaneebecb32018-10-26 22:51:51 +0000620 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
621 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000622
Leonard Chaneebecb32018-10-26 22:51:51 +0000623 StringRef getPassName() const override {
624 return "AddressSanitizerFunctionPass";
625 }
626
627 void getAnalysisUsage(AnalysisUsage &AU) const override {
628 AU.addRequired<DominatorTreeWrapperPass>();
629 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000630 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000631
Vitaly Buka21a9e572016-07-28 22:50:50 +0000632 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000633 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000634 if (AI.isArrayAllocation()) {
635 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000636 assert(CI && "non-constant array size");
637 ArraySize = CI->getZExtValue();
638 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000639 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000640 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000641 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000642 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000643 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000644
Anna Zaks8ed1d812015-02-27 03:12:36 +0000645 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000646 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000647
Anna Zaks8ed1d812015-02-27 03:12:36 +0000648 /// If it is an interesting memory access, return the PointerOperand
649 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000650 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
651 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000652 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000653 uint64_t *TypeSize, unsigned *Alignment,
654 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000655
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000656 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000657 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000658 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000659 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
660 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000661 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000662 void instrumentUnusualSizeOrAlignment(Instruction *I,
663 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000664 uint32_t TypeSize, bool IsWrite,
665 Value *SizeArgument, bool UseCalls,
666 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000667 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
668 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000669 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000670 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000671 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000672 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000673 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Leonard Chaneebecb32018-10-26 22:51:51 +0000674 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000675 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000676 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000677 void markEscapedLocalAllocas(Function &F);
Leonard Chaneebecb32018-10-26 22:51:51 +0000678 bool doInitialization(Module &M) override;
679 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000680
Yury Gribov3ae427d2014-12-01 08:47:58 +0000681 DominatorTree &getDominatorTree() const { return *DT; }
682
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000683private:
684 friend struct FunctionStackPoisoner;
685
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000686 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000687
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000688 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000689 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000690 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
691 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000692
Reid Kleckner2f907552015-07-21 17:40:14 +0000693 /// Helper to cleanup per-function state.
694 struct FunctionStateRAII {
695 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000696
Reid Kleckner2f907552015-07-21 17:40:14 +0000697 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
698 assert(Pass->ProcessedAllocas.empty() &&
699 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000700 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000701 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000702
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000703 ~FunctionStateRAII() {
704 Pass->LocalDynamicShadow = nullptr;
705 Pass->ProcessedAllocas.clear();
706 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000707 };
708
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000709 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000710 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000711 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000712 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000713 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000714 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000715 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000716 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000717 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000718 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000719 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000720 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000721
722 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000723 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
724 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000725
726 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000727 Function *AsanErrorCallbackSized[2][2];
728 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000729
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000730 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000731 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000732 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000733 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000734 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000735};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000736
Leonard Chaneebecb32018-10-26 22:51:51 +0000737class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000738public:
Leonard Chaneebecb32018-10-26 22:51:51 +0000739 // Pass identification, replacement for typeid
740 static char ID;
741
Yury Gribovd7731982015-11-11 10:36:49 +0000742 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000743 bool Recover = false,
Vitaly Buka8076c572018-12-05 01:44:31 +0000744 bool UseGlobalsGC = true,
745 bool UseOdrIndicator = false)
746 : ModulePass(ID), UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
747 // Enable aliases as they should have no downside with ODR indicators.
748 UsePrivateAlias(UseOdrIndicator || ClUsePrivateAlias),
749 UseOdrIndicator(UseOdrIndicator || ClUseOdrIndicator),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000750 // Not a typo: ClWithComdat is almost completely pointless without
751 // ClUseGlobalsGC (because then it only works on modules without
752 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
753 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
754 // argument is designed as workaround. Therefore, disable both
755 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
756 // do globals-gc.
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000757 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
Vitaly Buka8076c572018-12-05 01:44:31 +0000758 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
759 this->CompileKernel =
760 ClEnableKasan.getNumOccurrences() > 0 ? ClEnableKasan : CompileKernel;
Vitaly Buka537cfc02018-12-04 00:36:14 +0000761 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000762
Leonard Chaneebecb32018-10-26 22:51:51 +0000763 bool runOnModule(Module &M) override;
764 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000765
Mehdi Amini117296c2016-10-01 02:56:57 +0000766private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000767 void initializeCallbacks(Module &M);
768
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000769 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000770 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
771 ArrayRef<GlobalVariable *> ExtendedGlobals,
772 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000773 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
774 ArrayRef<GlobalVariable *> ExtendedGlobals,
775 ArrayRef<Constant *> MetadataInitializers,
776 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000777 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
778 ArrayRef<GlobalVariable *> ExtendedGlobals,
779 ArrayRef<Constant *> MetadataInitializers);
780 void
781 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
782 ArrayRef<GlobalVariable *> ExtendedGlobals,
783 ArrayRef<Constant *> MetadataInitializers);
784
785 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
786 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000787 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
788 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000789 IRBuilder<> CreateAsanModuleDtor(Module &M);
790
Kostya Serebryany20a79972012-11-22 03:18:50 +0000791 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000792 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000793 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000794 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000795 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000796 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000797 return RedzoneSizeForScale(Mapping.Scale);
798 }
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000799 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000800
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000801 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000802 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000803 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000804 bool UseGlobalsGC;
Vitaly Buka8076c572018-12-05 01:44:31 +0000805 bool UsePrivateAlias;
806 bool UseOdrIndicator;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000807 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000808 Type *IntptrTy;
809 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000810 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000811 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000812 Function *AsanPoisonGlobals;
813 Function *AsanUnpoisonGlobals;
814 Function *AsanRegisterGlobals;
815 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000816 Function *AsanRegisterImageGlobals;
817 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000818 Function *AsanRegisterElfGlobals;
819 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000820
821 Function *AsanCtorFunction = nullptr;
822 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000823};
824
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000825// Stack poisoning does not play well with exception handling.
826// When an exception is thrown, we essentially bypass the code
827// that unpoisones the stack. This is why the run-time library has
828// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
829// stack in the interceptor. This however does not work inside the
830// actual function which catches the exception. Most likely because the
831// compiler hoists the load of the shadow value somewhere too high.
832// This causes asan to report a non-existing bug on 453.povray.
833// It sounds like an LLVM bug.
834struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
835 Function &F;
836 AddressSanitizer &ASan;
837 DIBuilder DIB;
838 LLVMContext *C;
839 Type *IntptrTy;
840 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000841 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000842
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000843 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000844 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000845 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000846 unsigned StackAlignment;
847
Kostya Serebryany6805de52013-09-10 13:16:56 +0000848 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000849 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000850 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000851 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000852 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000853
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000854 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
855 struct AllocaPoisonCall {
856 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000857 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000858 uint64_t Size;
859 bool DoPoison;
860 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000861 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
862 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000863
Yury Gribov98b18592015-05-28 07:51:49 +0000864 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
865 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
866 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000867 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000868
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000869 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000870 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000871 AllocaForValueMapTy AllocaForValue;
872
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000873 bool HasNonEmptyInlineAsm = false;
874 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000875 std::unique_ptr<CallInst> EmptyInlineAsm;
876
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000877 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000878 : F(F),
879 ASan(ASan),
880 DIB(*F.getParent(), /*AllowUnresolved*/ false),
881 C(ASan.C),
882 IntptrTy(ASan.IntptrTy),
883 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
884 Mapping(ASan.Mapping),
885 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000886 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000887
888 bool runOnFunction() {
889 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000890
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000891 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000892 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000893
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000894 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000895 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000896
Yury Gribov55441bb2014-11-21 10:29:50 +0000897 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000898
899 initializeCallbacks(*F.getParent());
900
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000901 processDynamicAllocas();
902 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000903
904 if (ClDebugStack) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000905 LLVM_DEBUG(dbgs() << F);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000906 }
907 return true;
908 }
909
Vitaly Buka74443f02017-07-18 22:28:03 +0000910 // Arguments marked with the "byval" attribute are implicitly copied without
911 // using an alloca instruction. To produce redzones for those arguments, we
912 // copy them a second time into memory allocated with an alloca instruction.
913 void copyArgsPassedByValToAllocas();
914
Yury Gribov55441bb2014-11-21 10:29:50 +0000915 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000916 // poisoned red zones around all of them.
917 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000918 void processStaticAllocas();
919 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000920
Yury Gribov98b18592015-05-28 07:51:49 +0000921 void createDynamicAllocasInitStorage();
922
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000923 // ----------------------- Visitors.
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000924 /// Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000925 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000926
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000927 /// Collect all Resume instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000928 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
929
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000930 /// Collect all CatchReturnInst instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000931 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
932
Yury Gribov98b18592015-05-28 07:51:49 +0000933 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
934 Value *SavedStack) {
935 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000936 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
937 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
938 // need to adjust extracted SP to compute the address of the most recent
939 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
940 // this purpose.
941 if (!isa<ReturnInst>(InstBefore)) {
942 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
943 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
944 {IntptrTy});
945
946 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
947
948 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
949 DynamicAreaOffset);
950 }
951
Yury Gribov781bce22015-05-28 08:03:28 +0000952 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000953 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000954 }
955
Yury Gribov55441bb2014-11-21 10:29:50 +0000956 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000957 void unpoisonDynamicAllocas() {
958 for (auto &Ret : RetVec)
959 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000960
Yury Gribov98b18592015-05-28 07:51:49 +0000961 for (auto &StackRestoreInst : StackRestoreVec)
962 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
963 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000964 }
965
Yury Gribov55441bb2014-11-21 10:29:50 +0000966 // Deploy and poison redzones around dynamic alloca call. To do this, we
967 // should replace this call with another one with changed parameters and
968 // replace all its uses with new address, so
969 // addr = alloca type, old_size, align
970 // is replaced by
971 // new_size = (old_size + additional_size) * sizeof(type)
972 // tmp = alloca i8, new_size, max(align, 32)
973 // addr = tmp + 32 (first 32 bytes are for the left redzone).
974 // Additional_size is added to make new memory allocation contain not only
975 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000976 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000977
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000978 /// Collect Alloca instructions we want (and can) handle.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000979 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000980 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000981 if (AI.isStaticAlloca()) {
982 // Skip over allocas that are present *before* the first instrumented
983 // alloca, we don't want to move those around.
984 if (AllocaVec.empty())
985 return;
986
987 StaticAllocasToMoveUp.push_back(&AI);
988 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000989 return;
990 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000991
992 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000993 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000994 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000995 else
996 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000997 }
998
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000999 /// Collect lifetime intrinsic calls to check for use-after-scope
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001000 /// errors.
1001 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001002 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +00001003 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +00001004 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001005 if (!ASan.UseAfterScope)
1006 return;
Vedant Kumarb264d692018-12-21 21:49:40 +00001007 if (!II.isLifetimeStartOrEnd())
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001008 return;
1009 // Found lifetime intrinsic, add ASan instrumentation if necessary.
1010 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
1011 // If size argument is undefined, don't do anything.
1012 if (Size->isMinusOne()) return;
1013 // Check that size doesn't saturate uint64_t and can
1014 // be stored in IntptrTy.
1015 const uint64_t SizeValue = Size->getValue().getLimitedValue();
1016 if (SizeValue == ~0ULL ||
1017 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
1018 return;
1019 // Find alloca instruction that corresponds to llvm.lifetime argument.
1020 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +00001021 if (!AI || !ASan.isInterestingAlloca(*AI))
1022 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001023 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +00001024 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +00001025 if (AI->isStaticAlloca())
1026 StaticAllocaPoisonCallVec.push_back(APC);
1027 else if (ClInstrumentDynamicAllocas)
1028 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001029 }
1030
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001031 void visitCallSite(CallSite CS) {
1032 Instruction *I = CS.getInstruction();
1033 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00001034 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1035 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1036 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001037 HasReturnsTwiceCall |= CI->canReturnTwice();
1038 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001039 }
1040
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001041 // ---------------------- Helpers.
1042 void initializeCallbacks(Module &M);
1043
Yury Gribov3ae427d2014-12-01 08:47:58 +00001044 bool doesDominateAllExits(const Instruction *I) const {
1045 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001046 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001047 }
1048 return true;
1049 }
1050
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001051 /// Finds alloca where the value comes from.
1052 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001053
1054 // Copies bytes from ShadowBytes into shadow memory for indexes where
1055 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1056 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1057 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1058 IRBuilder<> &IRB, Value *ShadowBase);
1059 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1060 size_t Begin, size_t End, IRBuilder<> &IRB,
1061 Value *ShadowBase);
1062 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1063 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1064 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1065
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001066 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001067
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001068 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1069 bool Dynamic);
1070 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1071 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001072};
1073
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001074} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001075
Leonard Chaneebecb32018-10-26 22:51:51 +00001076char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001077
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001078INITIALIZE_PASS_BEGIN(
Leonard Chaneebecb32018-10-26 22:51:51 +00001079 AddressSanitizer, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001080 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1081 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001082INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001083INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001084INITIALIZE_PASS_END(
Leonard Chaneebecb32018-10-26 22:51:51 +00001085 AddressSanitizer, "asan",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001086 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1087 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001088
Yury Gribovd7731982015-11-11 10:36:49 +00001089FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001090 bool Recover,
1091 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001092 assert(!CompileKernel || Recover);
Leonard Chaneebecb32018-10-26 22:51:51 +00001093 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001094}
1095
Leonard Chaneebecb32018-10-26 22:51:51 +00001096char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001097
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001098INITIALIZE_PASS(
Leonard Chaneebecb32018-10-26 22:51:51 +00001099 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001100 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001101 "ModulePass",
1102 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001103
Yury Gribovd7731982015-11-11 10:36:49 +00001104ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001105 bool Recover,
Vitaly Buka8076c572018-12-05 01:44:31 +00001106 bool UseGlobalsGC,
1107 bool UseOdrIndicator) {
Yury Gribovd7731982015-11-11 10:36:49 +00001108 assert(!CompileKernel || Recover);
Vitaly Buka8076c572018-12-05 01:44:31 +00001109 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC,
1110 UseOdrIndicator);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001111}
1112
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001113static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001114 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001115 assert(Res < kNumberOfAccessSizes);
1116 return Res;
1117}
1118
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001119/// Create a global describing a source location.
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001120static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1121 LocationMetadata MD) {
1122 Constant *LocData[] = {
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00001123 createPrivateGlobalForString(M, MD.Filename, true, kAsanGenPrefix),
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001124 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1125 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1126 };
1127 auto LocStruct = ConstantStruct::getAnon(LocData);
1128 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1129 GlobalValue::PrivateLinkage, LocStruct,
1130 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001131 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001132 return GV;
1133}
1134
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001135/// Check if \p G has been created by a trusted compiler pass.
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001136static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
Reid Kleckner85a8c122018-08-20 23:35:45 +00001137 // Do not instrument @llvm.global_ctors, @llvm.used, etc.
1138 if (G->getName().startswith("llvm."))
1139 return true;
1140
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001141 // Do not instrument asan globals.
1142 if (G->getName().startswith(kAsanGenPrefix) ||
1143 G->getName().startswith(kSanCovGenPrefix) ||
1144 G->getName().startswith(kODRGenPrefix))
1145 return true;
1146
1147 // Do not instrument gcov counter arrays.
1148 if (G->getName() == "__llvm_gcov_ctr")
1149 return true;
1150
1151 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001152}
1153
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001154Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1155 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001156 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001157 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001158 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001159 Value *ShadowBase;
1160 if (LocalDynamicShadow)
1161 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001162 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001163 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1164 if (Mapping.OrShadowOffset)
1165 return IRB.CreateOr(Shadow, ShadowBase);
1166 else
1167 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001168}
1169
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001170// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001171void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1172 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001173 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001174 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001175 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001176 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1177 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1178 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001179 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001180 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001181 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001182 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1183 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1184 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001185 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001186 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001187}
1188
Anna Zaks8ed1d812015-02-27 03:12:36 +00001189/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001190bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001191 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1192
1193 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1194 return PreviouslySeenAllocaInfo->getSecond();
1195
Yury Gribov98b18592015-05-28 07:51:49 +00001196 bool IsInteresting =
1197 (AI.getAllocatedType()->isSized() &&
1198 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001199 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001200 // We are only interested in allocas not promotable to registers.
1201 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001202 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1203 // inalloca allocas are not treated as static, and we don't want
1204 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001205 !AI.isUsedWithInAlloca() &&
1206 // swifterror allocas are register promoted by ISel
1207 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001208
1209 ProcessedAllocas[&AI] = IsInteresting;
1210 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001211}
1212
Anna Zaks8ed1d812015-02-27 03:12:36 +00001213Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1214 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001215 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001216 unsigned *Alignment,
1217 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001218 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001219 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001220
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001221 // Do not instrument the load fetching the dynamic shadow address.
1222 if (LocalDynamicShadow == I)
1223 return nullptr;
1224
Anna Zaks8ed1d812015-02-27 03:12:36 +00001225 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001226 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001227 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001228 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001229 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001230 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001231 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001232 PtrOperand = LI->getPointerOperand();
1233 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001234 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001235 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001236 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001237 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001238 PtrOperand = SI->getPointerOperand();
1239 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001240 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001241 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001242 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001243 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001244 PtrOperand = RMW->getPointerOperand();
1245 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001246 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001247 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001248 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001249 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001250 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001251 } else if (auto CI = dyn_cast<CallInst>(I)) {
1252 auto *F = dyn_cast<Function>(CI->getCalledValue());
1253 if (F && (F->getName().startswith("llvm.masked.load.") ||
1254 F->getName().startswith("llvm.masked.store."))) {
1255 unsigned OpOffset = 0;
1256 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001257 if (!ClInstrumentWrites)
1258 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001259 // Masked store has an initial operand for the value.
1260 OpOffset = 1;
1261 *IsWrite = true;
1262 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001263 if (!ClInstrumentReads)
1264 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001265 *IsWrite = false;
1266 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001267
1268 auto BasePtr = CI->getOperand(0 + OpOffset);
1269 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1270 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1271 if (auto AlignmentConstant =
1272 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1273 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1274 else
1275 *Alignment = 1; // No alignment guarantees. We probably got Undef
1276 if (MaybeMask)
1277 *MaybeMask = CI->getOperand(2 + OpOffset);
1278 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001279 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001280 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001281
Anna Zaks644d9d32016-06-22 00:15:52 +00001282 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001283 // Do not instrument acesses from different address spaces; we cannot deal
1284 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001285 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1286 if (PtrTy->getPointerAddressSpace() != 0)
1287 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001288
1289 // Ignore swifterror addresses.
1290 // swifterror memory addresses are mem2reg promoted by instruction
1291 // selection. As such they cannot have regular uses like an instrumentation
1292 // function and it makes no sense to track them as memory.
1293 if (PtrOperand->isSwiftError())
1294 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001295 }
1296
Anna Zaks8ed1d812015-02-27 03:12:36 +00001297 // Treat memory accesses to promotable allocas as non-interesting since they
1298 // will not cause memory violations. This greatly speeds up the instrumented
1299 // executable at -O0.
1300 if (ClSkipPromotableAllocas)
1301 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1302 return isInterestingAlloca(*AI) ? AI : nullptr;
1303
1304 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001305}
1306
Kostya Serebryany796f6552014-02-27 12:45:36 +00001307static bool isPointerOperand(Value *V) {
1308 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1309}
1310
1311// This is a rough heuristic; it may cause both false positives and
1312// false negatives. The proper implementation requires cooperation with
1313// the frontend.
1314static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1315 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001316 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001317 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001318 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001319 } else {
1320 return false;
1321 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001322 return isPointerOperand(I->getOperand(0)) &&
1323 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001324}
1325
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001326bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1327 // If a global variable does not have dynamic initialization we don't
1328 // have to instrument it. However, if a global does not have initializer
1329 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001330 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001331}
1332
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001333void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1334 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001335 IRBuilder<> IRB(I);
1336 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1337 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001338 for (Value *&i : Param) {
1339 if (i->getType()->isPointerTy())
1340 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001341 }
David Blaikieff6409d2015-05-18 22:13:54 +00001342 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001343}
1344
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001345static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001346 Instruction *InsertBefore, Value *Addr,
1347 unsigned Alignment, unsigned Granularity,
1348 uint32_t TypeSize, bool IsWrite,
1349 Value *SizeArgument, bool UseCalls,
1350 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001351 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1352 // if the data is properly aligned.
1353 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1354 TypeSize == 128) &&
1355 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001356 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1357 nullptr, UseCalls, Exp);
1358 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1359 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001360}
1361
1362static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1363 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001364 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001365 Value *Addr, unsigned Alignment,
1366 unsigned Granularity, uint32_t TypeSize,
1367 bool IsWrite, Value *SizeArgument,
1368 bool UseCalls, uint32_t Exp) {
1369 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1370 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1371 unsigned Num = VTy->getVectorNumElements();
1372 auto Zero = ConstantInt::get(IntptrTy, 0);
1373 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001374 Value *InstrumentedAddress = nullptr;
1375 Instruction *InsertBefore = I;
1376 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1377 // dyn_cast as we might get UndefValue
1378 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001379 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001380 // Mask is constant false, so no instrumentation needed.
1381 continue;
1382 // If we have a true or undef value, fall through to doInstrumentAddress
1383 // with InsertBefore == I
1384 }
1385 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001386 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001387 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001388 Instruction *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001389 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001390 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001391
1392 IRBuilder<> IRB(InsertBefore);
1393 InstrumentedAddress =
1394 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1395 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1396 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1397 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001398 }
1399}
1400
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001401void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001402 Instruction *I, bool UseCalls,
1403 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001404 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001405 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001406 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001407 Value *MaybeMask = nullptr;
1408 Value *Addr =
1409 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001410 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001411
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001412 // Optimization experiments.
1413 // The experiments can be used to evaluate potential optimizations that remove
1414 // instrumentation (assess false negatives). Instead of completely removing
1415 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1416 // experiments that want to remove instrumentation of this instruction).
1417 // If Exp is non-zero, this pass will emit special calls into runtime
1418 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1419 // make runtime terminate the program in a special way (with a different
1420 // exit status). Then you run the new compiler on a buggy corpus, collect
1421 // the special terminations (ideally, you don't see them at all -- no false
1422 // negatives) and make the decision on the optimization.
1423 uint32_t Exp = ClForceExperiment;
1424
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001425 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001426 // If initialization order checking is disabled, a simple access to a
1427 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001428 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001429 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001430 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1431 NumOptimizedAccessesToGlobalVar++;
1432 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001433 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001434 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001435
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001436 if (ClOpt && ClOptStack) {
1437 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001439 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1440 NumOptimizedAccessesToStackVar++;
1441 return;
1442 }
1443 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001444
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001445 if (IsWrite)
1446 NumInstrumentedWrites++;
1447 else
1448 NumInstrumentedReads++;
1449
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001450 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001451 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001452 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1453 Alignment, Granularity, TypeSize, IsWrite,
1454 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001455 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001456 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001457 IsWrite, nullptr, UseCalls, Exp);
1458 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001459}
1460
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001461Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1462 Value *Addr, bool IsWrite,
1463 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001464 Value *SizeArgument,
1465 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001466 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001467 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1468 CallInst *Call = nullptr;
1469 if (SizeArgument) {
1470 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001471 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1472 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001473 else
David Blaikieff6409d2015-05-18 22:13:54 +00001474 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1475 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001476 } else {
1477 if (Exp == 0)
1478 Call =
1479 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1480 else
David Blaikieff6409d2015-05-18 22:13:54 +00001481 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1482 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001483 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001484
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001485 // We don't do Call->setDoesNotReturn() because the BB already has
1486 // UnreachableInst at the end.
1487 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001488 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001489 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001490}
1491
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001492Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001493 Value *ShadowValue,
1494 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001495 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001496 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001497 Value *LastAccessedByte =
1498 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001499 // (Addr & (Granularity - 1)) + size - 1
1500 if (TypeSize / 8 > 1)
1501 LastAccessedByte = IRB.CreateAdd(
1502 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1503 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001504 LastAccessedByte =
1505 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001506 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1507 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1508}
1509
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001510void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001511 Instruction *InsertBefore, Value *Addr,
1512 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001513 Value *SizeArgument, bool UseCalls,
1514 uint32_t Exp) {
Walter Leecdbb2072018-05-18 04:10:38 +00001515 bool IsMyriad = TargetTriple.getVendor() == llvm::Triple::Myriad;
1516
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001517 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001518 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001519 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1520
1521 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001522 if (Exp == 0)
1523 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1524 AddrLong);
1525 else
David Blaikieff6409d2015-05-18 22:13:54 +00001526 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1527 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001528 return;
1529 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530
Walter Leecdbb2072018-05-18 04:10:38 +00001531 if (IsMyriad) {
1532 // Strip the cache bit and do range check.
1533 // AddrLong &= ~kMyriadCacheBitMask32
1534 AddrLong = IRB.CreateAnd(AddrLong, ~kMyriadCacheBitMask32);
1535 // Tag = AddrLong >> kMyriadTagShift
1536 Value *Tag = IRB.CreateLShr(AddrLong, kMyriadTagShift);
1537 // Tag == kMyriadDDRTag
1538 Value *TagCheck =
1539 IRB.CreateICmpEQ(Tag, ConstantInt::get(IntptrTy, kMyriadDDRTag));
1540
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001541 Instruction *TagCheckTerm =
1542 SplitBlockAndInsertIfThen(TagCheck, InsertBefore, false,
1543 MDBuilder(*C).createBranchWeights(1, 100000));
Walter Leecdbb2072018-05-18 04:10:38 +00001544 assert(cast<BranchInst>(TagCheckTerm)->isUnconditional());
1545 IRB.SetInsertPoint(TagCheckTerm);
1546 InsertBefore = TagCheckTerm;
1547 }
1548
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001549 Type *ShadowTy =
1550 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001551 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1552 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1553 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001554 Value *ShadowValue =
1555 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001556
1557 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001558 size_t Granularity = 1ULL << Mapping.Scale;
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001559 Instruction *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001560
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001561 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001562 // We use branch weights for the slow path check, to indicate that the slow
1563 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00001564 Instruction *CheckTerm = SplitBlockAndInsertIfThen(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001565 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001566 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001567 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001568 IRB.SetInsertPoint(CheckTerm);
1569 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001570 if (Recover) {
1571 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1572 } else {
1573 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001574 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001575 CrashTerm = new UnreachableInst(*C, CrashBlock);
1576 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1577 ReplaceInstWithInst(CheckTerm, NewTerm);
1578 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001579 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001580 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001581 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001582
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001583 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001584 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001585 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001586}
1587
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001588// Instrument unusual size or unusual alignment.
1589// We can not do it with a single check, so we do 1-byte check for the first
1590// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1591// to report the actual access size.
1592void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001593 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1594 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1595 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001596 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1597 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1598 if (UseCalls) {
1599 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001600 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1601 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001602 else
David Blaikieff6409d2015-05-18 22:13:54 +00001603 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1604 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001605 } else {
1606 Value *LastByte = IRB.CreateIntToPtr(
1607 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1608 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001609 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1610 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001611 }
1612}
1613
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001614void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1615 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001616 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001617 IRBuilder<> IRB(&GlobalInit.front(),
1618 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001619
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001620 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001621 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1622 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001623
1624 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001625 for (auto &BB : GlobalInit.getBasicBlockList())
1626 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001627 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001628}
1629
1630void AddressSanitizerModule::createInitializerPoisonCalls(
1631 Module &M, GlobalValue *ModuleName) {
1632 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001633 if (!GV)
1634 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001635
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001636 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1637 if (!CA)
1638 return;
1639
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001640 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001641 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001642 ConstantStruct *CS = cast<ConstantStruct>(OP);
1643
1644 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001645 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001646 if (F->getName() == kAsanModuleCtorName) continue;
1647 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1648 // Don't instrument CTORs that will run before asan.module_ctor.
1649 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1650 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001651 }
1652 }
1653}
1654
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001655bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001656 Type *Ty = G->getValueType();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001657 LLVM_DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001658
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001659 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001660 if (!Ty->isSized()) return false;
1661 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001662 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001663 // Two problems with thread-locals:
1664 // - The address of the main thread's copy can't be computed at link-time.
1665 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001666 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001667 // For now, just ignore this Global if the alignment is large.
1668 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001669
Reid Kleckner85a8c122018-08-20 23:35:45 +00001670 // For non-COFF targets, only instrument globals known to be defined by this
1671 // TU.
1672 // FIXME: We can instrument comdat globals on ELF if we are using the
1673 // GC-friendly metadata scheme.
1674 if (!TargetTriple.isOSBinFormatCOFF()) {
1675 if (!G->hasExactDefinition() || G->hasComdat())
1676 return false;
1677 } else {
1678 // On COFF, don't instrument non-ODR linkages.
1679 if (G->isInterposable())
1680 return false;
1681 }
1682
1683 // If a comdat is present, it must have a selection kind that implies ODR
1684 // semantics: no duplicates, any, or exact match.
1685 if (Comdat *C = G->getComdat()) {
1686 switch (C->getSelectionKind()) {
1687 case Comdat::Any:
1688 case Comdat::ExactMatch:
1689 case Comdat::NoDuplicates:
1690 break;
1691 case Comdat::Largest:
1692 case Comdat::SameSize:
1693 return false;
1694 }
1695 }
1696
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001697 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001698 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001699
Anna Zaks11904602015-06-09 00:58:08 +00001700 // Globals from llvm.metadata aren't emitted, do not instrument them.
1701 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001702 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001703 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001704
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001705 // Do not instrument function pointers to initialization and termination
1706 // routines: dynamic linker will not properly handle redzones.
1707 if (Section.startswith(".preinit_array") ||
1708 Section.startswith(".init_array") ||
1709 Section.startswith(".fini_array")) {
1710 return false;
1711 }
1712
Reid Kleckner12395b72018-06-13 20:47:21 +00001713 // On COFF, if the section name contains '$', it is highly likely that the
1714 // user is using section sorting to create an array of globals similar to
1715 // the way initialization callbacks are registered in .init_array and
1716 // .CRT$XCU. The ATL also registers things in .ATL$__[azm]. Adding redzones
1717 // to such globals is counterproductive, because the intent is that they
1718 // will form an array, and out-of-bounds accesses are expected.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001719 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001720 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
Reid Kleckner12395b72018-06-13 20:47:21 +00001721 if (TargetTriple.isOSBinFormatCOFF() && Section.contains('$')) {
1722 LLVM_DEBUG(dbgs() << "Ignoring global in sorted section (contains '$'): "
1723 << *G << "\n");
Anna Zaks11904602015-06-09 00:58:08 +00001724 return false;
1725 }
1726
Kuba Brecka1001bb52014-12-05 22:19:18 +00001727 if (TargetTriple.isOSBinFormatMachO()) {
1728 StringRef ParsedSegment, ParsedSection;
1729 unsigned TAA = 0, StubSize = 0;
1730 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001731 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1732 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001733 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001734
1735 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1736 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1737 // them.
1738 if (ParsedSegment == "__OBJC" ||
1739 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001740 LLVM_DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001741 return false;
1742 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001743 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001744 // Constant CFString instances are compiled in the following way:
1745 // -- the string buffer is emitted into
1746 // __TEXT,__cstring,cstring_literals
1747 // -- the constant NSConstantString structure referencing that buffer
1748 // is placed into __DATA,__cfstring
1749 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1750 // Moreover, it causes the linker to crash on OS X 10.7
1751 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001752 LLVM_DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001753 return false;
1754 }
1755 // The linker merges the contents of cstring_literals and removes the
1756 // trailing zeroes.
1757 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001758 LLVM_DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001759 return false;
1760 }
1761 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001762 }
1763
1764 return true;
1765}
1766
Ryan Govostes653f9d02016-03-28 20:28:57 +00001767// On Mach-O platforms, we emit global metadata in a separate section of the
1768// binary in order to allow the linker to properly dead strip. This is only
1769// supported on recent versions of ld64.
1770bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1771 if (!TargetTriple.isOSBinFormatMachO())
1772 return false;
1773
1774 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1775 return true;
1776 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001777 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001778 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1779 return true;
1780
1781 return false;
1782}
1783
Reid Kleckner01660a32016-11-21 20:40:37 +00001784StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1785 switch (TargetTriple.getObjectFormat()) {
1786 case Triple::COFF: return ".ASAN$GL";
1787 case Triple::ELF: return "asan_globals";
1788 case Triple::MachO: return "__DATA,__asan_globals,regular";
1789 default: break;
1790 }
1791 llvm_unreachable("unsupported object format");
1792}
1793
Alexey Samsonov788381b2012-12-25 12:28:20 +00001794void AddressSanitizerModule::initializeCallbacks(Module &M) {
1795 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001796
Alexey Samsonov788381b2012-12-25 12:28:20 +00001797 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001798 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001799 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001800 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001801 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001802 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001803 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001804
Alexey Samsonov788381b2012-12-25 12:28:20 +00001805 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001806 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001807 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001808 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001809 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1810 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001811 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001812 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001813
1814 // Declare the functions that find globals in a shared object and then invoke
1815 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001816 AsanRegisterImageGlobals =
1817 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001818 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001819 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001820
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001821 AsanUnregisterImageGlobals =
1822 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001823 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001824 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001825
1826 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1827 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1828 IntptrTy, IntptrTy, IntptrTy));
1829 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1830
1831 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1832 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1833 IntptrTy, IntptrTy, IntptrTy));
1834 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001835}
1836
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001837// Put the metadata and the instrumented global in the same group. This ensures
1838// that the metadata is discarded if the instrumented global is discarded.
1839void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001840 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001841 Module &M = *G->getParent();
1842 Comdat *C = G->getComdat();
1843 if (!C) {
1844 if (!G->hasName()) {
1845 // If G is unnamed, it must be internal. Give it an artificial name
1846 // so we can put it in a comdat.
1847 assert(G->hasLocalLinkage());
1848 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1849 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001850
1851 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1852 std::string Name = G->getName();
1853 Name += InternalSuffix;
1854 C = M.getOrInsertComdat(Name);
1855 } else {
1856 C = M.getOrInsertComdat(G->getName());
1857 }
1858
Reid Klecknerc212cc82017-10-31 16:16:08 +00001859 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1860 // linkage to internal linkage so that a symbol table entry is emitted. This
1861 // is necessary in order to create the comdat group.
1862 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001863 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001864 if (G->hasPrivateLinkage())
1865 G->setLinkage(GlobalValue::InternalLinkage);
1866 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001867 G->setComdat(C);
1868 }
1869
1870 assert(G->hasComdat());
1871 Metadata->setComdat(G->getComdat());
1872}
1873
1874// Create a separate metadata global and put it in the appropriate ASan
1875// global registration section.
1876GlobalVariable *
1877AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1878 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001879 auto Linkage = TargetTriple.isOSBinFormatMachO()
1880 ? GlobalVariable::InternalLinkage
1881 : GlobalVariable::PrivateLinkage;
1882 GlobalVariable *Metadata = new GlobalVariable(
1883 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001884 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001885 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001886 return Metadata;
1887}
1888
1889IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001890 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001891 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1892 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1893 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001894
1895 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1896}
1897
1898void AddressSanitizerModule::InstrumentGlobalsCOFF(
1899 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1900 ArrayRef<Constant *> MetadataInitializers) {
1901 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001902 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001903
1904 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001905 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001906 GlobalVariable *G = ExtendedGlobals[i];
1907 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001908 CreateMetadataGlobal(M, Initializer, G->getName());
1909
1910 // The MSVC linker always inserts padding when linking incrementally. We
1911 // cope with that by aligning each struct to its size, which must be a power
1912 // of two.
1913 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1914 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1915 "global metadata will not be padded appropriately");
1916 Metadata->setAlignment(SizeOfGlobalStruct);
1917
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001918 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001919 }
1920}
1921
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001922void AddressSanitizerModule::InstrumentGlobalsELF(
1923 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1924 ArrayRef<Constant *> MetadataInitializers,
1925 const std::string &UniqueModuleId) {
1926 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1927
1928 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1929 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1930 GlobalVariable *G = ExtendedGlobals[i];
1931 GlobalVariable *Metadata =
1932 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1933 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1934 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1935 MetadataGlobals[i] = Metadata;
1936
1937 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1938 }
1939
1940 // Update llvm.compiler.used, adding the new metadata globals. This is
1941 // needed so that during LTO these variables stay alive.
1942 if (!MetadataGlobals.empty())
1943 appendToCompilerUsed(M, MetadataGlobals);
1944
1945 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1946 // to look up the loaded image that contains it. Second, we can store in it
1947 // whether registration has already occurred, to prevent duplicate
1948 // registration.
1949 //
1950 // Common linkage ensures that there is only one global per shared library.
1951 GlobalVariable *RegisteredFlag = new GlobalVariable(
1952 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1953 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1954 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1955
1956 // Create start and stop symbols.
1957 GlobalVariable *StartELFMetadata = new GlobalVariable(
1958 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1959 "__start_" + getGlobalMetadataSection());
1960 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1961 GlobalVariable *StopELFMetadata = new GlobalVariable(
1962 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1963 "__stop_" + getGlobalMetadataSection());
1964 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1965
1966 // Create a call to register the globals with the runtime.
1967 IRB.CreateCall(AsanRegisterElfGlobals,
1968 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1969 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1970 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1971
1972 // We also need to unregister globals at the end, e.g., when a shared library
1973 // gets closed.
1974 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1975 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1976 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1977 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1978 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1979}
1980
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001981void AddressSanitizerModule::InstrumentGlobalsMachO(
1982 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1983 ArrayRef<Constant *> MetadataInitializers) {
1984 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1985
1986 // On recent Mach-O platforms, use a structure which binds the liveness of
1987 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1988 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001989 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001990 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1991
1992 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1993 Constant *Initializer = MetadataInitializers[i];
1994 GlobalVariable *G = ExtendedGlobals[i];
1995 GlobalVariable *Metadata =
1996 CreateMetadataGlobal(M, Initializer, G->getName());
1997
1998 // On recent Mach-O platforms, we emit the global metadata in a way that
1999 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00002000 auto LivenessBinder =
2001 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
2002 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002003 GlobalVariable *Liveness = new GlobalVariable(
2004 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
2005 Twine("__asan_binder_") + G->getName());
2006 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
2007 LivenessGlobals[i] = Liveness;
2008 }
2009
2010 // Update llvm.compiler.used, adding the new liveness globals. This is
2011 // needed so that during LTO these variables stay alive. The alternative
2012 // would be to have the linker handling the LTO symbols, but libLTO
2013 // current API does not expose access to the section for each symbol.
2014 if (!LivenessGlobals.empty())
2015 appendToCompilerUsed(M, LivenessGlobals);
2016
2017 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
2018 // to look up the loaded image that contains it. Second, we can store in it
2019 // whether registration has already occurred, to prevent duplicate
2020 // registration.
2021 //
2022 // common linkage ensures that there is only one global per shared library.
2023 GlobalVariable *RegisteredFlag = new GlobalVariable(
2024 M, IntptrTy, false, GlobalVariable::CommonLinkage,
2025 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
2026 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
2027
2028 IRB.CreateCall(AsanRegisterImageGlobals,
2029 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2030
2031 // We also need to unregister globals at the end, e.g., when a shared library
2032 // gets closed.
2033 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2034 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
2035 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
2036}
2037
2038void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
2039 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
2040 ArrayRef<Constant *> MetadataInitializers) {
2041 assert(ExtendedGlobals.size() == MetadataInitializers.size());
2042 unsigned N = ExtendedGlobals.size();
2043 assert(N > 0);
2044
2045 // On platforms that don't have a custom metadata section, we emit an array
2046 // of global metadata structures.
2047 ArrayType *ArrayOfGlobalStructTy =
2048 ArrayType::get(MetadataInitializers[0]->getType(), N);
2049 auto AllGlobals = new GlobalVariable(
2050 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
2051 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00002052 if (Mapping.Scale > 3)
2053 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002054
2055 IRB.CreateCall(AsanRegisterGlobals,
2056 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2057 ConstantInt::get(IntptrTy, N)});
2058
2059 // We also need to unregister globals at the end, e.g., when a shared library
2060 // gets closed.
2061 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2062 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2063 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2064 ConstantInt::get(IntptrTy, N)});
2065}
2066
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002067// This function replaces all global variables with new variables that have
2068// trailing redzones. It also creates a function that poisons
2069// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002070// Sets *CtorComdat to true if the global registration code emitted into the
2071// asan constructor is comdat-compatible.
2072bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2073 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002074 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002075
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002076 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2077
Alexey Samsonova02e6642014-05-29 18:40:48 +00002078 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002079 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002080 }
2081
2082 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002083 if (n == 0) {
2084 *CtorComdat = true;
2085 return false;
2086 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002087
Reid Kleckner78565832016-11-29 01:32:21 +00002088 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002089
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002090 // A global is described by a structure
2091 // size_t beg;
2092 // size_t size;
2093 // size_t size_with_redzone;
2094 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002095 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002096 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002097 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002098 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002099 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002100 StructType *GlobalStructTy =
2101 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002102 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002103 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2104 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002105
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002106 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002107
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002108 // We shouldn't merge same module names, as this string serves as unique
2109 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002110 GlobalVariable *ModuleName = createPrivateGlobalForString(
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002111 M, M.getModuleIdentifier(), /*AllowMerging*/ false, kAsanGenPrefix);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002112
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002113 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002114 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002115 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002116
2117 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002118 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002119 // Create string holding the global name (use global name from metadata
2120 // if it's available, otherwise just write the name of global variable).
2121 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002122 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00002123 /*AllowMerging*/ true, kAsanGenPrefix);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002124
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002125 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002126 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002127 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002128 // MinRZ <= RZ <= kMaxGlobalRedzone
2129 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002130 uint64_t RZ = std::max(
2131 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002132 uint64_t RightRedzoneSize = RZ;
2133 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002134 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002135 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002136 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2137
Serge Gueltone38003f2017-05-09 19:31:13 +00002138 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2139 Constant *NewInitializer = ConstantStruct::get(
2140 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002141
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002142 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002143 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2144 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2145 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002146 GlobalVariable *NewGlobal =
2147 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2148 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002149 NewGlobal->copyAttributesFrom(G);
Reid Kleckner85a8c122018-08-20 23:35:45 +00002150 NewGlobal->setComdat(G->getComdat());
Kostya Serebryany87191f62013-01-24 10:35:40 +00002151 NewGlobal->setAlignment(MinRZ);
Vitaly Bukad414e1b2018-12-20 00:30:18 +00002152 // Don't fold globals with redzones. ODR violation detector and redzone
2153 // poisoning implicitly creates a dependence on the global's address, so it
2154 // is no longer valid for it to be marked unnamed_addr.
2155 NewGlobal->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002156
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002157 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2158 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2159 G->isConstant()) {
2160 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2161 if (Seq && Seq->isCString())
2162 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2163 }
2164
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002165 // Transfer the debug info. The payload starts at offset zero so we can
2166 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002167 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002168 G->getDebugInfo(GVs);
2169 for (auto *GV : GVs)
2170 NewGlobal->addDebugInfo(GV);
2171
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002172 Value *Indices2[2];
2173 Indices2[0] = IRB.getInt32(0);
2174 Indices2[1] = IRB.getInt32(0);
2175
2176 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002177 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002178 NewGlobal->takeName(G);
2179 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002180 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002181
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002182 Constant *SourceLoc;
2183 if (!MD.SourceLoc.empty()) {
2184 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2185 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2186 } else {
2187 SourceLoc = ConstantInt::get(IntptrTy, 0);
2188 }
2189
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002190 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2191 GlobalValue *InstrumentedGlobal = NewGlobal;
2192
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002193 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002194 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2195 TargetTriple.isOSBinFormatWasm();
Vitaly Buka8076c572018-12-05 01:44:31 +00002196 if (CanUsePrivateAliases && UsePrivateAlias) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002197 // Create local alias for NewGlobal to avoid crash on ODR between
2198 // instrumented and non-instrumented libraries.
Vitaly Bukad6bab092018-12-04 23:17:41 +00002199 InstrumentedGlobal =
Vitaly Buka537cfc02018-12-04 00:36:14 +00002200 GlobalAlias::create(GlobalValue::PrivateLinkage, "", NewGlobal);
Vitaly Bukad6bab092018-12-04 23:17:41 +00002201 }
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002202
Vitaly Buka07a55f22018-12-20 00:30:27 +00002203 // ODR should not happen for local linkage.
2204 if (NewGlobal->hasLocalLinkage()) {
Vitaly Bukaa2576392018-12-13 09:47:39 +00002205 ODRIndicator = ConstantExpr::getIntToPtr(ConstantInt::get(IntptrTy, -1),
2206 IRB.getInt8PtrTy());
2207 } else if (UseOdrIndicator) {
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002208 // With local aliases, we need to provide another externally visible
2209 // symbol __odr_asan_XXX to detect ODR violation.
2210 auto *ODRIndicatorSym =
2211 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2212 Constant::getNullValue(IRB.getInt8Ty()),
2213 kODRGenPrefix + NameForGlobal, nullptr,
2214 NewGlobal->getThreadLocalMode());
2215
2216 // Set meaningful attributes for indicator symbol.
2217 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2218 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2219 ODRIndicatorSym->setAlignment(1);
2220 ODRIndicator = ODRIndicatorSym;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002221 }
2222
Reid Kleckner01660a32016-11-21 20:40:37 +00002223 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002224 GlobalStructTy,
2225 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002226 ConstantInt::get(IntptrTy, SizeInBytes),
2227 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2228 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002229 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002230 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002231 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002232
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002233 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002234
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002235 LLVM_DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002236
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002237 Initializers[i] = Initializer;
2238 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002239
Kuba Mracek8842da82018-03-08 21:02:18 +00002240 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2241 // ConstantMerge'ing them.
2242 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2243 for (size_t i = 0; i < n; i++) {
2244 GlobalVariable *G = NewGlobals[i];
2245 if (G->getName().empty()) continue;
2246 GlobalsToAddToUsedList.push_back(G);
2247 }
2248 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2249
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002250 std::string ELFUniqueModuleId =
2251 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2252 : "";
2253
2254 if (!ELFUniqueModuleId.empty()) {
2255 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2256 *CtorComdat = true;
2257 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002258 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002259 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002260 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2261 } else {
2262 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002263 }
2264
Reid Kleckner01660a32016-11-21 20:40:37 +00002265 // Create calls for poisoning before initializers run and unpoisoning after.
2266 if (HasDynamicallyInitializedGlobals)
2267 createInitializerPoisonCalls(M, ModuleName);
2268
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002269 LLVM_DEBUG(dbgs() << M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002270 return true;
2271}
2272
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002273int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2274 int LongSize = M.getDataLayout().getPointerSizeInBits();
2275 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2276 int Version = 8;
2277 // 32-bit Android is one version ahead because of the switch to dynamic
2278 // shadow.
2279 Version += (LongSize == 32 && isAndroid);
2280 return Version;
2281}
2282
Leonard Chaneebecb32018-10-26 22:51:51 +00002283bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002284 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002285 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002286 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002287 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002288 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002289 initializeCallbacks(M);
2290
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002291 if (CompileKernel)
2292 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002293
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002294 // Create a module constructor. A destructor is created lazily because not all
2295 // platforms, and not all modules need it.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002296 std::string VersionCheckName =
2297 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002298 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2299 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002300 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002301
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002302 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002303 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002304 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002305 if (ClGlobals) {
2306 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002307 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2308 }
2309
2310 // Put the constructor and destructor in comdat if both
2311 // (1) global instrumentation is not TU-specific
2312 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002313 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002314 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2315 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2316 AsanCtorFunction);
2317 if (AsanDtorFunction) {
2318 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2319 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2320 AsanDtorFunction);
2321 }
2322 } else {
2323 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2324 if (AsanDtorFunction)
2325 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002326 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002327
2328 return Changed;
2329}
2330
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002331void AddressSanitizer::initializeCallbacks(Module &M) {
2332 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002333 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002334 // IsWrite, TypeSize and Exp are encoded in the function name.
2335 for (int Exp = 0; Exp < 2; Exp++) {
2336 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2337 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2338 const std::string ExpStr = Exp ? "exp_" : "";
Yury Gribovd7731982015-11-11 10:36:49 +00002339 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002340
2341 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2342 SmallVector<Type *, 2> Args1{1, IntptrTy};
2343 if (Exp) {
2344 Type *ExpType = Type::getInt32Ty(*C);
2345 Args2.push_back(ExpType);
2346 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002347 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002348 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2349 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Evgeniy Stepanov31475a02018-01-25 21:28:51 +00002350 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002351 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002352
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002353 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2354 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2355 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2356 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002357
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002358 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2359 AccessSizeIndex++) {
2360 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2361 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2362 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2363 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2364 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002365
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002366 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2367 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2368 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2369 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2370 }
2371 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002372 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002373
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002374 const std::string MemIntrinCallbackPrefix =
2375 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002376 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002377 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002378 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002379 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002380 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002381 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002382 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002383 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002384 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002385
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002386 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002387 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002388
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002389 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002390 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002391 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002392 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002393 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2394 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2395 StringRef(""), StringRef(""),
2396 /*hasSideEffects=*/true);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002397 if (Mapping.InGlobal)
2398 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2399 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002400}
2401
Leonard Chaneebecb32018-10-26 22:51:51 +00002402// virtual
2403bool AddressSanitizer::doInitialization(Module &M) {
2404 // Initialize the private fields. No one has accessed them before.
2405 GlobalsMD.init(M);
2406
2407 C = &(M.getContext());
2408 LongSize = M.getDataLayout().getPointerSizeInBits();
2409 IntptrTy = Type::getIntNTy(*C, LongSize);
2410 TargetTriple = Triple(M.getTargetTriple());
2411
2412 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
2413 return true;
2414}
2415
2416bool AddressSanitizer::doFinalization(Module &M) {
2417 GlobalsMD.reset();
2418 return false;
2419}
2420
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002421bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2422 // For each NSObject descendant having a +load method, this method is invoked
2423 // by the ObjC runtime before any of the static constructors is called.
2424 // Therefore we need to instrument such methods with a call to __asan_init
2425 // at the beginning in order to initialize our runtime before any access to
2426 // the shadow memory.
2427 // We cannot just ignore these methods, because they may call other
2428 // instrumented functions.
2429 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002430 Function *AsanInitFunction =
2431 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002432 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002433 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002434 return true;
2435 }
2436 return false;
2437}
2438
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002439void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2440 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002441 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002442 return;
2443
2444 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002445 if (Mapping.InGlobal) {
2446 if (ClWithIfuncSuppressRemat) {
2447 // An empty inline asm with input reg == output reg.
2448 // An opaque pointer-to-int cast, basically.
2449 InlineAsm *Asm = InlineAsm::get(
2450 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2451 StringRef(""), StringRef("=r,0"),
2452 /*hasSideEffects=*/false);
2453 LocalDynamicShadow =
2454 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2455 } else {
2456 LocalDynamicShadow =
2457 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2458 }
2459 } else {
2460 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2461 kAsanShadowMemoryDynamicAddress, IntptrTy);
2462 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2463 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002464}
2465
Reid Kleckner2f907552015-07-21 17:40:14 +00002466void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2467 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2468 // to it as uninteresting. This assumes we haven't started processing allocas
2469 // yet. This check is done up front because iterating the use list in
2470 // isInterestingAlloca would be algorithmically slower.
2471 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2472
2473 // Try to get the declaration of llvm.localescape. If it's not in the module,
2474 // we can exit early.
2475 if (!F.getParent()->getFunction("llvm.localescape")) return;
2476
2477 // Look for a call to llvm.localescape call in the entry block. It can't be in
2478 // any other block.
2479 for (Instruction &I : F.getEntryBlock()) {
2480 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2481 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2482 // We found a call. Mark all the allocas passed in as uninteresting.
2483 for (Value *Arg : II->arg_operands()) {
2484 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2485 assert(AI && AI->isStaticAlloca() &&
2486 "non-static alloca arg to localescape");
2487 ProcessedAllocas[AI] = false;
2488 }
2489 break;
2490 }
2491 }
2492}
2493
Leonard Chaneebecb32018-10-26 22:51:51 +00002494bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002495 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002496 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002497 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002498
Etienne Bergeron78582b22016-09-15 15:45:05 +00002499 bool FunctionModified = false;
2500
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002501 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002502 // This function needs to be called even if the function body is not
Fangrui Songf78650a2018-07-30 19:41:25 +00002503 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002504 if (maybeInsertAsanInitAtFunctionEntry(F))
2505 FunctionModified = true;
Fangrui Songf78650a2018-07-30 19:41:25 +00002506
Etienne Bergeron752f8832016-09-14 17:18:37 +00002507 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002508 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002509
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002510 LLVM_DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Etienne Bergeron752f8832016-09-14 17:18:37 +00002511
2512 initializeCallbacks(*F.getParent());
Leonard Chaneebecb32018-10-26 22:51:51 +00002513 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002514
Reid Kleckner2f907552015-07-21 17:40:14 +00002515 FunctionStateRAII CleanupObj(this);
2516
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002517 maybeInsertDynamicShadowAtFunctionEntry(F);
2518
Reid Kleckner2f907552015-07-21 17:40:14 +00002519 // We can't instrument allocas used with llvm.localescape. Only static allocas
2520 // can be passed to that intrinsic.
2521 markEscapedLocalAllocas(F);
2522
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002523 // We want to instrument every address only once per basic block (unless there
2524 // are calls between uses).
Florian Hahna1cc8482018-06-12 11:16:56 +00002525 SmallPtrSet<Value *, 16> TempsToInstrument;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002526 SmallVector<Instruction *, 16> ToInstrument;
2527 SmallVector<Instruction *, 8> NoReturnCalls;
2528 SmallVector<BasicBlock *, 16> AllBlocks;
2529 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002530 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002531 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002532 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002533 uint64_t TypeSize;
Leonard Chaneebecb32018-10-26 22:51:51 +00002534 const TargetLibraryInfo *TLI =
2535 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002536
2537 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002538 for (auto &BB : F) {
2539 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002540 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002541 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002542 for (auto &Inst : BB) {
2543 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002544 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002545 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002546 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002547 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002548 // If we have a mask, skip instrumentation if we've already
2549 // instrumented the full object. But don't add to TempsToInstrument
2550 // because we might get another load/store with a different mask.
2551 if (MaybeMask) {
2552 if (TempsToInstrument.count(Addr))
2553 continue; // We've seen this (whole) temp in the current BB.
2554 } else {
2555 if (!TempsToInstrument.insert(Addr).second)
2556 continue; // We've seen this temp in the current BB.
2557 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002558 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002559 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002560 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2561 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002562 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002563 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002564 // ok, take it.
2565 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002566 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002567 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002568 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002569 // A call inside BB.
2570 TempsToInstrument.clear();
Julian Lettnerb62e9dc2019-01-24 18:04:21 +00002571 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002572 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002573 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2574 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002575 continue;
2576 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002577 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002578 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002579 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002580 }
2581 }
2582
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002583 bool UseCalls =
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002584 (ClInstrumentationWithCallsThreshold >= 0 &&
2585 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002586 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002587 ObjectSizeOpts ObjSizeOpts;
2588 ObjSizeOpts.RoundToAlign = true;
2589 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002590
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002591 // Instrument.
2592 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002593 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002594 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2595 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002596 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002597 instrumentMop(ObjSizeVis, Inst, UseCalls,
2598 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002599 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002600 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002601 }
2602 NumInstrumented++;
2603 }
2604
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002605 FunctionStackPoisoner FSP(F, *this);
2606 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002607
2608 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002609 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002610 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002611 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002612 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002613 }
2614
Alexey Samsonova02e6642014-05-29 18:40:48 +00002615 for (auto Inst : PointerComparisonsOrSubtracts) {
2616 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002617 NumInstrumented++;
2618 }
2619
Etienne Bergeron78582b22016-09-15 15:45:05 +00002620 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2621 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002622
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002623 LLVM_DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2624 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002625
Etienne Bergeron78582b22016-09-15 15:45:05 +00002626 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002627}
2628
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002629// Workaround for bug 11395: we don't want to instrument stack in functions
2630// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2631// FIXME: remove once the bug 11395 is fixed.
2632bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2633 if (LongSize != 32) return false;
2634 CallInst *CI = dyn_cast<CallInst>(I);
2635 if (!CI || !CI->isInlineAsm()) return false;
2636 if (CI->getNumArgOperands() <= 5) return false;
2637 // We have inline assembly with quite a few arguments.
2638 return true;
2639}
2640
2641void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2642 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002643 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2644 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002645 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2646 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002647 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002648 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002649 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002650 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002651 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002652 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002653 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2654 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002655 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002656 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2657 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002658 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002659 }
2660
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002661 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2662 std::ostringstream Name;
2663 Name << kAsanSetShadowPrefix;
2664 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002665 AsanSetShadowFunc[Val] =
2666 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002667 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002668 }
2669
Yury Gribov98b18592015-05-28 07:51:49 +00002670 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002671 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002672 AsanAllocasUnpoisonFunc =
2673 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002674 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002675}
2676
Vitaly Buka793913c2016-08-29 18:17:21 +00002677void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2678 ArrayRef<uint8_t> ShadowBytes,
2679 size_t Begin, size_t End,
2680 IRBuilder<> &IRB,
2681 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002682 if (Begin >= End)
2683 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002684
2685 const size_t LargestStoreSizeInBytes =
2686 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2687
2688 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2689
2690 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002691 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2692 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2693 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002694 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002695 if (!ShadowMask[i]) {
2696 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002697 ++i;
2698 continue;
2699 }
2700
2701 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2702 // Fit store size into the range.
2703 while (StoreSizeInBytes > End - i)
2704 StoreSizeInBytes /= 2;
2705
2706 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002707 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002708 while (j <= StoreSizeInBytes / 2)
2709 StoreSizeInBytes /= 2;
2710 }
2711
2712 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002713 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2714 if (IsLittleEndian)
2715 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2716 else
2717 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002718 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002719
2720 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2721 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002722 IRB.CreateAlignedStore(
2723 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002724
2725 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002726 }
2727}
2728
Vitaly Buka793913c2016-08-29 18:17:21 +00002729void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2730 ArrayRef<uint8_t> ShadowBytes,
2731 IRBuilder<> &IRB, Value *ShadowBase) {
2732 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2733}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002734
Vitaly Buka793913c2016-08-29 18:17:21 +00002735void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2736 ArrayRef<uint8_t> ShadowBytes,
2737 size_t Begin, size_t End,
2738 IRBuilder<> &IRB, Value *ShadowBase) {
2739 assert(ShadowMask.size() == ShadowBytes.size());
2740 size_t Done = Begin;
2741 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2742 if (!ShadowMask[i]) {
2743 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002744 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002745 }
2746 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002747 if (!AsanSetShadowFunc[Val])
2748 continue;
2749
2750 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002751 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002752 }
2753
2754 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002755 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002756 IRB.CreateCall(AsanSetShadowFunc[Val],
2757 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2758 ConstantInt::get(IntptrTy, j - i)});
2759 Done = j;
2760 }
2761 }
2762
Vitaly Buka793913c2016-08-29 18:17:21 +00002763 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002764}
2765
Kostya Serebryany6805de52013-09-10 13:16:56 +00002766// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2767// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2768static int StackMallocSizeClass(uint64_t LocalStackSize) {
2769 assert(LocalStackSize <= kMaxStackMallocSize);
2770 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002771 for (int i = 0;; i++, MaxSize *= 2)
2772 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002773 llvm_unreachable("impossible LocalStackSize");
2774}
2775
Vitaly Buka74443f02017-07-18 22:28:03 +00002776void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002777 Instruction *CopyInsertPoint = &F.front().front();
2778 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2779 // Insert after the dynamic shadow location is determined
2780 CopyInsertPoint = CopyInsertPoint->getNextNode();
2781 assert(CopyInsertPoint);
2782 }
2783 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002784 const DataLayout &DL = F.getParent()->getDataLayout();
2785 for (Argument &Arg : F.args()) {
2786 if (Arg.hasByValAttr()) {
2787 Type *Ty = Arg.getType()->getPointerElementType();
2788 unsigned Align = Arg.getParamAlignment();
2789 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2790
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002791 AllocaInst *AI = IRB.CreateAlloca(
2792 Ty, nullptr,
2793 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2794 ".byval");
Vitaly Buka74443f02017-07-18 22:28:03 +00002795 AI->setAlignment(Align);
2796 Arg.replaceAllUsesWith(AI);
2797
2798 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
Daniel Neilsona98d9d92018-02-08 21:26:12 +00002799 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
Vitaly Buka74443f02017-07-18 22:28:03 +00002800 }
2801 }
2802}
2803
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002804PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2805 Value *ValueIfTrue,
2806 Instruction *ThenTerm,
2807 Value *ValueIfFalse) {
2808 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2809 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2810 PHI->addIncoming(ValueIfFalse, CondBlock);
2811 BasicBlock *ThenBlock = ThenTerm->getParent();
2812 PHI->addIncoming(ValueIfTrue, ThenBlock);
2813 return PHI;
2814}
2815
2816Value *FunctionStackPoisoner::createAllocaForLayout(
2817 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2818 AllocaInst *Alloca;
2819 if (Dynamic) {
2820 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2821 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2822 "MyAlloca");
2823 } else {
2824 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2825 nullptr, "MyAlloca");
2826 assert(Alloca->isStaticAlloca());
2827 }
2828 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2829 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2830 Alloca->setAlignment(FrameAlignment);
2831 return IRB.CreatePointerCast(Alloca, IntptrTy);
2832}
2833
Yury Gribov98b18592015-05-28 07:51:49 +00002834void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2835 BasicBlock &FirstBB = *F.begin();
2836 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2837 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2838 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2839 DynamicAllocaLayout->setAlignment(32);
2840}
2841
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002842void FunctionStackPoisoner::processDynamicAllocas() {
2843 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2844 assert(DynamicAllocaPoisonCallVec.empty());
2845 return;
2846 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002847
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002848 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2849 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002850 assert(APC.InsBefore);
2851 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002852 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002853 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002854
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002855 IRBuilder<> IRB(APC.InsBefore);
2856 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002857 // Dynamic allocas will be unpoisoned unconditionally below in
2858 // unpoisonDynamicAllocas.
2859 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002860 }
2861
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002862 // Handle dynamic allocas.
2863 createDynamicAllocasInitStorage();
2864 for (auto &AI : DynamicAllocaVec)
2865 handleDynamicAllocaCall(AI);
2866 unpoisonDynamicAllocas();
2867}
Yury Gribov98b18592015-05-28 07:51:49 +00002868
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002869void FunctionStackPoisoner::processStaticAllocas() {
2870 if (AllocaVec.empty()) {
2871 assert(StaticAllocaPoisonCallVec.empty());
2872 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002873 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002874
Kostya Serebryany6805de52013-09-10 13:16:56 +00002875 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002876 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002877 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002878 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002879
2880 Instruction *InsBefore = AllocaVec[0];
2881 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002882 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002883
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002884 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2885 // debug info is broken, because only entry-block allocas are treated as
2886 // regular stack slots.
2887 auto InsBeforeB = InsBefore->getParent();
2888 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002889 for (auto *AI : StaticAllocasToMoveUp)
2890 if (AI->getParent() == InsBeforeB)
2891 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002892
Reid Kleckner2f907552015-07-21 17:40:14 +00002893 // If we have a call to llvm.localescape, keep it in the entry block.
2894 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2895
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002896 SmallVector<ASanStackVariableDescription, 16> SVD;
2897 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002898 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002899 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002900 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002901 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002902 AI->getAlignment(),
2903 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002904 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002905 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002906 SVD.push_back(D);
2907 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002908
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002909 // Minimal header size (left redzone) is 4 pointers,
2910 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00002911 size_t Granularity = 1ULL << Mapping.Scale;
2912 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00002913 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00002914 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002915
Vitaly Buka5910a922016-10-18 23:29:52 +00002916 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2917 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2918 for (auto &Desc : SVD)
2919 AllocaToSVDMap[Desc.AI] = &Desc;
2920
2921 // Update SVD with information from lifetime intrinsics.
2922 for (const auto &APC : StaticAllocaPoisonCallVec) {
2923 assert(APC.InsBefore);
2924 assert(APC.AI);
2925 assert(ASan.isInterestingAlloca(*APC.AI));
2926 assert(APC.AI->isStaticAlloca());
2927
2928 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2929 Desc.LifetimeSize = Desc.Size;
2930 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2931 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2932 if (LifetimeLoc->getFile() == FnLoc->getFile())
2933 if (unsigned Line = LifetimeLoc->getLine())
2934 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2935 }
2936 }
2937 }
2938
2939 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002940 LLVM_DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002941 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002942 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2943 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002944 bool DoDynamicAlloca = ClDynamicAllocaStack;
2945 // Don't do dynamic alloca or stack malloc if:
2946 // 1) There is inline asm: too often it makes assumptions on which registers
2947 // are available.
2948 // 2) There is a returns_twice call (typically setjmp), which is
2949 // optimization-hostile, and doesn't play well with introduced indirect
2950 // register-relative calculation of local variable addresses.
2951 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2952 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002953
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002954 Value *StaticAlloca =
2955 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2956
2957 Value *FakeStack;
2958 Value *LocalStackBase;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002959 Value *LocalStackBaseAlloca;
2960 bool Deref;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002961
2962 if (DoStackMalloc) {
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002963 LocalStackBaseAlloca =
2964 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002965 // void *FakeStack = __asan_option_detect_stack_use_after_return
2966 // ? __asan_stack_malloc_N(LocalStackSize)
2967 // : nullptr;
2968 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002969 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2970 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2971 Value *UseAfterReturnIsEnabled =
2972 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002973 Constant::getNullValue(IRB.getInt32Ty()));
2974 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002975 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002976 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002977 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002978 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2979 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2980 Value *FakeStackValue =
2981 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2982 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002983 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002984 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002985 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002986 ConstantInt::get(IntptrTy, 0));
2987
2988 Value *NoFakeStack =
2989 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2990 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2991 IRBIf.SetInsertPoint(Term);
2992 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2993 Value *AllocaValue =
2994 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002995
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002996 IRB.SetInsertPoint(InsBefore);
2997 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2998 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002999 IRB.SetCurrentDebugLocation(EntryDebugLocation);
3000 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
3001 Deref = true;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003002 } else {
3003 // void *FakeStack = nullptr;
3004 // void *LocalStackBase = alloca(LocalStackSize);
3005 FakeStack = ConstantInt::get(IntptrTy, 0);
3006 LocalStackBase =
3007 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003008 LocalStackBaseAlloca = LocalStackBase;
3009 Deref = false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003010 }
3011
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003012 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003013 for (const auto &Desc : SVD) {
3014 AllocaInst *AI = Desc.AI;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00003015 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
3016 Desc.Offset, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00003017 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00003018 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00003019 AI->getType());
Alexey Samsonov261177a2012-12-04 01:34:23 +00003020 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003021 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003022
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003023 // The left-most redzone has enough space for at least 4 pointers.
3024 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003025 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
3026 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
3027 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003028 // Write the frame description constant to redzone[1].
3029 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003030 IRB.CreateAdd(LocalStackBase,
3031 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
3032 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00003033 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00003034 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Kostya Serebryanyd891ac92018-10-11 23:03:27 +00003035 /*AllowMerging*/ true, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003036 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003037 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003038 // Write the PC to redzone[2].
3039 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003040 IRB.CreateAdd(LocalStackBase,
3041 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
3042 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00003043 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003044
Vitaly Buka793913c2016-08-29 18:17:21 +00003045 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
3046
3047 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003048 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00003049 // As mask we must use most poisoned case: red zones and after scope.
3050 // As bytes we can use either the same or just red zones only.
3051 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
3052
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003053 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00003054 const auto &ShadowInScope = GetShadowBytes(SVD, L);
3055
3056 // Poison static allocas near lifetime intrinsics.
3057 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00003058 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00003059 assert(Desc.Offset % L.Granularity == 0);
3060 size_t Begin = Desc.Offset / L.Granularity;
3061 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
3062
3063 IRBuilder<> IRB(APC.InsBefore);
3064 copyToShadow(ShadowAfterScope,
3065 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
3066 IRB, ShadowBase);
3067 }
3068 }
3069
3070 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00003071 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00003072
Kostya Serebryany530e2072013-12-23 14:15:08 +00003073 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003074 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003075 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003076 // Mark the current frame as retired.
3077 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3078 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003079 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00003080 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003081 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00003082 // // In use-after-return mode, poison the whole stack frame.
3083 // if StackMallocIdx <= 4
3084 // // For small sizes inline the whole thing:
3085 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003086 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00003087 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003088 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00003089 // else
3090 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003091 Value *Cmp =
3092 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Chandler Carruth4a2d58e2018-10-15 09:34:05 +00003093 Instruction *ThenTerm, *ElseTerm;
Kostya Serebryany530e2072013-12-23 14:15:08 +00003094 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3095
3096 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003097 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003098 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003099 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3100 kAsanStackUseAfterReturnMagic);
3101 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3102 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003103 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003104 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003105 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3106 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3107 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3108 IRBPoison.CreateStore(
3109 Constant::getNullValue(IRBPoison.getInt8Ty()),
3110 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3111 } else {
3112 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003113 IRBPoison.CreateCall(
3114 AsanStackFreeFunc[StackMallocIdx],
3115 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003116 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003117
3118 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003119 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003120 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003121 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003122 }
3123 }
3124
Kostya Serebryany09959942012-10-19 06:20:53 +00003125 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003126 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003127}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003128
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003129void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003130 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003131 // For now just insert the call to ASan runtime.
3132 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3133 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003134 IRB.CreateCall(
3135 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3136 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003137}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003138
3139// Handling llvm.lifetime intrinsics for a given %alloca:
3140// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3141// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3142// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3143// could be poisoned by previous llvm.lifetime.end instruction, as the
3144// variable may go in and out of scope several times, e.g. in loops).
3145// (3) if we poisoned at least one %alloca in a function,
3146// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003147
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003148AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3149 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003150 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003151 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003152 // See if we've already calculated (or started to calculate) alloca for a
3153 // given value.
3154 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003155 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003156 // Store 0 while we're calculating alloca for value V to avoid
3157 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003158 AllocaForValue[V] = nullptr;
3159 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003160 if (CastInst *CI = dyn_cast<CastInst>(V))
3161 Res = findAllocaForValue(CI->getOperand(0));
3162 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003163 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003164 // Allow self-referencing phi-nodes.
3165 if (IncValue == PN) continue;
3166 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3167 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003168 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3169 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003170 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003171 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003172 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3173 Res = findAllocaForValue(EP->getPointerOperand());
3174 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003175 LLVM_DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V
3176 << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003177 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003178 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003179 return Res;
3180}
Yury Gribov55441bb2014-11-21 10:29:50 +00003181
Yury Gribov98b18592015-05-28 07:51:49 +00003182void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003183 IRBuilder<> IRB(AI);
3184
Yury Gribov55441bb2014-11-21 10:29:50 +00003185 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3186 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3187
3188 Value *Zero = Constant::getNullValue(IntptrTy);
3189 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3190 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003191
3192 // Since we need to extend alloca with additional memory to locate
3193 // redzones, and OldSize is number of allocated blocks with
3194 // ElementSize size, get allocated memory size in bytes by
3195 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003196 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003197 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003198 Value *OldSize =
3199 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3200 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003201
3202 // PartialSize = OldSize % 32
3203 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3204
3205 // Misalign = kAllocaRzSize - PartialSize;
3206 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3207
3208 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3209 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3210 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3211
3212 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3213 // Align is added to locate left redzone, PartialPadding for possible
3214 // partial redzone and kAllocaRzSize for right redzone respectively.
3215 Value *AdditionalChunkSize = IRB.CreateAdd(
3216 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3217
3218 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3219
3220 // Insert new alloca with new NewSize and Align params.
3221 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3222 NewAlloca->setAlignment(Align);
3223
3224 // NewAddress = Address + Align
3225 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3226 ConstantInt::get(IntptrTy, Align));
3227
Yury Gribov98b18592015-05-28 07:51:49 +00003228 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003229 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003230
3231 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3232 // for unpoisoning stuff.
3233 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3234
Yury Gribov55441bb2014-11-21 10:29:50 +00003235 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3236
Yury Gribov98b18592015-05-28 07:51:49 +00003237 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003238 AI->replaceAllUsesWith(NewAddressPtr);
3239
Yury Gribov98b18592015-05-28 07:51:49 +00003240 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003241 AI->eraseFromParent();
3242}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003243
3244// isSafeAccess returns true if Addr is always inbounds with respect to its
3245// base object. For example, it is a field access or an array access with
3246// constant inbounds index.
3247bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3248 Value *Addr, uint64_t TypeSize) const {
3249 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3250 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003251 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003252 int64_t Offset = SizeOffset.second.getSExtValue();
3253 // Three checks are required to ensure safety:
3254 // . Offset >= 0 (since the offset is given from the base ptr)
3255 // . Size >= Offset (unsigned)
3256 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003257 return Offset >= 0 && Size >= uint64_t(Offset) &&
3258 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003259}