blob: 42f0c60c1d739677ba1e26b2fdc9295e1109c16e [file] [log] [blame]
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001//===- AddressSanitizer.cpp - memory error detector -----------------------===//
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
Hans Wennborg08b34a02017-11-13 23:47:58 +000012// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000013//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000019#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000021#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/ADT/StringRef.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000025#include "llvm/ADT/Twine.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000026#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000028#include "llvm/Analysis/Utils/Local.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000029#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000030#include "llvm/BinaryFormat/MachO.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000031#include "llvm/IR/Argument.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000032#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000034#include "llvm/IR/CallSite.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000035#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000038#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000040#include "llvm/IR/DebugInfoMetadata.h"
41#include "llvm/IR/DebugLoc.h"
42#include "llvm/IR/DerivedTypes.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000043#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000045#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000050#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000051#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000055#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000057#include "llvm/IR/MDBuilder.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000058#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Module.h"
60#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000061#include "llvm/IR/Use.h"
62#include "llvm/IR/Value.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000063#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000064#include "llvm/Pass.h"
65#include "llvm/Support/Casting.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066#include "llvm/Support/CommandLine.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000068#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/MathExtras.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000070#include "llvm/Support/ScopedPrinter.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000071#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000072#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000073#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
75#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000076#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000078#include <cassert>
79#include <cstddef>
80#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000081#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000082#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000083#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000084#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000086#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
88using namespace llvm;
89
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "asan"
91
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const uint64_t kDefaultShadowScale = 3;
93static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000098static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Walter Lee8f1545c2017-11-16 17:03:00 +0000100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
101static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Bill Seurer957a0762017-12-07 22:53:33 +0000103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000104static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000105static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000106static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000107static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000108static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
109static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000110static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000111static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000112static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000113
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000114// The shadow memory space is dynamically allocated.
115static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000116
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000117static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000118static const size_t kMaxStackMallocSize = 1 << 16; // 64K
119static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
120static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
121
Craig Topperd3a34f82013-07-16 01:17:10 +0000122static const char *const kAsanModuleCtorName = "asan.module_ctor";
123static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000124static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000125static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000126static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000127static const char *const kAsanUnregisterGlobalsName =
128 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000129static const char *const kAsanRegisterImageGlobalsName =
130 "__asan_register_image_globals";
131static const char *const kAsanUnregisterImageGlobalsName =
132 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000133static const char *const kAsanRegisterElfGlobalsName =
134 "__asan_register_elf_globals";
135static const char *const kAsanUnregisterElfGlobalsName =
136 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000137static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
138static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000139static const char *const kAsanInitName = "__asan_init";
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000140static const char *const kAsanVersionCheckNamePrefix =
141 "__asan_version_mismatch_check_v";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000142static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
143static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000144static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000145static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000146static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
147static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000148static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000149static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000150static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000151static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000152static const char *const kAsanPoisonStackMemoryName =
153 "__asan_poison_stack_memory";
154static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000155 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000156
157// ASan version script has __asan_* wildcard. Triple underscore prevents a
158// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000159static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000160 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000161
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000162static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000163 "__asan_option_detect_stack_use_after_return";
164
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000165static const char *const kAsanShadowMemoryDynamicAddress =
166 "__asan_shadow_memory_dynamic_address";
167
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000168static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
169static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000170
Kostya Serebryany874dae62012-07-16 16:15:40 +0000171// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
172static const size_t kNumberOfAccessSizes = 5;
173
Yury Gribov55441bb2014-11-21 10:29:50 +0000174static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000175
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000176// Command-line flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000177
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000178static cl::opt<bool> ClEnableKasan(
179 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
180 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000181
Yury Gribovd7731982015-11-11 10:36:49 +0000182static cl::opt<bool> ClRecover(
183 "asan-recover",
184 cl::desc("Enable recovery mode (continue-after-error)."),
185 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000186
187// This flag may need to be replaced with -f[no-]asan-reads.
188static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000189 cl::desc("instrument read instructions"),
190 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000191
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192static cl::opt<bool> ClInstrumentWrites(
193 "asan-instrument-writes", cl::desc("instrument write instructions"),
194 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000195
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000196static cl::opt<bool> ClInstrumentAtomics(
197 "asan-instrument-atomics",
198 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
199 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000200
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000201static cl::opt<bool> ClAlwaysSlowPath(
202 "asan-always-slow-path",
203 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
204 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000205
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000206static cl::opt<bool> ClForceDynamicShadow(
207 "asan-force-dynamic-shadow",
208 cl::desc("Load shadow address into a local variable for each function"),
209 cl::Hidden, cl::init(false));
210
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000211static cl::opt<bool>
212 ClWithIfunc("asan-with-ifunc",
213 cl::desc("Access dynamic shadow through an ifunc global on "
214 "platforms that support this"),
215 cl::Hidden, cl::init(true));
216
217static cl::opt<bool> ClWithIfuncSuppressRemat(
218 "asan-with-ifunc-suppress-remat",
219 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
220 "it through inline asm in prologue."),
221 cl::Hidden, cl::init(true));
222
Kostya Serebryany874dae62012-07-16 16:15:40 +0000223// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000224// in any given BB. Normally, this should be set to unlimited (INT_MAX),
225// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
226// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000227static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
228 "asan-max-ins-per-bb", cl::init(10000),
229 cl::desc("maximal number of instructions to instrument in any given BB"),
230 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000231
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000232// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000233static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
234 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000235static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
236 "asan-max-inline-poisoning-size",
237 cl::desc(
238 "Inline shadow poisoning for blocks up to the given size in bytes."),
239 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000242 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000243 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000244
Vitaly Buka74443f02017-07-18 22:28:03 +0000245static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
246 cl::desc("Create redzones for byval "
247 "arguments (extra copy "
248 "required)"), cl::Hidden,
249 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000250
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000251static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
252 cl::desc("Check stack-use-after-scope"),
253 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000254
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000255// This flag may need to be replaced with -f[no]asan-globals.
256static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000257 cl::desc("Handle global objects"), cl::Hidden,
258 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000259
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000260static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000261 cl::desc("Handle C++ initializer order"),
262 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000263
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000264static cl::opt<bool> ClInvalidPointerPairs(
265 "asan-detect-invalid-pointer-pair",
266 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
267 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000268
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000269static cl::opt<unsigned> ClRealignStack(
270 "asan-realign-stack",
271 cl::desc("Realign stack to the value of this flag (power of two)"),
272 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000273
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000274static cl::opt<int> ClInstrumentationWithCallsThreshold(
275 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000276 cl::desc(
277 "If the function being instrumented contains more than "
278 "this number of memory accesses, use callbacks instead of "
279 "inline checks (-1 means never use callbacks)."),
280 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000281
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000282static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000283 "asan-memory-access-callback-prefix",
284 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
285 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000286
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000287static cl::opt<bool>
288 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
289 cl::desc("instrument dynamic allocas"),
290 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000291
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000292static cl::opt<bool> ClSkipPromotableAllocas(
293 "asan-skip-promotable-allocas",
294 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
295 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000296
297// These flags allow to change the shadow mapping.
298// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000299// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000300
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000301static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000302 cl::desc("scale of asan shadow mapping"),
303 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000304
Ryan Govostes6194ae62016-05-06 11:22:11 +0000305static cl::opt<unsigned long long> ClMappingOffset(
306 "asan-mapping-offset",
307 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
308 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000309
310// Optimization flags. Not user visible, used mostly for testing
311// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000312
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000313static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
314 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000315
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000316static cl::opt<bool> ClOptSameTemp(
317 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
318 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000319
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000320static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000321 cl::desc("Don't instrument scalar globals"),
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> ClOptStack(
325 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
326 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000327
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000328static cl::opt<bool> ClDynamicAllocaStack(
329 "asan-stack-dynamic-alloca",
330 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000331 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000332
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000333static cl::opt<uint32_t> ClForceExperiment(
334 "asan-force-experiment",
335 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
336 cl::init(0));
337
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000338static cl::opt<bool>
339 ClUsePrivateAliasForGlobals("asan-use-private-alias",
340 cl::desc("Use private aliases for global"
341 " variables"),
342 cl::Hidden, cl::init(false));
343
Ryan Govostese51401b2016-07-05 21:53:08 +0000344static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000345 ClUseGlobalsGC("asan-globals-live-support",
346 cl::desc("Use linker features to support dead "
347 "code stripping of globals"),
348 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000349
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000350// This is on by default even though there is a bug in gold:
351// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
352static cl::opt<bool>
353 ClWithComdat("asan-with-comdat",
354 cl::desc("Place ASan constructors in comdat sections"),
355 cl::Hidden, cl::init(true));
356
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000357// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000358
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000359static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
360 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000361
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000362static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
363 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000364
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000365static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
366 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000367
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000368static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
369 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000370
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000371static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000372 cl::Hidden, cl::init(-1));
373
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000374STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
375STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000376STATISTIC(NumOptimizedAccessesToGlobalVar,
377 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000378STATISTIC(NumOptimizedAccessesToStackVar,
379 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000380
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000381namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000382
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000383/// Frontend-provided metadata for source location.
384struct LocationMetadata {
385 StringRef Filename;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000386 int LineNo = 0;
387 int ColumnNo = 0;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000388
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000389 LocationMetadata() = default;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000390
391 bool empty() const { return Filename.empty(); }
392
393 void parse(MDNode *MDN) {
394 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000395 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
396 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000397 LineNo =
398 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
399 ColumnNo =
400 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000401 }
402};
403
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000404/// Frontend-provided metadata for global variables.
405class GlobalsMetadata {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000406public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000407 struct Entry {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000408 LocationMetadata SourceLoc;
409 StringRef Name;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000410 bool IsDynInit = false;
411 bool IsBlacklisted = false;
412
413 Entry() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000414 };
415
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000416 GlobalsMetadata() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000417
Keno Fischere03fae42015-12-05 14:42:34 +0000418 void reset() {
419 inited_ = false;
420 Entries.clear();
421 }
422
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000423 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000424 assert(!inited_);
425 inited_ = true;
426 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000427 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000428 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000429 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000430 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000431 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000432 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000433 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000434 // We can already have an entry for GV if it was merged with another
435 // global.
436 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000437 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
438 E.SourceLoc.parse(Loc);
439 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
440 E.Name = Name->getString();
441 ConstantInt *IsDynInit =
442 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000443 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000444 ConstantInt *IsBlacklisted =
445 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000446 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000447 }
448 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000449
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000450 /// Returns metadata entry for a given global.
451 Entry get(GlobalVariable *G) const {
452 auto Pos = Entries.find(G);
453 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000454 }
455
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000456private:
457 bool inited_ = false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000458 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000459};
460
Alexey Samsonov1345d352013-01-16 13:23:28 +0000461/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000462/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000463/// If InGlobal is true, then
464/// extern char __asan_shadow[];
465/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000466struct ShadowMapping {
467 int Scale;
468 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000469 bool OrShadowOffset;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000470 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000471};
472
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000473} // end anonymous namespace
474
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000475static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
476 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000477 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000478 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000479 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000480 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000481 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000482 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000483 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
484 TargetTriple.getArch() == Triple::ppc64le;
485 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
486 bool IsX86 = TargetTriple.getArch() == Triple::x86;
487 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
488 bool IsMIPS32 = TargetTriple.getArch() == Triple::mips ||
489 TargetTriple.getArch() == Triple::mipsel;
490 bool IsMIPS64 = TargetTriple.getArch() == Triple::mips64 ||
491 TargetTriple.getArch() == Triple::mips64el;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000492 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000493 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000494 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000495 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000496
497 ShadowMapping Mapping;
498
Walter Lee8f1545c2017-11-16 17:03:00 +0000499 Mapping.Scale = kDefaultShadowScale;
500 if (ClMappingScale.getNumOccurrences() > 0) {
501 Mapping.Scale = ClMappingScale;
502 }
503
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000504 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000505 if (IsAndroid)
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000506 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000507 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000508 Mapping.Offset = kMIPS32_ShadowOffset32;
509 else if (IsFreeBSD)
510 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000511 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000512 // If we're targeting iOS and x86, the binary is built for iOS simulator.
513 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000514 else if (IsWindows)
515 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000516 else
517 Mapping.Offset = kDefaultShadowOffset32;
518 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000519 // Fuchsia is always PIE, which means that the beginning of the address
520 // space is always available.
521 if (IsFuchsia)
522 Mapping.Offset = 0;
523 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000524 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000525 else if (IsSystemZ)
526 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000527 else if (IsFreeBSD)
528 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000529 else if (IsNetBSD)
530 Mapping.Offset = kNetBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000531 else if (IsPS4CPU)
532 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000533 else if (IsLinux && IsX86_64) {
534 if (IsKasan)
535 Mapping.Offset = kLinuxKasan_ShadowOffset64;
536 else
Walter Lee8f1545c2017-11-16 17:03:00 +0000537 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
538 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
Etienne Bergeron70684f92016-06-21 15:07:29 +0000539 } else if (IsWindows && IsX86_64) {
540 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000541 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000542 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000543 else if (IsIOS)
544 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000545 // We are using dynamic shadow offset on the 64-bit devices.
546 Mapping.Offset =
547 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000548 else if (IsAArch64)
549 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000550 else
551 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000552 }
553
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000554 if (ClForceDynamicShadow) {
555 Mapping.Offset = kDynamicShadowSentinel;
556 }
557
Ryan Govostes3f37df02016-05-06 10:25:22 +0000558 if (ClMappingOffset.getNumOccurrences() > 0) {
559 Mapping.Offset = ClMappingOffset;
560 }
561
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000562 // OR-ing shadow offset if more efficient (at least on x86) if the offset
563 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000564 // offset is not necessary 1/8-th of the address space. On SystemZ,
565 // we could OR the constant in a single instruction, but it's more
566 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000567 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
568 !(Mapping.Offset & (Mapping.Offset - 1)) &&
569 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000570 bool IsAndroidWithIfuncSupport =
571 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
572 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000573
Alexey Samsonov1345d352013-01-16 13:23:28 +0000574 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000575}
576
Alexey Samsonov1345d352013-01-16 13:23:28 +0000577static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000578 // Redzone used for stack and globals is at least 32 bytes.
579 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000580 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000581}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000582
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000583namespace {
584
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000585/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000586struct AddressSanitizer : public FunctionPass {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000587 // Pass identification, replacement for typeid
588 static char ID;
589
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000590 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
591 bool UseAfterScope = false)
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000592 : FunctionPass(ID), UseAfterScope(UseAfterScope || ClUseAfterScope) {
593 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
594 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
595 ClEnableKasan : CompileKernel;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000596 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
597 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000598
Mehdi Amini117296c2016-10-01 02:56:57 +0000599 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000600 return "AddressSanitizerFunctionPass";
601 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000602
Yury Gribov3ae427d2014-12-01 08:47:58 +0000603 void getAnalysisUsage(AnalysisUsage &AU) const override {
604 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000605 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000606 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000607
Vitaly Buka21a9e572016-07-28 22:50:50 +0000608 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000609 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000610 if (AI.isArrayAllocation()) {
611 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000612 assert(CI && "non-constant array size");
613 ArraySize = CI->getZExtValue();
614 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000615 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000616 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000617 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000618 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000619 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000620
Anna Zaks8ed1d812015-02-27 03:12:36 +0000621 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000622 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000623
Anna Zaks8ed1d812015-02-27 03:12:36 +0000624 /// If it is an interesting memory access, return the PointerOperand
625 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000626 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
627 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000628 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000629 uint64_t *TypeSize, unsigned *Alignment,
630 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000631
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000632 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000633 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000634 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000635 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
636 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000637 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000638 void instrumentUnusualSizeOrAlignment(Instruction *I,
639 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000640 uint32_t TypeSize, bool IsWrite,
641 Value *SizeArgument, bool UseCalls,
642 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000643 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
644 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000645 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000646 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000647 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000648 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000649 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000650 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000651 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000652 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000653 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000654 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000655 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000656
Yury Gribov3ae427d2014-12-01 08:47:58 +0000657 DominatorTree &getDominatorTree() const { return *DT; }
658
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000659private:
660 friend struct FunctionStackPoisoner;
661
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000662 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000663
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000664 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000665 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000666 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
667 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000668
Reid Kleckner2f907552015-07-21 17:40:14 +0000669 /// Helper to cleanup per-function state.
670 struct FunctionStateRAII {
671 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000672
Reid Kleckner2f907552015-07-21 17:40:14 +0000673 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
674 assert(Pass->ProcessedAllocas.empty() &&
675 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000676 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000677 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000678
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000679 ~FunctionStateRAII() {
680 Pass->LocalDynamicShadow = nullptr;
681 Pass->ProcessedAllocas.clear();
682 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000683 };
684
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000685 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000686 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000687 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000688 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000689 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000690 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000691 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000692 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000693 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000694 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000695 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000696 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000697
698 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000699 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
700 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000701
702 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000703 Function *AsanErrorCallbackSized[2][2];
704 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000705
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000706 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000707 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000708 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000709 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000710 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000711};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000712
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000713class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000714public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000715 // Pass identification, replacement for typeid
716 static char ID;
717
Yury Gribovd7731982015-11-11 10:36:49 +0000718 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000719 bool Recover = false,
720 bool UseGlobalsGC = true)
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000721 : ModulePass(ID),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000722 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
723 // Not a typo: ClWithComdat is almost completely pointless without
724 // ClUseGlobalsGC (because then it only works on modules without
725 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
726 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
727 // argument is designed as workaround. Therefore, disable both
728 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
729 // do globals-gc.
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000730 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
731 this->Recover = ClRecover.getNumOccurrences() > 0 ?
732 ClRecover : Recover;
733 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
734 ClEnableKasan : CompileKernel;
735 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000736
Craig Topper3e4c6972014-03-05 09:10:37 +0000737 bool runOnModule(Module &M) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000738 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000739
Mehdi Amini117296c2016-10-01 02:56:57 +0000740private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000741 void initializeCallbacks(Module &M);
742
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000743 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000744 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
745 ArrayRef<GlobalVariable *> ExtendedGlobals,
746 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000747 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
748 ArrayRef<GlobalVariable *> ExtendedGlobals,
749 ArrayRef<Constant *> MetadataInitializers,
750 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000751 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
752 ArrayRef<GlobalVariable *> ExtendedGlobals,
753 ArrayRef<Constant *> MetadataInitializers);
754 void
755 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
756 ArrayRef<GlobalVariable *> ExtendedGlobals,
757 ArrayRef<Constant *> MetadataInitializers);
758
759 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
760 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000761 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
762 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000763 IRBuilder<> CreateAsanModuleDtor(Module &M);
764
Kostya Serebryany20a79972012-11-22 03:18:50 +0000765 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000766 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000767 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000768 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000769 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000770 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000771 return RedzoneSizeForScale(Mapping.Scale);
772 }
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000773 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000774
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000775 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000776 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000777 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000778 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000779 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000780 Type *IntptrTy;
781 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000782 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000783 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000784 Function *AsanPoisonGlobals;
785 Function *AsanUnpoisonGlobals;
786 Function *AsanRegisterGlobals;
787 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000788 Function *AsanRegisterImageGlobals;
789 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000790 Function *AsanRegisterElfGlobals;
791 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000792
793 Function *AsanCtorFunction = nullptr;
794 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000795};
796
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000797// Stack poisoning does not play well with exception handling.
798// When an exception is thrown, we essentially bypass the code
799// that unpoisones the stack. This is why the run-time library has
800// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
801// stack in the interceptor. This however does not work inside the
802// actual function which catches the exception. Most likely because the
803// compiler hoists the load of the shadow value somewhere too high.
804// This causes asan to report a non-existing bug on 453.povray.
805// It sounds like an LLVM bug.
806struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
807 Function &F;
808 AddressSanitizer &ASan;
809 DIBuilder DIB;
810 LLVMContext *C;
811 Type *IntptrTy;
812 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000813 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000814
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000815 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000816 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000817 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000818 unsigned StackAlignment;
819
Kostya Serebryany6805de52013-09-10 13:16:56 +0000820 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000821 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000822 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000823 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000824 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000825
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000826 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
827 struct AllocaPoisonCall {
828 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000829 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000830 uint64_t Size;
831 bool DoPoison;
832 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000833 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
834 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000835
Yury Gribov98b18592015-05-28 07:51:49 +0000836 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
837 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
838 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000839 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000840
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000841 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000842 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000843 AllocaForValueMapTy AllocaForValue;
844
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000845 bool HasNonEmptyInlineAsm = false;
846 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000847 std::unique_ptr<CallInst> EmptyInlineAsm;
848
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000849 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000850 : F(F),
851 ASan(ASan),
852 DIB(*F.getParent(), /*AllowUnresolved*/ false),
853 C(ASan.C),
854 IntptrTy(ASan.IntptrTy),
855 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
856 Mapping(ASan.Mapping),
857 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000858 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000859
860 bool runOnFunction() {
861 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000862
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000863 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000864 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000865
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000866 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000867 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000868
Yury Gribov55441bb2014-11-21 10:29:50 +0000869 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000870
871 initializeCallbacks(*F.getParent());
872
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000873 processDynamicAllocas();
874 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000875
876 if (ClDebugStack) {
877 DEBUG(dbgs() << F);
878 }
879 return true;
880 }
881
Vitaly Buka74443f02017-07-18 22:28:03 +0000882 // Arguments marked with the "byval" attribute are implicitly copied without
883 // using an alloca instruction. To produce redzones for those arguments, we
884 // copy them a second time into memory allocated with an alloca instruction.
885 void copyArgsPassedByValToAllocas();
886
Yury Gribov55441bb2014-11-21 10:29:50 +0000887 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000888 // poisoned red zones around all of them.
889 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000890 void processStaticAllocas();
891 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000892
Yury Gribov98b18592015-05-28 07:51:49 +0000893 void createDynamicAllocasInitStorage();
894
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000895 // ----------------------- Visitors.
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000896 /// Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000897 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000898
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000899 /// Collect all Resume instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000900 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
901
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000902 /// Collect all CatchReturnInst instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000903 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
904
Yury Gribov98b18592015-05-28 07:51:49 +0000905 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
906 Value *SavedStack) {
907 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000908 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
909 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
910 // need to adjust extracted SP to compute the address of the most recent
911 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
912 // this purpose.
913 if (!isa<ReturnInst>(InstBefore)) {
914 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
915 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
916 {IntptrTy});
917
918 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
919
920 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
921 DynamicAreaOffset);
922 }
923
Yury Gribov781bce22015-05-28 08:03:28 +0000924 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000925 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000926 }
927
Yury Gribov55441bb2014-11-21 10:29:50 +0000928 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000929 void unpoisonDynamicAllocas() {
930 for (auto &Ret : RetVec)
931 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000932
Yury Gribov98b18592015-05-28 07:51:49 +0000933 for (auto &StackRestoreInst : StackRestoreVec)
934 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
935 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000936 }
937
Yury Gribov55441bb2014-11-21 10:29:50 +0000938 // Deploy and poison redzones around dynamic alloca call. To do this, we
939 // should replace this call with another one with changed parameters and
940 // replace all its uses with new address, so
941 // addr = alloca type, old_size, align
942 // is replaced by
943 // new_size = (old_size + additional_size) * sizeof(type)
944 // tmp = alloca i8, new_size, max(align, 32)
945 // addr = tmp + 32 (first 32 bytes are for the left redzone).
946 // Additional_size is added to make new memory allocation contain not only
947 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000948 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000949
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000950 /// Collect Alloca instructions we want (and can) handle.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000951 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000952 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000953 if (AI.isStaticAlloca()) {
954 // Skip over allocas that are present *before* the first instrumented
955 // alloca, we don't want to move those around.
956 if (AllocaVec.empty())
957 return;
958
959 StaticAllocasToMoveUp.push_back(&AI);
960 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000961 return;
962 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000963
964 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000965 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000966 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000967 else
968 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000969 }
970
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000971 /// Collect lifetime intrinsic calls to check for use-after-scope
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000972 /// errors.
973 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000974 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000975 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000976 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000977 if (!ASan.UseAfterScope)
978 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000979 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000980 return;
981 // Found lifetime intrinsic, add ASan instrumentation if necessary.
982 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
983 // If size argument is undefined, don't do anything.
984 if (Size->isMinusOne()) return;
985 // Check that size doesn't saturate uint64_t and can
986 // be stored in IntptrTy.
987 const uint64_t SizeValue = Size->getValue().getLimitedValue();
988 if (SizeValue == ~0ULL ||
989 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
990 return;
991 // Find alloca instruction that corresponds to llvm.lifetime argument.
992 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000993 if (!AI || !ASan.isInterestingAlloca(*AI))
994 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000995 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000996 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000997 if (AI->isStaticAlloca())
998 StaticAllocaPoisonCallVec.push_back(APC);
999 else if (ClInstrumentDynamicAllocas)
1000 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001001 }
1002
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001003 void visitCallSite(CallSite CS) {
1004 Instruction *I = CS.getInstruction();
1005 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00001006 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1007 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1008 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001009 HasReturnsTwiceCall |= CI->canReturnTwice();
1010 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001011 }
1012
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001013 // ---------------------- Helpers.
1014 void initializeCallbacks(Module &M);
1015
Yury Gribov3ae427d2014-12-01 08:47:58 +00001016 bool doesDominateAllExits(const Instruction *I) const {
1017 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001018 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001019 }
1020 return true;
1021 }
1022
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001023 /// Finds alloca where the value comes from.
1024 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001025
1026 // Copies bytes from ShadowBytes into shadow memory for indexes where
1027 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1028 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1029 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1030 IRBuilder<> &IRB, Value *ShadowBase);
1031 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1032 size_t Begin, size_t End, IRBuilder<> &IRB,
1033 Value *ShadowBase);
1034 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1035 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1036 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1037
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001038 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001039
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001040 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1041 bool Dynamic);
1042 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1043 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001044};
1045
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001046} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001047
1048char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001049
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001050INITIALIZE_PASS_BEGIN(
1051 AddressSanitizer, "asan",
1052 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1053 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001054INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001055INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001056INITIALIZE_PASS_END(
1057 AddressSanitizer, "asan",
1058 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1059 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001060
Yury Gribovd7731982015-11-11 10:36:49 +00001061FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001062 bool Recover,
1063 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001064 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001065 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001066}
1067
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001068char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001069
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001070INITIALIZE_PASS(
1071 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001072 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001073 "ModulePass",
1074 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001075
Yury Gribovd7731982015-11-11 10:36:49 +00001076ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001077 bool Recover,
1078 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +00001079 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001080 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001081}
1082
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001083static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001084 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001085 assert(Res < kNumberOfAccessSizes);
1086 return Res;
1087}
1088
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001089// Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001090static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1091 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001092 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001093 // We use private linkage for module-local strings. If they can be merged
1094 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001095 GlobalVariable *GV =
1096 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001097 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001098 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +00001099 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1100 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001101}
1102
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001103/// Create a global describing a source location.
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001104static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1105 LocationMetadata MD) {
1106 Constant *LocData[] = {
1107 createPrivateGlobalForString(M, MD.Filename, true),
1108 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1109 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1110 };
1111 auto LocStruct = ConstantStruct::getAnon(LocData);
1112 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1113 GlobalValue::PrivateLinkage, LocStruct,
1114 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001115 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001116 return GV;
1117}
1118
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001119/// Check if \p G has been created by a trusted compiler pass.
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001120static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1121 // Do not instrument asan globals.
1122 if (G->getName().startswith(kAsanGenPrefix) ||
1123 G->getName().startswith(kSanCovGenPrefix) ||
1124 G->getName().startswith(kODRGenPrefix))
1125 return true;
1126
1127 // Do not instrument gcov counter arrays.
1128 if (G->getName() == "__llvm_gcov_ctr")
1129 return true;
1130
1131 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001132}
1133
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001134Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1135 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001136 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001137 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001138 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001139 Value *ShadowBase;
1140 if (LocalDynamicShadow)
1141 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001142 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001143 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1144 if (Mapping.OrShadowOffset)
1145 return IRB.CreateOr(Shadow, ShadowBase);
1146 else
1147 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001148}
1149
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001150// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001151void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1152 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001153 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001154 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001155 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001156 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1157 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1158 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001159 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001160 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001161 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001162 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1163 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1164 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001165 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001166 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001167}
1168
Anna Zaks8ed1d812015-02-27 03:12:36 +00001169/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001170bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001171 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1172
1173 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1174 return PreviouslySeenAllocaInfo->getSecond();
1175
Yury Gribov98b18592015-05-28 07:51:49 +00001176 bool IsInteresting =
1177 (AI.getAllocatedType()->isSized() &&
1178 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001179 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001180 // We are only interested in allocas not promotable to registers.
1181 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001182 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1183 // inalloca allocas are not treated as static, and we don't want
1184 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001185 !AI.isUsedWithInAlloca() &&
1186 // swifterror allocas are register promoted by ISel
1187 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001188
1189 ProcessedAllocas[&AI] = IsInteresting;
1190 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001191}
1192
Anna Zaks8ed1d812015-02-27 03:12:36 +00001193Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1194 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001195 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001196 unsigned *Alignment,
1197 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001198 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001199 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001200
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001201 // Do not instrument the load fetching the dynamic shadow address.
1202 if (LocalDynamicShadow == I)
1203 return nullptr;
1204
Anna Zaks8ed1d812015-02-27 03:12:36 +00001205 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001206 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001207 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001208 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001209 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001210 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001211 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001212 PtrOperand = LI->getPointerOperand();
1213 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001214 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001215 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001216 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001217 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001218 PtrOperand = SI->getPointerOperand();
1219 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001220 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001221 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001222 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001223 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001224 PtrOperand = RMW->getPointerOperand();
1225 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001226 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001227 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001228 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001229 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001230 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001231 } else if (auto CI = dyn_cast<CallInst>(I)) {
1232 auto *F = dyn_cast<Function>(CI->getCalledValue());
1233 if (F && (F->getName().startswith("llvm.masked.load.") ||
1234 F->getName().startswith("llvm.masked.store."))) {
1235 unsigned OpOffset = 0;
1236 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001237 if (!ClInstrumentWrites)
1238 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001239 // Masked store has an initial operand for the value.
1240 OpOffset = 1;
1241 *IsWrite = true;
1242 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001243 if (!ClInstrumentReads)
1244 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001245 *IsWrite = false;
1246 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001247
1248 auto BasePtr = CI->getOperand(0 + OpOffset);
1249 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1250 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1251 if (auto AlignmentConstant =
1252 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1253 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1254 else
1255 *Alignment = 1; // No alignment guarantees. We probably got Undef
1256 if (MaybeMask)
1257 *MaybeMask = CI->getOperand(2 + OpOffset);
1258 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001259 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001260 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001261
Anna Zaks644d9d32016-06-22 00:15:52 +00001262 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001263 // Do not instrument acesses from different address spaces; we cannot deal
1264 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001265 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1266 if (PtrTy->getPointerAddressSpace() != 0)
1267 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001268
1269 // Ignore swifterror addresses.
1270 // swifterror memory addresses are mem2reg promoted by instruction
1271 // selection. As such they cannot have regular uses like an instrumentation
1272 // function and it makes no sense to track them as memory.
1273 if (PtrOperand->isSwiftError())
1274 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001275 }
1276
Anna Zaks8ed1d812015-02-27 03:12:36 +00001277 // Treat memory accesses to promotable allocas as non-interesting since they
1278 // will not cause memory violations. This greatly speeds up the instrumented
1279 // executable at -O0.
1280 if (ClSkipPromotableAllocas)
1281 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1282 return isInterestingAlloca(*AI) ? AI : nullptr;
1283
1284 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001285}
1286
Kostya Serebryany796f6552014-02-27 12:45:36 +00001287static bool isPointerOperand(Value *V) {
1288 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1289}
1290
1291// This is a rough heuristic; it may cause both false positives and
1292// false negatives. The proper implementation requires cooperation with
1293// the frontend.
1294static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1295 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001296 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001297 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001298 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001299 } else {
1300 return false;
1301 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001302 return isPointerOperand(I->getOperand(0)) &&
1303 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001304}
1305
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001306bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1307 // If a global variable does not have dynamic initialization we don't
1308 // have to instrument it. However, if a global does not have initializer
1309 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001310 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001311}
1312
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001313void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1314 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001315 IRBuilder<> IRB(I);
1316 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1317 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001318 for (Value *&i : Param) {
1319 if (i->getType()->isPointerTy())
1320 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001321 }
David Blaikieff6409d2015-05-18 22:13:54 +00001322 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001323}
1324
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001325static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001326 Instruction *InsertBefore, Value *Addr,
1327 unsigned Alignment, unsigned Granularity,
1328 uint32_t TypeSize, bool IsWrite,
1329 Value *SizeArgument, bool UseCalls,
1330 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001331 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1332 // if the data is properly aligned.
1333 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1334 TypeSize == 128) &&
1335 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001336 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1337 nullptr, UseCalls, Exp);
1338 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1339 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001340}
1341
1342static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1343 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001344 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001345 Value *Addr, unsigned Alignment,
1346 unsigned Granularity, uint32_t TypeSize,
1347 bool IsWrite, Value *SizeArgument,
1348 bool UseCalls, uint32_t Exp) {
1349 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1350 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1351 unsigned Num = VTy->getVectorNumElements();
1352 auto Zero = ConstantInt::get(IntptrTy, 0);
1353 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001354 Value *InstrumentedAddress = nullptr;
1355 Instruction *InsertBefore = I;
1356 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1357 // dyn_cast as we might get UndefValue
1358 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001359 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001360 // Mask is constant false, so no instrumentation needed.
1361 continue;
1362 // If we have a true or undef value, fall through to doInstrumentAddress
1363 // with InsertBefore == I
1364 }
1365 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001366 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001367 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1368 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1369 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001370 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001371
1372 IRBuilder<> IRB(InsertBefore);
1373 InstrumentedAddress =
1374 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1375 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1376 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1377 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001378 }
1379}
1380
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001381void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001382 Instruction *I, bool UseCalls,
1383 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001384 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001385 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001386 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001387 Value *MaybeMask = nullptr;
1388 Value *Addr =
1389 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001390 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001391
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001392 // Optimization experiments.
1393 // The experiments can be used to evaluate potential optimizations that remove
1394 // instrumentation (assess false negatives). Instead of completely removing
1395 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1396 // experiments that want to remove instrumentation of this instruction).
1397 // If Exp is non-zero, this pass will emit special calls into runtime
1398 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1399 // make runtime terminate the program in a special way (with a different
1400 // exit status). Then you run the new compiler on a buggy corpus, collect
1401 // the special terminations (ideally, you don't see them at all -- no false
1402 // negatives) and make the decision on the optimization.
1403 uint32_t Exp = ClForceExperiment;
1404
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001405 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001406 // If initialization order checking is disabled, a simple access to a
1407 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001408 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001409 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001410 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1411 NumOptimizedAccessesToGlobalVar++;
1412 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001413 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001414 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001415
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001416 if (ClOpt && ClOptStack) {
1417 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001418 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001419 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1420 NumOptimizedAccessesToStackVar++;
1421 return;
1422 }
1423 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001424
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001425 if (IsWrite)
1426 NumInstrumentedWrites++;
1427 else
1428 NumInstrumentedReads++;
1429
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001430 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001431 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001432 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1433 Alignment, Granularity, TypeSize, IsWrite,
1434 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001435 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001436 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001437 IsWrite, nullptr, UseCalls, Exp);
1438 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001439}
1440
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001441Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1442 Value *Addr, bool IsWrite,
1443 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001444 Value *SizeArgument,
1445 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001446 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001447 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1448 CallInst *Call = nullptr;
1449 if (SizeArgument) {
1450 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001451 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1452 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001453 else
David Blaikieff6409d2015-05-18 22:13:54 +00001454 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1455 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001456 } else {
1457 if (Exp == 0)
1458 Call =
1459 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1460 else
David Blaikieff6409d2015-05-18 22:13:54 +00001461 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1462 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001463 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001464
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001465 // We don't do Call->setDoesNotReturn() because the BB already has
1466 // UnreachableInst at the end.
1467 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001468 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001469 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470}
1471
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001472Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001473 Value *ShadowValue,
1474 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001475 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001476 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001477 Value *LastAccessedByte =
1478 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001479 // (Addr & (Granularity - 1)) + size - 1
1480 if (TypeSize / 8 > 1)
1481 LastAccessedByte = IRB.CreateAdd(
1482 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1483 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001484 LastAccessedByte =
1485 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001486 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1487 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1488}
1489
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001490void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001491 Instruction *InsertBefore, Value *Addr,
1492 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001493 Value *SizeArgument, bool UseCalls,
1494 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001495 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001496 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001497 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1498
1499 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001500 if (Exp == 0)
1501 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1502 AddrLong);
1503 else
David Blaikieff6409d2015-05-18 22:13:54 +00001504 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1505 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001506 return;
1507 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001508
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001509 Type *ShadowTy =
1510 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001511 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1512 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1513 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001514 Value *ShadowValue =
1515 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001516
1517 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001518 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001519 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001520
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001521 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001522 // We use branch weights for the slow path check, to indicate that the slow
1523 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001524 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1525 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001526 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001527 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001528 IRB.SetInsertPoint(CheckTerm);
1529 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001530 if (Recover) {
1531 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1532 } else {
1533 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001534 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001535 CrashTerm = new UnreachableInst(*C, CrashBlock);
1536 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1537 ReplaceInstWithInst(CheckTerm, NewTerm);
1538 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001539 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001540 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001541 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001542
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001543 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001544 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001545 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001546}
1547
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001548// Instrument unusual size or unusual alignment.
1549// We can not do it with a single check, so we do 1-byte check for the first
1550// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1551// to report the actual access size.
1552void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001553 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1554 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1555 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001556 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1557 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1558 if (UseCalls) {
1559 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001560 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1561 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001562 else
David Blaikieff6409d2015-05-18 22:13:54 +00001563 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1564 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001565 } else {
1566 Value *LastByte = IRB.CreateIntToPtr(
1567 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1568 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001569 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1570 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001571 }
1572}
1573
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001574void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1575 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001576 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001577 IRBuilder<> IRB(&GlobalInit.front(),
1578 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001579
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001580 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001581 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1582 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001583
1584 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001585 for (auto &BB : GlobalInit.getBasicBlockList())
1586 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001587 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001588}
1589
1590void AddressSanitizerModule::createInitializerPoisonCalls(
1591 Module &M, GlobalValue *ModuleName) {
1592 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001593 if (!GV)
1594 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001595
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001596 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1597 if (!CA)
1598 return;
1599
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001600 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001601 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001602 ConstantStruct *CS = cast<ConstantStruct>(OP);
1603
1604 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001605 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001606 if (F->getName() == kAsanModuleCtorName) continue;
1607 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1608 // Don't instrument CTORs that will run before asan.module_ctor.
1609 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1610 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001611 }
1612 }
1613}
1614
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001615bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001616 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001617 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001618
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001619 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001620 if (!Ty->isSized()) return false;
1621 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001622 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001623 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001624 // Don't handle ODR linkage types and COMDATs since other modules may be built
1625 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001626 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1627 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1628 G->getLinkage() != GlobalVariable::InternalLinkage)
1629 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001630 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001631 // Two problems with thread-locals:
1632 // - The address of the main thread's copy can't be computed at link-time.
1633 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001634 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001635 // For now, just ignore this Global if the alignment is large.
1636 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001637
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001638 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001639 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001640
Anna Zaks11904602015-06-09 00:58:08 +00001641 // Globals from llvm.metadata aren't emitted, do not instrument them.
1642 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001643 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001644 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001645
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001646 // Do not instrument function pointers to initialization and termination
1647 // routines: dynamic linker will not properly handle redzones.
1648 if (Section.startswith(".preinit_array") ||
1649 Section.startswith(".init_array") ||
1650 Section.startswith(".fini_array")) {
1651 return false;
1652 }
1653
Anna Zaks11904602015-06-09 00:58:08 +00001654 // Callbacks put into the CRT initializer/terminator sections
1655 // should not be instrumented.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001656 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001657 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1658 if (Section.startswith(".CRT")) {
1659 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1660 return false;
1661 }
1662
Kuba Brecka1001bb52014-12-05 22:19:18 +00001663 if (TargetTriple.isOSBinFormatMachO()) {
1664 StringRef ParsedSegment, ParsedSection;
1665 unsigned TAA = 0, StubSize = 0;
1666 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001667 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1668 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001669 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001670
1671 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1672 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1673 // them.
1674 if (ParsedSegment == "__OBJC" ||
1675 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1676 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1677 return false;
1678 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001679 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001680 // Constant CFString instances are compiled in the following way:
1681 // -- the string buffer is emitted into
1682 // __TEXT,__cstring,cstring_literals
1683 // -- the constant NSConstantString structure referencing that buffer
1684 // is placed into __DATA,__cfstring
1685 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1686 // Moreover, it causes the linker to crash on OS X 10.7
1687 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1688 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1689 return false;
1690 }
1691 // The linker merges the contents of cstring_literals and removes the
1692 // trailing zeroes.
1693 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1694 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1695 return false;
1696 }
1697 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001698 }
1699
1700 return true;
1701}
1702
Ryan Govostes653f9d02016-03-28 20:28:57 +00001703// On Mach-O platforms, we emit global metadata in a separate section of the
1704// binary in order to allow the linker to properly dead strip. This is only
1705// supported on recent versions of ld64.
1706bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1707 if (!TargetTriple.isOSBinFormatMachO())
1708 return false;
1709
1710 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1711 return true;
1712 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001713 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001714 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1715 return true;
1716
1717 return false;
1718}
1719
Reid Kleckner01660a32016-11-21 20:40:37 +00001720StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1721 switch (TargetTriple.getObjectFormat()) {
1722 case Triple::COFF: return ".ASAN$GL";
1723 case Triple::ELF: return "asan_globals";
1724 case Triple::MachO: return "__DATA,__asan_globals,regular";
1725 default: break;
1726 }
1727 llvm_unreachable("unsupported object format");
1728}
1729
Alexey Samsonov788381b2012-12-25 12:28:20 +00001730void AddressSanitizerModule::initializeCallbacks(Module &M) {
1731 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001732
Alexey Samsonov788381b2012-12-25 12:28:20 +00001733 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001734 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001735 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001736 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001737 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001738 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001739 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001740
Alexey Samsonov788381b2012-12-25 12:28:20 +00001741 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001742 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001743 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001744 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001745 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1746 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001747 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001748 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001749
1750 // Declare the functions that find globals in a shared object and then invoke
1751 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001752 AsanRegisterImageGlobals =
1753 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001754 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001755 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001756
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001757 AsanUnregisterImageGlobals =
1758 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001759 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001760 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001761
1762 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1763 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1764 IntptrTy, IntptrTy, IntptrTy));
1765 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1766
1767 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1768 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1769 IntptrTy, IntptrTy, IntptrTy));
1770 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001771}
1772
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001773// Put the metadata and the instrumented global in the same group. This ensures
1774// that the metadata is discarded if the instrumented global is discarded.
1775void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001776 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001777 Module &M = *G->getParent();
1778 Comdat *C = G->getComdat();
1779 if (!C) {
1780 if (!G->hasName()) {
1781 // If G is unnamed, it must be internal. Give it an artificial name
1782 // so we can put it in a comdat.
1783 assert(G->hasLocalLinkage());
1784 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1785 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001786
1787 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1788 std::string Name = G->getName();
1789 Name += InternalSuffix;
1790 C = M.getOrInsertComdat(Name);
1791 } else {
1792 C = M.getOrInsertComdat(G->getName());
1793 }
1794
Reid Klecknerc212cc82017-10-31 16:16:08 +00001795 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1796 // linkage to internal linkage so that a symbol table entry is emitted. This
1797 // is necessary in order to create the comdat group.
1798 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001799 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001800 if (G->hasPrivateLinkage())
1801 G->setLinkage(GlobalValue::InternalLinkage);
1802 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001803 G->setComdat(C);
1804 }
1805
1806 assert(G->hasComdat());
1807 Metadata->setComdat(G->getComdat());
1808}
1809
1810// Create a separate metadata global and put it in the appropriate ASan
1811// global registration section.
1812GlobalVariable *
1813AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1814 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001815 auto Linkage = TargetTriple.isOSBinFormatMachO()
1816 ? GlobalVariable::InternalLinkage
1817 : GlobalVariable::PrivateLinkage;
1818 GlobalVariable *Metadata = new GlobalVariable(
1819 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001820 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001821 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001822 return Metadata;
1823}
1824
1825IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001826 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001827 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1828 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1829 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001830
1831 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1832}
1833
1834void AddressSanitizerModule::InstrumentGlobalsCOFF(
1835 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1836 ArrayRef<Constant *> MetadataInitializers) {
1837 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001838 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001839
1840 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001841 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001842 GlobalVariable *G = ExtendedGlobals[i];
1843 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001844 CreateMetadataGlobal(M, Initializer, G->getName());
1845
1846 // The MSVC linker always inserts padding when linking incrementally. We
1847 // cope with that by aligning each struct to its size, which must be a power
1848 // of two.
1849 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1850 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1851 "global metadata will not be padded appropriately");
1852 Metadata->setAlignment(SizeOfGlobalStruct);
1853
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001854 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001855 }
1856}
1857
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001858void AddressSanitizerModule::InstrumentGlobalsELF(
1859 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1860 ArrayRef<Constant *> MetadataInitializers,
1861 const std::string &UniqueModuleId) {
1862 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1863
1864 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1865 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1866 GlobalVariable *G = ExtendedGlobals[i];
1867 GlobalVariable *Metadata =
1868 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1869 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1870 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1871 MetadataGlobals[i] = Metadata;
1872
1873 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1874 }
1875
1876 // Update llvm.compiler.used, adding the new metadata globals. This is
1877 // needed so that during LTO these variables stay alive.
1878 if (!MetadataGlobals.empty())
1879 appendToCompilerUsed(M, MetadataGlobals);
1880
1881 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1882 // to look up the loaded image that contains it. Second, we can store in it
1883 // whether registration has already occurred, to prevent duplicate
1884 // registration.
1885 //
1886 // Common linkage ensures that there is only one global per shared library.
1887 GlobalVariable *RegisteredFlag = new GlobalVariable(
1888 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1889 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1890 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1891
1892 // Create start and stop symbols.
1893 GlobalVariable *StartELFMetadata = new GlobalVariable(
1894 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1895 "__start_" + getGlobalMetadataSection());
1896 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1897 GlobalVariable *StopELFMetadata = new GlobalVariable(
1898 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1899 "__stop_" + getGlobalMetadataSection());
1900 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1901
1902 // Create a call to register the globals with the runtime.
1903 IRB.CreateCall(AsanRegisterElfGlobals,
1904 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1905 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1906 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1907
1908 // We also need to unregister globals at the end, e.g., when a shared library
1909 // gets closed.
1910 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1911 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1912 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1913 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1914 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1915}
1916
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001917void AddressSanitizerModule::InstrumentGlobalsMachO(
1918 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1919 ArrayRef<Constant *> MetadataInitializers) {
1920 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1921
1922 // On recent Mach-O platforms, use a structure which binds the liveness of
1923 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1924 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001925 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001926 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1927
1928 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1929 Constant *Initializer = MetadataInitializers[i];
1930 GlobalVariable *G = ExtendedGlobals[i];
1931 GlobalVariable *Metadata =
1932 CreateMetadataGlobal(M, Initializer, G->getName());
1933
1934 // On recent Mach-O platforms, we emit the global metadata in a way that
1935 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001936 auto LivenessBinder =
1937 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1938 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001939 GlobalVariable *Liveness = new GlobalVariable(
1940 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1941 Twine("__asan_binder_") + G->getName());
1942 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1943 LivenessGlobals[i] = Liveness;
1944 }
1945
1946 // Update llvm.compiler.used, adding the new liveness globals. This is
1947 // needed so that during LTO these variables stay alive. The alternative
1948 // would be to have the linker handling the LTO symbols, but libLTO
1949 // current API does not expose access to the section for each symbol.
1950 if (!LivenessGlobals.empty())
1951 appendToCompilerUsed(M, LivenessGlobals);
1952
1953 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1954 // to look up the loaded image that contains it. Second, we can store in it
1955 // whether registration has already occurred, to prevent duplicate
1956 // registration.
1957 //
1958 // common linkage ensures that there is only one global per shared library.
1959 GlobalVariable *RegisteredFlag = new GlobalVariable(
1960 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1961 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1962 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1963
1964 IRB.CreateCall(AsanRegisterImageGlobals,
1965 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1966
1967 // We also need to unregister globals at the end, e.g., when a shared library
1968 // gets closed.
1969 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1970 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1971 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1972}
1973
1974void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1975 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1976 ArrayRef<Constant *> MetadataInitializers) {
1977 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1978 unsigned N = ExtendedGlobals.size();
1979 assert(N > 0);
1980
1981 // On platforms that don't have a custom metadata section, we emit an array
1982 // of global metadata structures.
1983 ArrayType *ArrayOfGlobalStructTy =
1984 ArrayType::get(MetadataInitializers[0]->getType(), N);
1985 auto AllGlobals = new GlobalVariable(
1986 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1987 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00001988 if (Mapping.Scale > 3)
1989 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001990
1991 IRB.CreateCall(AsanRegisterGlobals,
1992 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1993 ConstantInt::get(IntptrTy, N)});
1994
1995 // We also need to unregister globals at the end, e.g., when a shared library
1996 // gets closed.
1997 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1998 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1999 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2000 ConstantInt::get(IntptrTy, N)});
2001}
2002
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002003// This function replaces all global variables with new variables that have
2004// trailing redzones. It also creates a function that poisons
2005// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002006// Sets *CtorComdat to true if the global registration code emitted into the
2007// asan constructor is comdat-compatible.
2008bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2009 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002010 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002011
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002012 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2013
Alexey Samsonova02e6642014-05-29 18:40:48 +00002014 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002015 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002016 }
2017
2018 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002019 if (n == 0) {
2020 *CtorComdat = true;
2021 return false;
2022 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002023
Reid Kleckner78565832016-11-29 01:32:21 +00002024 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002025
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002026 // A global is described by a structure
2027 // size_t beg;
2028 // size_t size;
2029 // size_t size_with_redzone;
2030 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002031 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002032 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002033 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002034 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002035 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002036 StructType *GlobalStructTy =
2037 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002038 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002039 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2040 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002041
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002042 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002043
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002044 // We shouldn't merge same module names, as this string serves as unique
2045 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002046 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002047 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002048
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002049 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002050 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002051 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002052
2053 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002054 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002055 // Create string holding the global name (use global name from metadata
2056 // if it's available, otherwise just write the name of global variable).
2057 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002058 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002059 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002060
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002061 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002062 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002063 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002064 // MinRZ <= RZ <= kMaxGlobalRedzone
2065 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002066 uint64_t RZ = std::max(
2067 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002068 uint64_t RightRedzoneSize = RZ;
2069 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002070 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002071 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002072 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2073
Serge Gueltone38003f2017-05-09 19:31:13 +00002074 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2075 Constant *NewInitializer = ConstantStruct::get(
2076 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002077
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002078 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002079 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2080 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2081 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002082 GlobalVariable *NewGlobal =
2083 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2084 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002085 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002086 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002087
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002088 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2089 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2090 G->isConstant()) {
2091 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2092 if (Seq && Seq->isCString())
2093 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2094 }
2095
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002096 // Transfer the debug info. The payload starts at offset zero so we can
2097 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002098 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002099 G->getDebugInfo(GVs);
2100 for (auto *GV : GVs)
2101 NewGlobal->addDebugInfo(GV);
2102
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002103 Value *Indices2[2];
2104 Indices2[0] = IRB.getInt32(0);
2105 Indices2[1] = IRB.getInt32(0);
2106
2107 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002108 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002109 NewGlobal->takeName(G);
2110 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002111 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002113 Constant *SourceLoc;
2114 if (!MD.SourceLoc.empty()) {
2115 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2116 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2117 } else {
2118 SourceLoc = ConstantInt::get(IntptrTy, 0);
2119 }
2120
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002121 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2122 GlobalValue *InstrumentedGlobal = NewGlobal;
2123
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002124 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002125 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2126 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002127 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2128 // Create local alias for NewGlobal to avoid crash on ODR between
2129 // instrumented and non-instrumented libraries.
2130 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2131 NameForGlobal + M.getName(), NewGlobal);
2132
2133 // With local aliases, we need to provide another externally visible
2134 // symbol __odr_asan_XXX to detect ODR violation.
2135 auto *ODRIndicatorSym =
2136 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2137 Constant::getNullValue(IRB.getInt8Ty()),
2138 kODRGenPrefix + NameForGlobal, nullptr,
2139 NewGlobal->getThreadLocalMode());
2140
2141 // Set meaningful attributes for indicator symbol.
2142 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2143 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2144 ODRIndicatorSym->setAlignment(1);
2145 ODRIndicator = ODRIndicatorSym;
2146 InstrumentedGlobal = GA;
2147 }
2148
Reid Kleckner01660a32016-11-21 20:40:37 +00002149 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002150 GlobalStructTy,
2151 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002152 ConstantInt::get(IntptrTy, SizeInBytes),
2153 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2154 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002155 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002156 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002157 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002158
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002159 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002160
Kostya Serebryany20343352012-10-17 13:40:06 +00002161 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002162
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002163 Initializers[i] = Initializer;
2164 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002165
Kuba Mracek8842da82018-03-08 21:02:18 +00002166 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2167 // ConstantMerge'ing them.
2168 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2169 for (size_t i = 0; i < n; i++) {
2170 GlobalVariable *G = NewGlobals[i];
2171 if (G->getName().empty()) continue;
2172 GlobalsToAddToUsedList.push_back(G);
2173 }
2174 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2175
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002176 std::string ELFUniqueModuleId =
2177 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2178 : "";
2179
2180 if (!ELFUniqueModuleId.empty()) {
2181 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2182 *CtorComdat = true;
2183 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002184 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002185 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002186 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2187 } else {
2188 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002189 }
2190
Reid Kleckner01660a32016-11-21 20:40:37 +00002191 // Create calls for poisoning before initializers run and unpoisoning after.
2192 if (HasDynamicallyInitializedGlobals)
2193 createInitializerPoisonCalls(M, ModuleName);
2194
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002195 DEBUG(dbgs() << M);
2196 return true;
2197}
2198
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002199int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2200 int LongSize = M.getDataLayout().getPointerSizeInBits();
2201 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2202 int Version = 8;
2203 // 32-bit Android is one version ahead because of the switch to dynamic
2204 // shadow.
2205 Version += (LongSize == 32 && isAndroid);
2206 return Version;
2207}
2208
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002209bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002210 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002211 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002212 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002213 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002214 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002215 initializeCallbacks(M);
2216
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002217 if (CompileKernel)
2218 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002219
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002220 // Create a module constructor. A destructor is created lazily because not all
2221 // platforms, and not all modules need it.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002222 std::string VersionCheckName =
2223 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002224 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2225 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002226 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002227
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002228 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002229 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002230 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002231 if (ClGlobals) {
2232 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002233 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2234 }
2235
2236 // Put the constructor and destructor in comdat if both
2237 // (1) global instrumentation is not TU-specific
2238 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002239 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002240 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2241 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2242 AsanCtorFunction);
2243 if (AsanDtorFunction) {
2244 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2245 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2246 AsanDtorFunction);
2247 }
2248 } else {
2249 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2250 if (AsanDtorFunction)
2251 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002252 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002253
2254 return Changed;
2255}
2256
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002257void AddressSanitizer::initializeCallbacks(Module &M) {
2258 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002259 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002260 // IsWrite, TypeSize and Exp are encoded in the function name.
2261 for (int Exp = 0; Exp < 2; Exp++) {
2262 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2263 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2264 const std::string ExpStr = Exp ? "exp_" : "";
Yury Gribovd7731982015-11-11 10:36:49 +00002265 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002266
2267 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2268 SmallVector<Type *, 2> Args1{1, IntptrTy};
2269 if (Exp) {
2270 Type *ExpType = Type::getInt32Ty(*C);
2271 Args2.push_back(ExpType);
2272 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002273 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002274 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2275 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Evgeniy Stepanov31475a02018-01-25 21:28:51 +00002276 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002277 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002278
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002279 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2280 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2281 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2282 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002283
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002284 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2285 AccessSizeIndex++) {
2286 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2287 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2288 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2289 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2290 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002291
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002292 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2293 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2294 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2295 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2296 }
2297 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002298 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002299
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002300 const std::string MemIntrinCallbackPrefix =
2301 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002302 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002303 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002304 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002305 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002306 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002307 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002308 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002309 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002310 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002311
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002312 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002313 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002314
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002315 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002316 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002317 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002318 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002319 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2320 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2321 StringRef(""), StringRef(""),
2322 /*hasSideEffects=*/true);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002323 if (Mapping.InGlobal)
2324 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2325 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002326}
2327
2328// virtual
2329bool AddressSanitizer::doInitialization(Module &M) {
2330 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002331 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002332
2333 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002334 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002335 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002336 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002337
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002338 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002339 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002340}
2341
Keno Fischere03fae42015-12-05 14:42:34 +00002342bool AddressSanitizer::doFinalization(Module &M) {
2343 GlobalsMD.reset();
2344 return false;
2345}
2346
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002347bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2348 // For each NSObject descendant having a +load method, this method is invoked
2349 // by the ObjC runtime before any of the static constructors is called.
2350 // Therefore we need to instrument such methods with a call to __asan_init
2351 // at the beginning in order to initialize our runtime before any access to
2352 // the shadow memory.
2353 // We cannot just ignore these methods, because they may call other
2354 // instrumented functions.
2355 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002356 Function *AsanInitFunction =
2357 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002358 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002359 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002360 return true;
2361 }
2362 return false;
2363}
2364
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002365void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2366 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002367 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002368 return;
2369
2370 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002371 if (Mapping.InGlobal) {
2372 if (ClWithIfuncSuppressRemat) {
2373 // An empty inline asm with input reg == output reg.
2374 // An opaque pointer-to-int cast, basically.
2375 InlineAsm *Asm = InlineAsm::get(
2376 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2377 StringRef(""), StringRef("=r,0"),
2378 /*hasSideEffects=*/false);
2379 LocalDynamicShadow =
2380 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2381 } else {
2382 LocalDynamicShadow =
2383 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2384 }
2385 } else {
2386 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2387 kAsanShadowMemoryDynamicAddress, IntptrTy);
2388 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2389 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002390}
2391
Reid Kleckner2f907552015-07-21 17:40:14 +00002392void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2393 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2394 // to it as uninteresting. This assumes we haven't started processing allocas
2395 // yet. This check is done up front because iterating the use list in
2396 // isInterestingAlloca would be algorithmically slower.
2397 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2398
2399 // Try to get the declaration of llvm.localescape. If it's not in the module,
2400 // we can exit early.
2401 if (!F.getParent()->getFunction("llvm.localescape")) return;
2402
2403 // Look for a call to llvm.localescape call in the entry block. It can't be in
2404 // any other block.
2405 for (Instruction &I : F.getEntryBlock()) {
2406 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2407 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2408 // We found a call. Mark all the allocas passed in as uninteresting.
2409 for (Value *Arg : II->arg_operands()) {
2410 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2411 assert(AI && AI->isStaticAlloca() &&
2412 "non-static alloca arg to localescape");
2413 ProcessedAllocas[AI] = false;
2414 }
2415 break;
2416 }
2417 }
2418}
2419
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002420bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002421 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002422 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002423 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002424
Etienne Bergeron78582b22016-09-15 15:45:05 +00002425 bool FunctionModified = false;
2426
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002427 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002428 // This function needs to be called even if the function body is not
2429 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002430 if (maybeInsertAsanInitAtFunctionEntry(F))
2431 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002432
2433 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002434 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002435
Etienne Bergeron752f8832016-09-14 17:18:37 +00002436 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2437
2438 initializeCallbacks(*F.getParent());
2439 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002440
Reid Kleckner2f907552015-07-21 17:40:14 +00002441 FunctionStateRAII CleanupObj(this);
2442
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002443 maybeInsertDynamicShadowAtFunctionEntry(F);
2444
Reid Kleckner2f907552015-07-21 17:40:14 +00002445 // We can't instrument allocas used with llvm.localescape. Only static allocas
2446 // can be passed to that intrinsic.
2447 markEscapedLocalAllocas(F);
2448
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002449 // We want to instrument every address only once per basic block (unless there
2450 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002451 SmallSet<Value *, 16> TempsToInstrument;
2452 SmallVector<Instruction *, 16> ToInstrument;
2453 SmallVector<Instruction *, 8> NoReturnCalls;
2454 SmallVector<BasicBlock *, 16> AllBlocks;
2455 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002456 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002457 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002458 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002459 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002460 const TargetLibraryInfo *TLI =
2461 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002462
2463 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002464 for (auto &BB : F) {
2465 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002466 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002467 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002468 for (auto &Inst : BB) {
2469 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002470 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002471 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002472 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002473 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002474 // If we have a mask, skip instrumentation if we've already
2475 // instrumented the full object. But don't add to TempsToInstrument
2476 // because we might get another load/store with a different mask.
2477 if (MaybeMask) {
2478 if (TempsToInstrument.count(Addr))
2479 continue; // We've seen this (whole) temp in the current BB.
2480 } else {
2481 if (!TempsToInstrument.insert(Addr).second)
2482 continue; // We've seen this temp in the current BB.
2483 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002484 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002485 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002486 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2487 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002488 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002489 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002490 // ok, take it.
2491 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002492 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002493 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002494 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002495 // A call inside BB.
2496 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002497 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002498 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002499 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2500 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002501 continue;
2502 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002503 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002504 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002505 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002506 }
2507 }
2508
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002509 bool UseCalls =
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002510 (ClInstrumentationWithCallsThreshold >= 0 &&
2511 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002512 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002513 ObjectSizeOpts ObjSizeOpts;
2514 ObjSizeOpts.RoundToAlign = true;
2515 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002516
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002517 // Instrument.
2518 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002519 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002520 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2521 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002522 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002523 instrumentMop(ObjSizeVis, Inst, UseCalls,
2524 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002525 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002526 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002527 }
2528 NumInstrumented++;
2529 }
2530
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002531 FunctionStackPoisoner FSP(F, *this);
2532 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002533
2534 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002535 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002536 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002537 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002538 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002539 }
2540
Alexey Samsonova02e6642014-05-29 18:40:48 +00002541 for (auto Inst : PointerComparisonsOrSubtracts) {
2542 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002543 NumInstrumented++;
2544 }
2545
Etienne Bergeron78582b22016-09-15 15:45:05 +00002546 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2547 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002548
Etienne Bergeron78582b22016-09-15 15:45:05 +00002549 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2550 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002551
Etienne Bergeron78582b22016-09-15 15:45:05 +00002552 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002553}
2554
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002555// Workaround for bug 11395: we don't want to instrument stack in functions
2556// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2557// FIXME: remove once the bug 11395 is fixed.
2558bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2559 if (LongSize != 32) return false;
2560 CallInst *CI = dyn_cast<CallInst>(I);
2561 if (!CI || !CI->isInlineAsm()) return false;
2562 if (CI->getNumArgOperands() <= 5) return false;
2563 // We have inline assembly with quite a few arguments.
2564 return true;
2565}
2566
2567void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2568 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002569 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2570 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002571 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2572 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002573 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002574 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002575 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002576 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002577 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002578 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002579 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2580 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002581 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002582 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2583 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002584 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002585 }
2586
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002587 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2588 std::ostringstream Name;
2589 Name << kAsanSetShadowPrefix;
2590 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002591 AsanSetShadowFunc[Val] =
2592 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002593 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002594 }
2595
Yury Gribov98b18592015-05-28 07:51:49 +00002596 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002597 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002598 AsanAllocasUnpoisonFunc =
2599 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002600 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002601}
2602
Vitaly Buka793913c2016-08-29 18:17:21 +00002603void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2604 ArrayRef<uint8_t> ShadowBytes,
2605 size_t Begin, size_t End,
2606 IRBuilder<> &IRB,
2607 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002608 if (Begin >= End)
2609 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002610
2611 const size_t LargestStoreSizeInBytes =
2612 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2613
2614 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2615
2616 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002617 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2618 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2619 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002620 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002621 if (!ShadowMask[i]) {
2622 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002623 ++i;
2624 continue;
2625 }
2626
2627 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2628 // Fit store size into the range.
2629 while (StoreSizeInBytes > End - i)
2630 StoreSizeInBytes /= 2;
2631
2632 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002633 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002634 while (j <= StoreSizeInBytes / 2)
2635 StoreSizeInBytes /= 2;
2636 }
2637
2638 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002639 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2640 if (IsLittleEndian)
2641 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2642 else
2643 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002644 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002645
2646 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2647 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002648 IRB.CreateAlignedStore(
2649 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002650
2651 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002652 }
2653}
2654
Vitaly Buka793913c2016-08-29 18:17:21 +00002655void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2656 ArrayRef<uint8_t> ShadowBytes,
2657 IRBuilder<> &IRB, Value *ShadowBase) {
2658 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2659}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002660
Vitaly Buka793913c2016-08-29 18:17:21 +00002661void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2662 ArrayRef<uint8_t> ShadowBytes,
2663 size_t Begin, size_t End,
2664 IRBuilder<> &IRB, Value *ShadowBase) {
2665 assert(ShadowMask.size() == ShadowBytes.size());
2666 size_t Done = Begin;
2667 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2668 if (!ShadowMask[i]) {
2669 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002670 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002671 }
2672 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002673 if (!AsanSetShadowFunc[Val])
2674 continue;
2675
2676 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002677 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002678 }
2679
2680 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002681 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002682 IRB.CreateCall(AsanSetShadowFunc[Val],
2683 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2684 ConstantInt::get(IntptrTy, j - i)});
2685 Done = j;
2686 }
2687 }
2688
Vitaly Buka793913c2016-08-29 18:17:21 +00002689 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002690}
2691
Kostya Serebryany6805de52013-09-10 13:16:56 +00002692// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2693// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2694static int StackMallocSizeClass(uint64_t LocalStackSize) {
2695 assert(LocalStackSize <= kMaxStackMallocSize);
2696 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002697 for (int i = 0;; i++, MaxSize *= 2)
2698 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002699 llvm_unreachable("impossible LocalStackSize");
2700}
2701
Vitaly Buka74443f02017-07-18 22:28:03 +00002702void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002703 Instruction *CopyInsertPoint = &F.front().front();
2704 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2705 // Insert after the dynamic shadow location is determined
2706 CopyInsertPoint = CopyInsertPoint->getNextNode();
2707 assert(CopyInsertPoint);
2708 }
2709 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002710 const DataLayout &DL = F.getParent()->getDataLayout();
2711 for (Argument &Arg : F.args()) {
2712 if (Arg.hasByValAttr()) {
2713 Type *Ty = Arg.getType()->getPointerElementType();
2714 unsigned Align = Arg.getParamAlignment();
2715 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2716
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002717 AllocaInst *AI = IRB.CreateAlloca(
2718 Ty, nullptr,
2719 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2720 ".byval");
Vitaly Buka74443f02017-07-18 22:28:03 +00002721 AI->setAlignment(Align);
2722 Arg.replaceAllUsesWith(AI);
2723
2724 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
Daniel Neilsona98d9d92018-02-08 21:26:12 +00002725 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
Vitaly Buka74443f02017-07-18 22:28:03 +00002726 }
2727 }
2728}
2729
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002730PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2731 Value *ValueIfTrue,
2732 Instruction *ThenTerm,
2733 Value *ValueIfFalse) {
2734 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2735 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2736 PHI->addIncoming(ValueIfFalse, CondBlock);
2737 BasicBlock *ThenBlock = ThenTerm->getParent();
2738 PHI->addIncoming(ValueIfTrue, ThenBlock);
2739 return PHI;
2740}
2741
2742Value *FunctionStackPoisoner::createAllocaForLayout(
2743 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2744 AllocaInst *Alloca;
2745 if (Dynamic) {
2746 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2747 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2748 "MyAlloca");
2749 } else {
2750 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2751 nullptr, "MyAlloca");
2752 assert(Alloca->isStaticAlloca());
2753 }
2754 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2755 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2756 Alloca->setAlignment(FrameAlignment);
2757 return IRB.CreatePointerCast(Alloca, IntptrTy);
2758}
2759
Yury Gribov98b18592015-05-28 07:51:49 +00002760void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2761 BasicBlock &FirstBB = *F.begin();
2762 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2763 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2764 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2765 DynamicAllocaLayout->setAlignment(32);
2766}
2767
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002768void FunctionStackPoisoner::processDynamicAllocas() {
2769 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2770 assert(DynamicAllocaPoisonCallVec.empty());
2771 return;
2772 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002773
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002774 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2775 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002776 assert(APC.InsBefore);
2777 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002778 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002779 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002780
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002781 IRBuilder<> IRB(APC.InsBefore);
2782 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002783 // Dynamic allocas will be unpoisoned unconditionally below in
2784 // unpoisonDynamicAllocas.
2785 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002786 }
2787
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002788 // Handle dynamic allocas.
2789 createDynamicAllocasInitStorage();
2790 for (auto &AI : DynamicAllocaVec)
2791 handleDynamicAllocaCall(AI);
2792 unpoisonDynamicAllocas();
2793}
Yury Gribov98b18592015-05-28 07:51:49 +00002794
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002795void FunctionStackPoisoner::processStaticAllocas() {
2796 if (AllocaVec.empty()) {
2797 assert(StaticAllocaPoisonCallVec.empty());
2798 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002799 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002800
Kostya Serebryany6805de52013-09-10 13:16:56 +00002801 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002802 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002803 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002804 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002805
2806 Instruction *InsBefore = AllocaVec[0];
2807 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002808 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002809
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002810 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2811 // debug info is broken, because only entry-block allocas are treated as
2812 // regular stack slots.
2813 auto InsBeforeB = InsBefore->getParent();
2814 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002815 for (auto *AI : StaticAllocasToMoveUp)
2816 if (AI->getParent() == InsBeforeB)
2817 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002818
Reid Kleckner2f907552015-07-21 17:40:14 +00002819 // If we have a call to llvm.localescape, keep it in the entry block.
2820 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2821
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002822 SmallVector<ASanStackVariableDescription, 16> SVD;
2823 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002824 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002825 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002826 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002827 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002828 AI->getAlignment(),
2829 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002830 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002831 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002832 SVD.push_back(D);
2833 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002834
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002835 // Minimal header size (left redzone) is 4 pointers,
2836 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00002837 size_t Granularity = 1ULL << Mapping.Scale;
2838 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00002839 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00002840 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002841
Vitaly Buka5910a922016-10-18 23:29:52 +00002842 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2843 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2844 for (auto &Desc : SVD)
2845 AllocaToSVDMap[Desc.AI] = &Desc;
2846
2847 // Update SVD with information from lifetime intrinsics.
2848 for (const auto &APC : StaticAllocaPoisonCallVec) {
2849 assert(APC.InsBefore);
2850 assert(APC.AI);
2851 assert(ASan.isInterestingAlloca(*APC.AI));
2852 assert(APC.AI->isStaticAlloca());
2853
2854 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2855 Desc.LifetimeSize = Desc.Size;
2856 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2857 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2858 if (LifetimeLoc->getFile() == FnLoc->getFile())
2859 if (unsigned Line = LifetimeLoc->getLine())
2860 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2861 }
2862 }
2863 }
2864
2865 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2866 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002867 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002868 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2869 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002870 bool DoDynamicAlloca = ClDynamicAllocaStack;
2871 // Don't do dynamic alloca or stack malloc if:
2872 // 1) There is inline asm: too often it makes assumptions on which registers
2873 // are available.
2874 // 2) There is a returns_twice call (typically setjmp), which is
2875 // optimization-hostile, and doesn't play well with introduced indirect
2876 // register-relative calculation of local variable addresses.
2877 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2878 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002879
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002880 Value *StaticAlloca =
2881 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2882
2883 Value *FakeStack;
2884 Value *LocalStackBase;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002885 Value *LocalStackBaseAlloca;
2886 bool Deref;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002887
2888 if (DoStackMalloc) {
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002889 LocalStackBaseAlloca =
2890 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002891 // void *FakeStack = __asan_option_detect_stack_use_after_return
2892 // ? __asan_stack_malloc_N(LocalStackSize)
2893 // : nullptr;
2894 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002895 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2896 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2897 Value *UseAfterReturnIsEnabled =
2898 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002899 Constant::getNullValue(IRB.getInt32Ty()));
2900 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002901 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002902 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002903 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002904 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2905 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2906 Value *FakeStackValue =
2907 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2908 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002909 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002910 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002911 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002912 ConstantInt::get(IntptrTy, 0));
2913
2914 Value *NoFakeStack =
2915 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2916 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2917 IRBIf.SetInsertPoint(Term);
2918 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2919 Value *AllocaValue =
2920 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002921
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002922 IRB.SetInsertPoint(InsBefore);
2923 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2924 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002925 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2926 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
2927 Deref = true;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002928 } else {
2929 // void *FakeStack = nullptr;
2930 // void *LocalStackBase = alloca(LocalStackSize);
2931 FakeStack = ConstantInt::get(IntptrTy, 0);
2932 LocalStackBase =
2933 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002934 LocalStackBaseAlloca = LocalStackBase;
2935 Deref = false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002936 }
2937
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002938 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002939 for (const auto &Desc : SVD) {
2940 AllocaInst *AI = Desc.AI;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002941 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
2942 Desc.Offset, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002943 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002944 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002945 AI->getType());
Alexey Samsonov261177a2012-12-04 01:34:23 +00002946 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002947 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002948
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002949 // The left-most redzone has enough space for at least 4 pointers.
2950 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002951 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2952 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2953 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002954 // Write the frame description constant to redzone[1].
2955 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002956 IRB.CreateAdd(LocalStackBase,
2957 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2958 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002959 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002960 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002961 /*AllowMerging*/ true);
2962 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002963 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002964 // Write the PC to redzone[2].
2965 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002966 IRB.CreateAdd(LocalStackBase,
2967 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2968 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002969 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002970
Vitaly Buka793913c2016-08-29 18:17:21 +00002971 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2972
2973 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002974 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002975 // As mask we must use most poisoned case: red zones and after scope.
2976 // As bytes we can use either the same or just red zones only.
2977 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2978
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002979 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002980 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2981
2982 // Poison static allocas near lifetime intrinsics.
2983 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002984 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002985 assert(Desc.Offset % L.Granularity == 0);
2986 size_t Begin = Desc.Offset / L.Granularity;
2987 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2988
2989 IRBuilder<> IRB(APC.InsBefore);
2990 copyToShadow(ShadowAfterScope,
2991 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2992 IRB, ShadowBase);
2993 }
2994 }
2995
2996 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002997 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002998
Kostya Serebryany530e2072013-12-23 14:15:08 +00002999 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003000 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003001 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003002 // Mark the current frame as retired.
3003 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3004 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003005 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00003006 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003007 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00003008 // // In use-after-return mode, poison the whole stack frame.
3009 // if StackMallocIdx <= 4
3010 // // For small sizes inline the whole thing:
3011 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003012 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00003013 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003014 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00003015 // else
3016 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003017 Value *Cmp =
3018 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00003019 TerminatorInst *ThenTerm, *ElseTerm;
3020 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3021
3022 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003023 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003024 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003025 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3026 kAsanStackUseAfterReturnMagic);
3027 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3028 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003029 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003030 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003031 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3032 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3033 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3034 IRBPoison.CreateStore(
3035 Constant::getNullValue(IRBPoison.getInt8Ty()),
3036 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3037 } else {
3038 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003039 IRBPoison.CreateCall(
3040 AsanStackFreeFunc[StackMallocIdx],
3041 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003042 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003043
3044 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003045 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003046 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003047 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003048 }
3049 }
3050
Kostya Serebryany09959942012-10-19 06:20:53 +00003051 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003052 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003053}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003054
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003055void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003056 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003057 // For now just insert the call to ASan runtime.
3058 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3059 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003060 IRB.CreateCall(
3061 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3062 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003063}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003064
3065// Handling llvm.lifetime intrinsics for a given %alloca:
3066// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3067// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3068// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3069// could be poisoned by previous llvm.lifetime.end instruction, as the
3070// variable may go in and out of scope several times, e.g. in loops).
3071// (3) if we poisoned at least one %alloca in a function,
3072// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003073
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003074AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3075 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003076 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003077 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003078 // See if we've already calculated (or started to calculate) alloca for a
3079 // given value.
3080 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003081 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003082 // Store 0 while we're calculating alloca for value V to avoid
3083 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003084 AllocaForValue[V] = nullptr;
3085 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003086 if (CastInst *CI = dyn_cast<CastInst>(V))
3087 Res = findAllocaForValue(CI->getOperand(0));
3088 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003089 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003090 // Allow self-referencing phi-nodes.
3091 if (IncValue == PN) continue;
3092 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3093 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003094 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3095 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003096 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003097 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003098 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3099 Res = findAllocaForValue(EP->getPointerOperand());
3100 } else {
3101 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003102 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003103 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003104 return Res;
3105}
Yury Gribov55441bb2014-11-21 10:29:50 +00003106
Yury Gribov98b18592015-05-28 07:51:49 +00003107void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003108 IRBuilder<> IRB(AI);
3109
Yury Gribov55441bb2014-11-21 10:29:50 +00003110 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3111 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3112
3113 Value *Zero = Constant::getNullValue(IntptrTy);
3114 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3115 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003116
3117 // Since we need to extend alloca with additional memory to locate
3118 // redzones, and OldSize is number of allocated blocks with
3119 // ElementSize size, get allocated memory size in bytes by
3120 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003121 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003122 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003123 Value *OldSize =
3124 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3125 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003126
3127 // PartialSize = OldSize % 32
3128 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3129
3130 // Misalign = kAllocaRzSize - PartialSize;
3131 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3132
3133 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3134 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3135 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3136
3137 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3138 // Align is added to locate left redzone, PartialPadding for possible
3139 // partial redzone and kAllocaRzSize for right redzone respectively.
3140 Value *AdditionalChunkSize = IRB.CreateAdd(
3141 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3142
3143 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3144
3145 // Insert new alloca with new NewSize and Align params.
3146 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3147 NewAlloca->setAlignment(Align);
3148
3149 // NewAddress = Address + Align
3150 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3151 ConstantInt::get(IntptrTy, Align));
3152
Yury Gribov98b18592015-05-28 07:51:49 +00003153 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003154 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003155
3156 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3157 // for unpoisoning stuff.
3158 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3159
Yury Gribov55441bb2014-11-21 10:29:50 +00003160 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3161
Yury Gribov98b18592015-05-28 07:51:49 +00003162 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003163 AI->replaceAllUsesWith(NewAddressPtr);
3164
Yury Gribov98b18592015-05-28 07:51:49 +00003165 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003166 AI->eraseFromParent();
3167}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003168
3169// isSafeAccess returns true if Addr is always inbounds with respect to its
3170// base object. For example, it is a field access or an array access with
3171// constant inbounds index.
3172bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3173 Value *Addr, uint64_t TypeSize) const {
3174 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3175 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003176 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003177 int64_t Offset = SizeOffset.second.getSExtValue();
3178 // Three checks are required to ensure safety:
3179 // . Offset >= 0 (since the offset is given from the base ptr)
3180 // . Size >= Offset (unsigned)
3181 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003182 return Offset >= 0 && Size >= uint64_t(Offset) &&
3183 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003184}