blob: c707dfc0b50a766bc13abb0b4dcead9153249364 [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"
28#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000029#include "llvm/BinaryFormat/MachO.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000030#include "llvm/IR/Argument.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000031#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000034#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000037#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000039#include "llvm/IR/DebugInfoMetadata.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/DerivedTypes.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000042#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000044#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000049#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000056#include "llvm/IR/MDBuilder.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000057#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Module.h"
59#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000060#include "llvm/IR/Use.h"
61#include "llvm/IR/Value.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000062#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000063#include "llvm/Pass.h"
64#include "llvm/Support/Casting.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065#include "llvm/Support/CommandLine.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000067#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/MathExtras.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000069#include "llvm/Support/ScopedPrinter.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000070#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000072#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000073#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000074#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000075#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000076#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000078#include <cassert>
79#include <cstddef>
80#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000081#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000082#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000083#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000084#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000086#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
88using namespace llvm;
89
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "asan"
91
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const uint64_t kDefaultShadowScale = 3;
93static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000098static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Walter Lee8f1545c2017-11-16 17:03:00 +0000100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
101static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
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 Stepanov989299c2017-11-10 22:27:48 +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 Stepanov989299c2017-11-10 22:27:48 +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"),
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +0000215 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));
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000222
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 Stepanov989299c2017-11-10 22:27:48 +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 Stepanov989299c2017-11-10 22:27:48 +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 Stepanov989299c2017-11-10 22:27:48 +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 Stepanov989299c2017-11-10 22:27:48 +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 Stepanov396ed672017-11-16 02:52:19 +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)
Yury Gribovd7731982015-11-11 10:36:49 +0000592 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000593 Recover(Recover || ClRecover),
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000594 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000595 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
596 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000597
Mehdi Amini117296c2016-10-01 02:56:57 +0000598 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000599 return "AddressSanitizerFunctionPass";
600 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000601
Yury Gribov3ae427d2014-12-01 08:47:58 +0000602 void getAnalysisUsage(AnalysisUsage &AU) const override {
603 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000604 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000605 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000606
Vitaly Buka21a9e572016-07-28 22:50:50 +0000607 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000608 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000609 if (AI.isArrayAllocation()) {
610 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000611 assert(CI && "non-constant array size");
612 ArraySize = CI->getZExtValue();
613 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000614 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000616 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000617 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000618 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000619
Anna Zaks8ed1d812015-02-27 03:12:36 +0000620 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000621 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000622
Anna Zaks8ed1d812015-02-27 03:12:36 +0000623 /// If it is an interesting memory access, return the PointerOperand
624 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000625 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
626 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000627 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000628 uint64_t *TypeSize, unsigned *Alignment,
629 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000630
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000631 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000632 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000633 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000634 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
635 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000636 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000637 void instrumentUnusualSizeOrAlignment(Instruction *I,
638 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000639 uint32_t TypeSize, bool IsWrite,
640 Value *SizeArgument, bool UseCalls,
641 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000642 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
643 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000644 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000645 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000646 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000647 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000648 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000649 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000650 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000651 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000652 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000653 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000654 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000655
Yury Gribov3ae427d2014-12-01 08:47:58 +0000656 DominatorTree &getDominatorTree() const { return *DT; }
657
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000658private:
659 friend struct FunctionStackPoisoner;
660
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000661 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000662
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000663 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000664 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000665 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
666 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000667
Reid Kleckner2f907552015-07-21 17:40:14 +0000668 /// Helper to cleanup per-function state.
669 struct FunctionStateRAII {
670 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000671
Reid Kleckner2f907552015-07-21 17:40:14 +0000672 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
673 assert(Pass->ProcessedAllocas.empty() &&
674 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000675 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000676 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000677
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000678 ~FunctionStateRAII() {
679 Pass->LocalDynamicShadow = nullptr;
680 Pass->ProcessedAllocas.clear();
681 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000682 };
683
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000684 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000685 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000686 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000687 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000688 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000689 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000690 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000691 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000692 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000693 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000694 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000695 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000696
697 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000698 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
699 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000700
701 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000702 Function *AsanErrorCallbackSized[2][2];
703 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000704
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000705 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000706 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000707 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000708 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000709 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000710};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000711
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000712class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000713public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000714 // Pass identification, replacement for typeid
715 static char ID;
716
Yury Gribovd7731982015-11-11 10:36:49 +0000717 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000718 bool Recover = false,
719 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000720 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000721 Recover(Recover || ClRecover),
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.
730 UseCtorComdat(UseGlobalsGC && ClWithComdat) {}
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000731
Craig Topper3e4c6972014-03-05 09:10:37 +0000732 bool runOnModule(Module &M) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000733 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000734
Mehdi Amini117296c2016-10-01 02:56:57 +0000735private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000736 void initializeCallbacks(Module &M);
737
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000738 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000739 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
740 ArrayRef<GlobalVariable *> ExtendedGlobals,
741 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000742 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
743 ArrayRef<GlobalVariable *> ExtendedGlobals,
744 ArrayRef<Constant *> MetadataInitializers,
745 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000746 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
747 ArrayRef<GlobalVariable *> ExtendedGlobals,
748 ArrayRef<Constant *> MetadataInitializers);
749 void
750 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
751 ArrayRef<GlobalVariable *> ExtendedGlobals,
752 ArrayRef<Constant *> MetadataInitializers);
753
754 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
755 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000756 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
757 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000758 IRBuilder<> CreateAsanModuleDtor(Module &M);
759
Kostya Serebryany20a79972012-11-22 03:18:50 +0000760 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000761 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000762 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000763 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000764 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000765 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000766 return RedzoneSizeForScale(Mapping.Scale);
767 }
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000768 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000769
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000770 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000771 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000772 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000773 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000774 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000775 Type *IntptrTy;
776 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000777 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000778 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000779 Function *AsanPoisonGlobals;
780 Function *AsanUnpoisonGlobals;
781 Function *AsanRegisterGlobals;
782 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000783 Function *AsanRegisterImageGlobals;
784 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000785 Function *AsanRegisterElfGlobals;
786 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000787
788 Function *AsanCtorFunction = nullptr;
789 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000790};
791
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000792// Stack poisoning does not play well with exception handling.
793// When an exception is thrown, we essentially bypass the code
794// that unpoisones the stack. This is why the run-time library has
795// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
796// stack in the interceptor. This however does not work inside the
797// actual function which catches the exception. Most likely because the
798// compiler hoists the load of the shadow value somewhere too high.
799// This causes asan to report a non-existing bug on 453.povray.
800// It sounds like an LLVM bug.
801struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
802 Function &F;
803 AddressSanitizer &ASan;
804 DIBuilder DIB;
805 LLVMContext *C;
806 Type *IntptrTy;
807 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000808 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000809
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000810 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000811 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000812 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000813 unsigned StackAlignment;
814
Kostya Serebryany6805de52013-09-10 13:16:56 +0000815 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000816 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000817 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000818 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000819 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000820
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000821 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
822 struct AllocaPoisonCall {
823 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000824 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000825 uint64_t Size;
826 bool DoPoison;
827 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000828 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
829 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000830
Yury Gribov98b18592015-05-28 07:51:49 +0000831 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
832 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
833 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000834 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000835
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000836 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000837 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000838 AllocaForValueMapTy AllocaForValue;
839
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000840 bool HasNonEmptyInlineAsm = false;
841 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000842 std::unique_ptr<CallInst> EmptyInlineAsm;
843
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000844 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000845 : F(F),
846 ASan(ASan),
847 DIB(*F.getParent(), /*AllowUnresolved*/ false),
848 C(ASan.C),
849 IntptrTy(ASan.IntptrTy),
850 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
851 Mapping(ASan.Mapping),
852 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000853 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000854
855 bool runOnFunction() {
856 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000857
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000858 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000859 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000860
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000861 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000862 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000863
Yury Gribov55441bb2014-11-21 10:29:50 +0000864 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000865
866 initializeCallbacks(*F.getParent());
867
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000868 processDynamicAllocas();
869 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000870
871 if (ClDebugStack) {
872 DEBUG(dbgs() << F);
873 }
874 return true;
875 }
876
Vitaly Buka74443f02017-07-18 22:28:03 +0000877 // Arguments marked with the "byval" attribute are implicitly copied without
878 // using an alloca instruction. To produce redzones for those arguments, we
879 // copy them a second time into memory allocated with an alloca instruction.
880 void copyArgsPassedByValToAllocas();
881
Yury Gribov55441bb2014-11-21 10:29:50 +0000882 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000883 // poisoned red zones around all of them.
884 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000885 void processStaticAllocas();
886 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000887
Yury Gribov98b18592015-05-28 07:51:49 +0000888 void createDynamicAllocasInitStorage();
889
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000890 // ----------------------- Visitors.
891 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000893
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000894 /// \brief Collect all Resume instructions.
895 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
896
897 /// \brief Collect all CatchReturnInst instructions.
898 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
899
Yury Gribov98b18592015-05-28 07:51:49 +0000900 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
901 Value *SavedStack) {
902 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000903 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
904 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
905 // need to adjust extracted SP to compute the address of the most recent
906 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
907 // this purpose.
908 if (!isa<ReturnInst>(InstBefore)) {
909 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
910 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
911 {IntptrTy});
912
913 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
914
915 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
916 DynamicAreaOffset);
917 }
918
Yury Gribov781bce22015-05-28 08:03:28 +0000919 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000920 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000921 }
922
Yury Gribov55441bb2014-11-21 10:29:50 +0000923 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000924 void unpoisonDynamicAllocas() {
925 for (auto &Ret : RetVec)
926 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000927
Yury Gribov98b18592015-05-28 07:51:49 +0000928 for (auto &StackRestoreInst : StackRestoreVec)
929 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
930 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000931 }
932
Yury Gribov55441bb2014-11-21 10:29:50 +0000933 // Deploy and poison redzones around dynamic alloca call. To do this, we
934 // should replace this call with another one with changed parameters and
935 // replace all its uses with new address, so
936 // addr = alloca type, old_size, align
937 // is replaced by
938 // new_size = (old_size + additional_size) * sizeof(type)
939 // tmp = alloca i8, new_size, max(align, 32)
940 // addr = tmp + 32 (first 32 bytes are for the left redzone).
941 // Additional_size is added to make new memory allocation contain not only
942 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000943 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000944
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000945 /// \brief Collect Alloca instructions we want (and can) handle.
946 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000947 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000948 if (AI.isStaticAlloca()) {
949 // Skip over allocas that are present *before* the first instrumented
950 // alloca, we don't want to move those around.
951 if (AllocaVec.empty())
952 return;
953
954 StaticAllocasToMoveUp.push_back(&AI);
955 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000956 return;
957 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000958
959 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000960 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000961 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000962 else
963 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000964 }
965
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000966 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
967 /// errors.
968 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000969 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000970 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000971 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000972 if (!ASan.UseAfterScope)
973 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000974 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000975 return;
976 // Found lifetime intrinsic, add ASan instrumentation if necessary.
977 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
978 // If size argument is undefined, don't do anything.
979 if (Size->isMinusOne()) return;
980 // Check that size doesn't saturate uint64_t and can
981 // be stored in IntptrTy.
982 const uint64_t SizeValue = Size->getValue().getLimitedValue();
983 if (SizeValue == ~0ULL ||
984 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
985 return;
986 // Find alloca instruction that corresponds to llvm.lifetime argument.
987 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000988 if (!AI || !ASan.isInterestingAlloca(*AI))
989 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000990 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000991 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000992 if (AI->isStaticAlloca())
993 StaticAllocaPoisonCallVec.push_back(APC);
994 else if (ClInstrumentDynamicAllocas)
995 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000996 }
997
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000998 void visitCallSite(CallSite CS) {
999 Instruction *I = CS.getInstruction();
1000 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00001001 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1002 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1003 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001004 HasReturnsTwiceCall |= CI->canReturnTwice();
1005 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001006 }
1007
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001008 // ---------------------- Helpers.
1009 void initializeCallbacks(Module &M);
1010
Yury Gribov3ae427d2014-12-01 08:47:58 +00001011 bool doesDominateAllExits(const Instruction *I) const {
1012 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001013 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001014 }
1015 return true;
1016 }
1017
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001018 /// Finds alloca where the value comes from.
1019 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001020
1021 // Copies bytes from ShadowBytes into shadow memory for indexes where
1022 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1023 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1024 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1025 IRBuilder<> &IRB, Value *ShadowBase);
1026 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1027 size_t Begin, size_t End, IRBuilder<> &IRB,
1028 Value *ShadowBase);
1029 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1030 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1031 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1032
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001033 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001034
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001035 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1036 bool Dynamic);
1037 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1038 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001039};
1040
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001041} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001042
1043char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001044
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001045INITIALIZE_PASS_BEGIN(
1046 AddressSanitizer, "asan",
1047 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1048 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001049INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001050INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001051INITIALIZE_PASS_END(
1052 AddressSanitizer, "asan",
1053 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1054 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001055
Yury Gribovd7731982015-11-11 10:36:49 +00001056FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001057 bool Recover,
1058 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001059 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001060 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001061}
1062
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001063char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001064
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001065INITIALIZE_PASS(
1066 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001067 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001068 "ModulePass",
1069 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001070
Yury Gribovd7731982015-11-11 10:36:49 +00001071ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001072 bool Recover,
1073 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +00001074 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001075 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001076}
1077
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001078static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001079 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001080 assert(Res < kNumberOfAccessSizes);
1081 return Res;
1082}
1083
Bill Wendling58f8cef2013-08-06 22:52:42 +00001084// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001085static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1086 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001087 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001088 // We use private linkage for module-local strings. If they can be merged
1089 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001090 GlobalVariable *GV =
1091 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001092 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001093 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +00001094 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1095 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001096}
1097
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001098/// \brief Create a global describing a source location.
1099static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1100 LocationMetadata MD) {
1101 Constant *LocData[] = {
1102 createPrivateGlobalForString(M, MD.Filename, true),
1103 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1104 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1105 };
1106 auto LocStruct = ConstantStruct::getAnon(LocData);
1107 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1108 GlobalValue::PrivateLinkage, LocStruct,
1109 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001110 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001111 return GV;
1112}
1113
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001114/// \brief Check if \p G has been created by a trusted compiler pass.
1115static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1116 // Do not instrument asan globals.
1117 if (G->getName().startswith(kAsanGenPrefix) ||
1118 G->getName().startswith(kSanCovGenPrefix) ||
1119 G->getName().startswith(kODRGenPrefix))
1120 return true;
1121
1122 // Do not instrument gcov counter arrays.
1123 if (G->getName() == "__llvm_gcov_ctr")
1124 return true;
1125
1126 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001127}
1128
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001129Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1130 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001131 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001132 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001133 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001134 Value *ShadowBase;
1135 if (LocalDynamicShadow)
1136 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001137 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001138 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1139 if (Mapping.OrShadowOffset)
1140 return IRB.CreateOr(Shadow, ShadowBase);
1141 else
1142 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001143}
1144
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001145// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001146void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1147 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001148 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001149 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001150 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001151 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1152 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1153 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001154 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001155 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001156 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001157 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1158 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1159 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001160 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001161 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001162}
1163
Anna Zaks8ed1d812015-02-27 03:12:36 +00001164/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001165bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001166 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1167
1168 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1169 return PreviouslySeenAllocaInfo->getSecond();
1170
Yury Gribov98b18592015-05-28 07:51:49 +00001171 bool IsInteresting =
1172 (AI.getAllocatedType()->isSized() &&
1173 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001174 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001175 // We are only interested in allocas not promotable to registers.
1176 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001177 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1178 // inalloca allocas are not treated as static, and we don't want
1179 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001180 !AI.isUsedWithInAlloca() &&
1181 // swifterror allocas are register promoted by ISel
1182 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001183
1184 ProcessedAllocas[&AI] = IsInteresting;
1185 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001186}
1187
Anna Zaks8ed1d812015-02-27 03:12:36 +00001188Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1189 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001190 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001191 unsigned *Alignment,
1192 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001193 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001194 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001195
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001196 // Do not instrument the load fetching the dynamic shadow address.
1197 if (LocalDynamicShadow == I)
1198 return nullptr;
1199
Anna Zaks8ed1d812015-02-27 03:12:36 +00001200 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001201 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001202 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001203 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001204 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001206 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001207 PtrOperand = LI->getPointerOperand();
1208 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001209 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001210 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001211 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001212 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001213 PtrOperand = SI->getPointerOperand();
1214 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001215 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001216 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001217 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001218 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001219 PtrOperand = RMW->getPointerOperand();
1220 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001221 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001222 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001223 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001224 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001225 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001226 } else if (auto CI = dyn_cast<CallInst>(I)) {
1227 auto *F = dyn_cast<Function>(CI->getCalledValue());
1228 if (F && (F->getName().startswith("llvm.masked.load.") ||
1229 F->getName().startswith("llvm.masked.store."))) {
1230 unsigned OpOffset = 0;
1231 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001232 if (!ClInstrumentWrites)
1233 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001234 // Masked store has an initial operand for the value.
1235 OpOffset = 1;
1236 *IsWrite = true;
1237 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001238 if (!ClInstrumentReads)
1239 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001240 *IsWrite = false;
1241 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001242
1243 auto BasePtr = CI->getOperand(0 + OpOffset);
1244 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1245 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1246 if (auto AlignmentConstant =
1247 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1248 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1249 else
1250 *Alignment = 1; // No alignment guarantees. We probably got Undef
1251 if (MaybeMask)
1252 *MaybeMask = CI->getOperand(2 + OpOffset);
1253 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001254 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001255 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001256
Anna Zaks644d9d32016-06-22 00:15:52 +00001257 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001258 // Do not instrument acesses from different address spaces; we cannot deal
1259 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001260 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1261 if (PtrTy->getPointerAddressSpace() != 0)
1262 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001263
1264 // Ignore swifterror addresses.
1265 // swifterror memory addresses are mem2reg promoted by instruction
1266 // selection. As such they cannot have regular uses like an instrumentation
1267 // function and it makes no sense to track them as memory.
1268 if (PtrOperand->isSwiftError())
1269 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001270 }
1271
Anna Zaks8ed1d812015-02-27 03:12:36 +00001272 // Treat memory accesses to promotable allocas as non-interesting since they
1273 // will not cause memory violations. This greatly speeds up the instrumented
1274 // executable at -O0.
1275 if (ClSkipPromotableAllocas)
1276 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1277 return isInterestingAlloca(*AI) ? AI : nullptr;
1278
1279 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001280}
1281
Kostya Serebryany796f6552014-02-27 12:45:36 +00001282static bool isPointerOperand(Value *V) {
1283 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1284}
1285
1286// This is a rough heuristic; it may cause both false positives and
1287// false negatives. The proper implementation requires cooperation with
1288// the frontend.
1289static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1290 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001291 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001292 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001293 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001294 } else {
1295 return false;
1296 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001297 return isPointerOperand(I->getOperand(0)) &&
1298 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001299}
1300
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001301bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1302 // If a global variable does not have dynamic initialization we don't
1303 // have to instrument it. However, if a global does not have initializer
1304 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001305 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001306}
1307
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001308void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1309 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001310 IRBuilder<> IRB(I);
1311 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1312 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001313 for (Value *&i : Param) {
1314 if (i->getType()->isPointerTy())
1315 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001316 }
David Blaikieff6409d2015-05-18 22:13:54 +00001317 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001318}
1319
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001320static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001321 Instruction *InsertBefore, Value *Addr,
1322 unsigned Alignment, unsigned Granularity,
1323 uint32_t TypeSize, bool IsWrite,
1324 Value *SizeArgument, bool UseCalls,
1325 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001326 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1327 // if the data is properly aligned.
1328 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1329 TypeSize == 128) &&
1330 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001331 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1332 nullptr, UseCalls, Exp);
1333 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1334 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001335}
1336
1337static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1338 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001339 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001340 Value *Addr, unsigned Alignment,
1341 unsigned Granularity, uint32_t TypeSize,
1342 bool IsWrite, Value *SizeArgument,
1343 bool UseCalls, uint32_t Exp) {
1344 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1345 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1346 unsigned Num = VTy->getVectorNumElements();
1347 auto Zero = ConstantInt::get(IntptrTy, 0);
1348 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001349 Value *InstrumentedAddress = nullptr;
1350 Instruction *InsertBefore = I;
1351 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1352 // dyn_cast as we might get UndefValue
1353 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001354 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001355 // Mask is constant false, so no instrumentation needed.
1356 continue;
1357 // If we have a true or undef value, fall through to doInstrumentAddress
1358 // with InsertBefore == I
1359 }
1360 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001361 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001362 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1363 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1364 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001365 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001366
1367 IRBuilder<> IRB(InsertBefore);
1368 InstrumentedAddress =
1369 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1370 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1371 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1372 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001373 }
1374}
1375
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001376void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001377 Instruction *I, bool UseCalls,
1378 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001379 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001380 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001381 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001382 Value *MaybeMask = nullptr;
1383 Value *Addr =
1384 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001385 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001386
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001387 // Optimization experiments.
1388 // The experiments can be used to evaluate potential optimizations that remove
1389 // instrumentation (assess false negatives). Instead of completely removing
1390 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1391 // experiments that want to remove instrumentation of this instruction).
1392 // If Exp is non-zero, this pass will emit special calls into runtime
1393 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1394 // make runtime terminate the program in a special way (with a different
1395 // exit status). Then you run the new compiler on a buggy corpus, collect
1396 // the special terminations (ideally, you don't see them at all -- no false
1397 // negatives) and make the decision on the optimization.
1398 uint32_t Exp = ClForceExperiment;
1399
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001400 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001401 // If initialization order checking is disabled, a simple access to a
1402 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001403 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001404 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001405 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1406 NumOptimizedAccessesToGlobalVar++;
1407 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001408 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001409 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001410
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001411 if (ClOpt && ClOptStack) {
1412 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001413 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001414 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1415 NumOptimizedAccessesToStackVar++;
1416 return;
1417 }
1418 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001419
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001420 if (IsWrite)
1421 NumInstrumentedWrites++;
1422 else
1423 NumInstrumentedReads++;
1424
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001425 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001426 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001427 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1428 Alignment, Granularity, TypeSize, IsWrite,
1429 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001430 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001431 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001432 IsWrite, nullptr, UseCalls, Exp);
1433 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001434}
1435
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001436Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1437 Value *Addr, bool IsWrite,
1438 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001439 Value *SizeArgument,
1440 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001441 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001442 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1443 CallInst *Call = nullptr;
1444 if (SizeArgument) {
1445 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001446 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1447 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001448 else
David Blaikieff6409d2015-05-18 22:13:54 +00001449 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1450 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001451 } else {
1452 if (Exp == 0)
1453 Call =
1454 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1455 else
David Blaikieff6409d2015-05-18 22:13:54 +00001456 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1457 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001458 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001459
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001460 // We don't do Call->setDoesNotReturn() because the BB already has
1461 // UnreachableInst at the end.
1462 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001463 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001464 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001465}
1466
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001467Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001468 Value *ShadowValue,
1469 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001470 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001471 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001472 Value *LastAccessedByte =
1473 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001474 // (Addr & (Granularity - 1)) + size - 1
1475 if (TypeSize / 8 > 1)
1476 LastAccessedByte = IRB.CreateAdd(
1477 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1478 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001479 LastAccessedByte =
1480 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001481 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1482 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1483}
1484
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001485void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001486 Instruction *InsertBefore, Value *Addr,
1487 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001488 Value *SizeArgument, bool UseCalls,
1489 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001490 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001491 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001492 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1493
1494 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001495 if (Exp == 0)
1496 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1497 AddrLong);
1498 else
David Blaikieff6409d2015-05-18 22:13:54 +00001499 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1500 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001501 return;
1502 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001503
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001504 Type *ShadowTy =
1505 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001506 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1507 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1508 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001509 Value *ShadowValue =
1510 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001511
1512 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001513 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001514 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001515
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001516 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001517 // We use branch weights for the slow path check, to indicate that the slow
1518 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001519 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1520 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001521 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001522 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001523 IRB.SetInsertPoint(CheckTerm);
1524 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001525 if (Recover) {
1526 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1527 } else {
1528 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001529 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001530 CrashTerm = new UnreachableInst(*C, CrashBlock);
1531 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1532 ReplaceInstWithInst(CheckTerm, NewTerm);
1533 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001534 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001535 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001536 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001537
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001538 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001539 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001540 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001541}
1542
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001543// Instrument unusual size or unusual alignment.
1544// We can not do it with a single check, so we do 1-byte check for the first
1545// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1546// to report the actual access size.
1547void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001548 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1549 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1550 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001551 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1552 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1553 if (UseCalls) {
1554 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001555 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1556 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001557 else
David Blaikieff6409d2015-05-18 22:13:54 +00001558 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1559 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001560 } else {
1561 Value *LastByte = IRB.CreateIntToPtr(
1562 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1563 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001564 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1565 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001566 }
1567}
1568
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001569void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1570 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001571 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001572 IRBuilder<> IRB(&GlobalInit.front(),
1573 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001574
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001575 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001576 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1577 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001578
1579 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001580 for (auto &BB : GlobalInit.getBasicBlockList())
1581 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001582 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001583}
1584
1585void AddressSanitizerModule::createInitializerPoisonCalls(
1586 Module &M, GlobalValue *ModuleName) {
1587 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001588 if (!GV)
1589 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001590
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001591 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1592 if (!CA)
1593 return;
1594
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001595 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001596 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001597 ConstantStruct *CS = cast<ConstantStruct>(OP);
1598
1599 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001600 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001601 if (F->getName() == kAsanModuleCtorName) continue;
1602 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1603 // Don't instrument CTORs that will run before asan.module_ctor.
1604 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1605 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001606 }
1607 }
1608}
1609
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001610bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001611 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001612 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001613
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001614 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001615 if (!Ty->isSized()) return false;
1616 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001617 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001618 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001619 // Don't handle ODR linkage types and COMDATs since other modules may be built
1620 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001621 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1622 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1623 G->getLinkage() != GlobalVariable::InternalLinkage)
1624 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001625 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001626 // Two problems with thread-locals:
1627 // - The address of the main thread's copy can't be computed at link-time.
1628 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001629 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001630 // For now, just ignore this Global if the alignment is large.
1631 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001632
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001633 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001634 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001635
Anna Zaks11904602015-06-09 00:58:08 +00001636 // Globals from llvm.metadata aren't emitted, do not instrument them.
1637 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001638 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001639 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001640
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001641 // Do not instrument function pointers to initialization and termination
1642 // routines: dynamic linker will not properly handle redzones.
1643 if (Section.startswith(".preinit_array") ||
1644 Section.startswith(".init_array") ||
1645 Section.startswith(".fini_array")) {
1646 return false;
1647 }
1648
Anna Zaks11904602015-06-09 00:58:08 +00001649 // Callbacks put into the CRT initializer/terminator sections
1650 // should not be instrumented.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001651 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001652 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1653 if (Section.startswith(".CRT")) {
1654 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1655 return false;
1656 }
1657
Kuba Brecka1001bb52014-12-05 22:19:18 +00001658 if (TargetTriple.isOSBinFormatMachO()) {
1659 StringRef ParsedSegment, ParsedSection;
1660 unsigned TAA = 0, StubSize = 0;
1661 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001662 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1663 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001664 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001665
1666 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1667 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1668 // them.
1669 if (ParsedSegment == "__OBJC" ||
1670 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1671 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1672 return false;
1673 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001674 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001675 // Constant CFString instances are compiled in the following way:
1676 // -- the string buffer is emitted into
1677 // __TEXT,__cstring,cstring_literals
1678 // -- the constant NSConstantString structure referencing that buffer
1679 // is placed into __DATA,__cfstring
1680 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1681 // Moreover, it causes the linker to crash on OS X 10.7
1682 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1683 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1684 return false;
1685 }
1686 // The linker merges the contents of cstring_literals and removes the
1687 // trailing zeroes.
1688 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1689 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1690 return false;
1691 }
1692 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001693 }
1694
1695 return true;
1696}
1697
Ryan Govostes653f9d02016-03-28 20:28:57 +00001698// On Mach-O platforms, we emit global metadata in a separate section of the
1699// binary in order to allow the linker to properly dead strip. This is only
1700// supported on recent versions of ld64.
1701bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1702 if (!TargetTriple.isOSBinFormatMachO())
1703 return false;
1704
1705 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1706 return true;
1707 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001708 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001709 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1710 return true;
1711
1712 return false;
1713}
1714
Reid Kleckner01660a32016-11-21 20:40:37 +00001715StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1716 switch (TargetTriple.getObjectFormat()) {
1717 case Triple::COFF: return ".ASAN$GL";
1718 case Triple::ELF: return "asan_globals";
1719 case Triple::MachO: return "__DATA,__asan_globals,regular";
1720 default: break;
1721 }
1722 llvm_unreachable("unsupported object format");
1723}
1724
Alexey Samsonov788381b2012-12-25 12:28:20 +00001725void AddressSanitizerModule::initializeCallbacks(Module &M) {
1726 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001727
Alexey Samsonov788381b2012-12-25 12:28:20 +00001728 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001729 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001730 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001731 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001732 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001733 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001734 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001735
Alexey Samsonov788381b2012-12-25 12:28:20 +00001736 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001737 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001738 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001739 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001740 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1741 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001742 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001743 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001744
1745 // Declare the functions that find globals in a shared object and then invoke
1746 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001747 AsanRegisterImageGlobals =
1748 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001749 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001750 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001751
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001752 AsanUnregisterImageGlobals =
1753 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001754 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001755 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001756
1757 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1758 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1759 IntptrTy, IntptrTy, IntptrTy));
1760 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1761
1762 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1763 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1764 IntptrTy, IntptrTy, IntptrTy));
1765 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001766}
1767
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001768// Put the metadata and the instrumented global in the same group. This ensures
1769// that the metadata is discarded if the instrumented global is discarded.
1770void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001771 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001772 Module &M = *G->getParent();
1773 Comdat *C = G->getComdat();
1774 if (!C) {
1775 if (!G->hasName()) {
1776 // If G is unnamed, it must be internal. Give it an artificial name
1777 // so we can put it in a comdat.
1778 assert(G->hasLocalLinkage());
1779 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1780 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001781
1782 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1783 std::string Name = G->getName();
1784 Name += InternalSuffix;
1785 C = M.getOrInsertComdat(Name);
1786 } else {
1787 C = M.getOrInsertComdat(G->getName());
1788 }
1789
Reid Klecknerc212cc82017-10-31 16:16:08 +00001790 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1791 // linkage to internal linkage so that a symbol table entry is emitted. This
1792 // is necessary in order to create the comdat group.
1793 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001794 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001795 if (G->hasPrivateLinkage())
1796 G->setLinkage(GlobalValue::InternalLinkage);
1797 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001798 G->setComdat(C);
1799 }
1800
1801 assert(G->hasComdat());
1802 Metadata->setComdat(G->getComdat());
1803}
1804
1805// Create a separate metadata global and put it in the appropriate ASan
1806// global registration section.
1807GlobalVariable *
1808AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1809 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001810 auto Linkage = TargetTriple.isOSBinFormatMachO()
1811 ? GlobalVariable::InternalLinkage
1812 : GlobalVariable::PrivateLinkage;
1813 GlobalVariable *Metadata = new GlobalVariable(
1814 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001815 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001816 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001817 return Metadata;
1818}
1819
1820IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001821 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001822 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1823 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1824 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001825
1826 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1827}
1828
1829void AddressSanitizerModule::InstrumentGlobalsCOFF(
1830 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1831 ArrayRef<Constant *> MetadataInitializers) {
1832 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001833 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001834
1835 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001836 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001837 GlobalVariable *G = ExtendedGlobals[i];
1838 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001839 CreateMetadataGlobal(M, Initializer, G->getName());
1840
1841 // The MSVC linker always inserts padding when linking incrementally. We
1842 // cope with that by aligning each struct to its size, which must be a power
1843 // of two.
1844 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1845 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1846 "global metadata will not be padded appropriately");
1847 Metadata->setAlignment(SizeOfGlobalStruct);
1848
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001849 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001850 }
1851}
1852
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001853void AddressSanitizerModule::InstrumentGlobalsELF(
1854 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1855 ArrayRef<Constant *> MetadataInitializers,
1856 const std::string &UniqueModuleId) {
1857 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1858
1859 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1860 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1861 GlobalVariable *G = ExtendedGlobals[i];
1862 GlobalVariable *Metadata =
1863 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1864 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1865 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1866 MetadataGlobals[i] = Metadata;
1867
1868 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1869 }
1870
1871 // Update llvm.compiler.used, adding the new metadata globals. This is
1872 // needed so that during LTO these variables stay alive.
1873 if (!MetadataGlobals.empty())
1874 appendToCompilerUsed(M, MetadataGlobals);
1875
1876 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1877 // to look up the loaded image that contains it. Second, we can store in it
1878 // whether registration has already occurred, to prevent duplicate
1879 // registration.
1880 //
1881 // Common linkage ensures that there is only one global per shared library.
1882 GlobalVariable *RegisteredFlag = new GlobalVariable(
1883 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1884 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1885 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1886
1887 // Create start and stop symbols.
1888 GlobalVariable *StartELFMetadata = new GlobalVariable(
1889 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1890 "__start_" + getGlobalMetadataSection());
1891 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1892 GlobalVariable *StopELFMetadata = new GlobalVariable(
1893 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1894 "__stop_" + getGlobalMetadataSection());
1895 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1896
1897 // Create a call to register the globals with the runtime.
1898 IRB.CreateCall(AsanRegisterElfGlobals,
1899 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1900 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1901 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1902
1903 // We also need to unregister globals at the end, e.g., when a shared library
1904 // gets closed.
1905 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1906 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1907 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1908 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1909 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1910}
1911
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001912void AddressSanitizerModule::InstrumentGlobalsMachO(
1913 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1914 ArrayRef<Constant *> MetadataInitializers) {
1915 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1916
1917 // On recent Mach-O platforms, use a structure which binds the liveness of
1918 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1919 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001920 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001921 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1922
1923 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1924 Constant *Initializer = MetadataInitializers[i];
1925 GlobalVariable *G = ExtendedGlobals[i];
1926 GlobalVariable *Metadata =
1927 CreateMetadataGlobal(M, Initializer, G->getName());
1928
1929 // On recent Mach-O platforms, we emit the global metadata in a way that
1930 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001931 auto LivenessBinder =
1932 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1933 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001934 GlobalVariable *Liveness = new GlobalVariable(
1935 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1936 Twine("__asan_binder_") + G->getName());
1937 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1938 LivenessGlobals[i] = Liveness;
1939 }
1940
1941 // Update llvm.compiler.used, adding the new liveness globals. This is
1942 // needed so that during LTO these variables stay alive. The alternative
1943 // would be to have the linker handling the LTO symbols, but libLTO
1944 // current API does not expose access to the section for each symbol.
1945 if (!LivenessGlobals.empty())
1946 appendToCompilerUsed(M, LivenessGlobals);
1947
1948 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1949 // to look up the loaded image that contains it. Second, we can store in it
1950 // whether registration has already occurred, to prevent duplicate
1951 // registration.
1952 //
1953 // common linkage ensures that there is only one global per shared library.
1954 GlobalVariable *RegisteredFlag = new GlobalVariable(
1955 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1956 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1957 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1958
1959 IRB.CreateCall(AsanRegisterImageGlobals,
1960 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1961
1962 // We also need to unregister globals at the end, e.g., when a shared library
1963 // gets closed.
1964 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1965 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1966 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1967}
1968
1969void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1970 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1971 ArrayRef<Constant *> MetadataInitializers) {
1972 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1973 unsigned N = ExtendedGlobals.size();
1974 assert(N > 0);
1975
1976 // On platforms that don't have a custom metadata section, we emit an array
1977 // of global metadata structures.
1978 ArrayType *ArrayOfGlobalStructTy =
1979 ArrayType::get(MetadataInitializers[0]->getType(), N);
1980 auto AllGlobals = new GlobalVariable(
1981 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1982 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00001983 if (Mapping.Scale > 3)
1984 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001985
1986 IRB.CreateCall(AsanRegisterGlobals,
1987 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1988 ConstantInt::get(IntptrTy, N)});
1989
1990 // We also need to unregister globals at the end, e.g., when a shared library
1991 // gets closed.
1992 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1993 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1994 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1995 ConstantInt::get(IntptrTy, N)});
1996}
1997
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001998// This function replaces all global variables with new variables that have
1999// trailing redzones. It also creates a function that poisons
2000// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002001// Sets *CtorComdat to true if the global registration code emitted into the
2002// asan constructor is comdat-compatible.
2003bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2004 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002005 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002006
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002007 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2008
Alexey Samsonova02e6642014-05-29 18:40:48 +00002009 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002010 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002011 }
2012
2013 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002014 if (n == 0) {
2015 *CtorComdat = true;
2016 return false;
2017 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002018
Reid Kleckner78565832016-11-29 01:32:21 +00002019 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002020
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002021 // A global is described by a structure
2022 // size_t beg;
2023 // size_t size;
2024 // size_t size_with_redzone;
2025 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002026 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002027 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002028 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002029 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002030 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002031 StructType *GlobalStructTy =
2032 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002033 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002034 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2035 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002036
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002037 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002038
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002039 // We shouldn't merge same module names, as this string serves as unique
2040 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002041 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002042 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002043
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002044 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002045 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002046 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002047
2048 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002049 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002050 // Create string holding the global name (use global name from metadata
2051 // if it's available, otherwise just write the name of global variable).
2052 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002053 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002054 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002055
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002056 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002057 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002058 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002059 // MinRZ <= RZ <= kMaxGlobalRedzone
2060 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002061 uint64_t RZ = std::max(
2062 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002063 uint64_t RightRedzoneSize = RZ;
2064 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002065 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002066 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002067 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2068
Serge Gueltone38003f2017-05-09 19:31:13 +00002069 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2070 Constant *NewInitializer = ConstantStruct::get(
2071 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002072
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002073 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002074 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2075 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2076 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002077 GlobalVariable *NewGlobal =
2078 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2079 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002080 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002081 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002082
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002083 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2084 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2085 G->isConstant()) {
2086 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2087 if (Seq && Seq->isCString())
2088 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2089 }
2090
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002091 // Transfer the debug info. The payload starts at offset zero so we can
2092 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002093 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002094 G->getDebugInfo(GVs);
2095 for (auto *GV : GVs)
2096 NewGlobal->addDebugInfo(GV);
2097
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002098 Value *Indices2[2];
2099 Indices2[0] = IRB.getInt32(0);
2100 Indices2[1] = IRB.getInt32(0);
2101
2102 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002103 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002104 NewGlobal->takeName(G);
2105 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002106 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002107
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002108 Constant *SourceLoc;
2109 if (!MD.SourceLoc.empty()) {
2110 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2111 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2112 } else {
2113 SourceLoc = ConstantInt::get(IntptrTy, 0);
2114 }
2115
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002116 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2117 GlobalValue *InstrumentedGlobal = NewGlobal;
2118
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002119 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002120 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2121 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002122 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2123 // Create local alias for NewGlobal to avoid crash on ODR between
2124 // instrumented and non-instrumented libraries.
2125 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2126 NameForGlobal + M.getName(), NewGlobal);
2127
2128 // With local aliases, we need to provide another externally visible
2129 // symbol __odr_asan_XXX to detect ODR violation.
2130 auto *ODRIndicatorSym =
2131 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2132 Constant::getNullValue(IRB.getInt8Ty()),
2133 kODRGenPrefix + NameForGlobal, nullptr,
2134 NewGlobal->getThreadLocalMode());
2135
2136 // Set meaningful attributes for indicator symbol.
2137 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2138 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2139 ODRIndicatorSym->setAlignment(1);
2140 ODRIndicator = ODRIndicatorSym;
2141 InstrumentedGlobal = GA;
2142 }
2143
Reid Kleckner01660a32016-11-21 20:40:37 +00002144 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002145 GlobalStructTy,
2146 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002147 ConstantInt::get(IntptrTy, SizeInBytes),
2148 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2149 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002150 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002151 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002152 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002153
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002154 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002155
Kostya Serebryany20343352012-10-17 13:40:06 +00002156 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002157
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002158 Initializers[i] = Initializer;
2159 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002160
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002161 std::string ELFUniqueModuleId =
2162 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2163 : "";
2164
2165 if (!ELFUniqueModuleId.empty()) {
2166 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2167 *CtorComdat = true;
2168 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002169 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002170 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002171 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2172 } else {
2173 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002174 }
2175
Reid Kleckner01660a32016-11-21 20:40:37 +00002176 // Create calls for poisoning before initializers run and unpoisoning after.
2177 if (HasDynamicallyInitializedGlobals)
2178 createInitializerPoisonCalls(M, ModuleName);
2179
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002180 DEBUG(dbgs() << M);
2181 return true;
2182}
2183
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002184int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2185 int LongSize = M.getDataLayout().getPointerSizeInBits();
2186 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2187 int Version = 8;
2188 // 32-bit Android is one version ahead because of the switch to dynamic
2189 // shadow.
2190 Version += (LongSize == 32 && isAndroid);
2191 return Version;
2192}
2193
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002194bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002195 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002196 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002197 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002198 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002199 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002200 initializeCallbacks(M);
2201
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002202 if (CompileKernel)
2203 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002204
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002205 // Create a module constructor. A destructor is created lazily because not all
2206 // platforms, and not all modules need it.
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002207 std::string VersionCheckName =
2208 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002209 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2210 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002211 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002212
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002213 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002214 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002215 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002216 if (ClGlobals) {
2217 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002218 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2219 }
2220
2221 // Put the constructor and destructor in comdat if both
2222 // (1) global instrumentation is not TU-specific
2223 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002224 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002225 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2226 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2227 AsanCtorFunction);
2228 if (AsanDtorFunction) {
2229 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2230 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2231 AsanDtorFunction);
2232 }
2233 } else {
2234 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2235 if (AsanDtorFunction)
2236 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002237 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002238
2239 return Changed;
2240}
2241
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002242void AddressSanitizer::initializeCallbacks(Module &M) {
2243 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002244 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002245 // IsWrite, TypeSize and Exp are encoded in the function name.
2246 for (int Exp = 0; Exp < 2; Exp++) {
2247 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2248 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2249 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002250 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002251 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002252
2253 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2254 SmallVector<Type *, 2> Args1{1, IntptrTy};
2255 if (Exp) {
2256 Type *ExpType = Type::getInt32Ty(*C);
2257 Args2.push_back(ExpType);
2258 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002259 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002260 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2261 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2262 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2263 EndingStr,
2264 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002265
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002266 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2267 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2268 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2269 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002270
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002271 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2272 AccessSizeIndex++) {
2273 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2274 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2275 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2276 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2277 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002278
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002279 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2280 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2281 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2282 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2283 }
2284 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002285 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002286
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002287 const std::string MemIntrinCallbackPrefix =
2288 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002289 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002290 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002291 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002292 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002293 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002294 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002295 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002296 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002297 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002298
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002299 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002300 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002301
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002302 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002303 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002304 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002305 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002306 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2307 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2308 StringRef(""), StringRef(""),
2309 /*hasSideEffects=*/true);
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002310 if (Mapping.InGlobal)
2311 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2312 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002313}
2314
2315// virtual
2316bool AddressSanitizer::doInitialization(Module &M) {
2317 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002318 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002319
2320 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002321 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002322 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002323 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002324
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002325 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002326 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002327}
2328
Keno Fischere03fae42015-12-05 14:42:34 +00002329bool AddressSanitizer::doFinalization(Module &M) {
2330 GlobalsMD.reset();
2331 return false;
2332}
2333
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002334bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2335 // For each NSObject descendant having a +load method, this method is invoked
2336 // by the ObjC runtime before any of the static constructors is called.
2337 // Therefore we need to instrument such methods with a call to __asan_init
2338 // at the beginning in order to initialize our runtime before any access to
2339 // the shadow memory.
2340 // We cannot just ignore these methods, because they may call other
2341 // instrumented functions.
2342 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002343 Function *AsanInitFunction =
2344 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002345 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002346 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002347 return true;
2348 }
2349 return false;
2350}
2351
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002352void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2353 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002354 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002355 return;
2356
2357 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002358 if (Mapping.InGlobal) {
2359 if (ClWithIfuncSuppressRemat) {
2360 // An empty inline asm with input reg == output reg.
2361 // An opaque pointer-to-int cast, basically.
2362 InlineAsm *Asm = InlineAsm::get(
2363 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2364 StringRef(""), StringRef("=r,0"),
2365 /*hasSideEffects=*/false);
2366 LocalDynamicShadow =
2367 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2368 } else {
2369 LocalDynamicShadow =
2370 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2371 }
2372 } else {
2373 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2374 kAsanShadowMemoryDynamicAddress, IntptrTy);
2375 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2376 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002377}
2378
Reid Kleckner2f907552015-07-21 17:40:14 +00002379void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2380 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2381 // to it as uninteresting. This assumes we haven't started processing allocas
2382 // yet. This check is done up front because iterating the use list in
2383 // isInterestingAlloca would be algorithmically slower.
2384 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2385
2386 // Try to get the declaration of llvm.localescape. If it's not in the module,
2387 // we can exit early.
2388 if (!F.getParent()->getFunction("llvm.localescape")) return;
2389
2390 // Look for a call to llvm.localescape call in the entry block. It can't be in
2391 // any other block.
2392 for (Instruction &I : F.getEntryBlock()) {
2393 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2394 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2395 // We found a call. Mark all the allocas passed in as uninteresting.
2396 for (Value *Arg : II->arg_operands()) {
2397 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2398 assert(AI && AI->isStaticAlloca() &&
2399 "non-static alloca arg to localescape");
2400 ProcessedAllocas[AI] = false;
2401 }
2402 break;
2403 }
2404 }
2405}
2406
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002407bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002408 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002409 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002410 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002411
Etienne Bergeron78582b22016-09-15 15:45:05 +00002412 bool FunctionModified = false;
2413
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002414 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002415 // This function needs to be called even if the function body is not
2416 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002417 if (maybeInsertAsanInitAtFunctionEntry(F))
2418 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002419
2420 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002421 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002422
Etienne Bergeron752f8832016-09-14 17:18:37 +00002423 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2424
2425 initializeCallbacks(*F.getParent());
2426 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002427
Reid Kleckner2f907552015-07-21 17:40:14 +00002428 FunctionStateRAII CleanupObj(this);
2429
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002430 maybeInsertDynamicShadowAtFunctionEntry(F);
2431
Reid Kleckner2f907552015-07-21 17:40:14 +00002432 // We can't instrument allocas used with llvm.localescape. Only static allocas
2433 // can be passed to that intrinsic.
2434 markEscapedLocalAllocas(F);
2435
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002436 // We want to instrument every address only once per basic block (unless there
2437 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002438 SmallSet<Value *, 16> TempsToInstrument;
2439 SmallVector<Instruction *, 16> ToInstrument;
2440 SmallVector<Instruction *, 8> NoReturnCalls;
2441 SmallVector<BasicBlock *, 16> AllBlocks;
2442 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002443 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002444 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002445 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002446 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002447 const TargetLibraryInfo *TLI =
2448 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002449
2450 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002451 for (auto &BB : F) {
2452 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002453 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002454 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002455 for (auto &Inst : BB) {
2456 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002457 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002458 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002459 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002460 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002461 // If we have a mask, skip instrumentation if we've already
2462 // instrumented the full object. But don't add to TempsToInstrument
2463 // because we might get another load/store with a different mask.
2464 if (MaybeMask) {
2465 if (TempsToInstrument.count(Addr))
2466 continue; // We've seen this (whole) temp in the current BB.
2467 } else {
2468 if (!TempsToInstrument.insert(Addr).second)
2469 continue; // We've seen this temp in the current BB.
2470 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002471 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002472 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002473 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2474 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002475 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002476 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002477 // ok, take it.
2478 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002479 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002480 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002481 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002482 // A call inside BB.
2483 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002484 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002485 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002486 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2487 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002488 continue;
2489 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002490 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002491 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002492 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002493 }
2494 }
2495
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002496 bool UseCalls =
2497 CompileKernel ||
2498 (ClInstrumentationWithCallsThreshold >= 0 &&
2499 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002500 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002501 ObjectSizeOpts ObjSizeOpts;
2502 ObjSizeOpts.RoundToAlign = true;
2503 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002504
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002505 // Instrument.
2506 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002507 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002508 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2509 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002510 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002511 instrumentMop(ObjSizeVis, Inst, UseCalls,
2512 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002513 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002514 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002515 }
2516 NumInstrumented++;
2517 }
2518
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002519 FunctionStackPoisoner FSP(F, *this);
2520 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002521
2522 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002523 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002524 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002525 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002526 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002527 }
2528
Alexey Samsonova02e6642014-05-29 18:40:48 +00002529 for (auto Inst : PointerComparisonsOrSubtracts) {
2530 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002531 NumInstrumented++;
2532 }
2533
Etienne Bergeron78582b22016-09-15 15:45:05 +00002534 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2535 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002536
Etienne Bergeron78582b22016-09-15 15:45:05 +00002537 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2538 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002539
Etienne Bergeron78582b22016-09-15 15:45:05 +00002540 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002541}
2542
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002543// Workaround for bug 11395: we don't want to instrument stack in functions
2544// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2545// FIXME: remove once the bug 11395 is fixed.
2546bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2547 if (LongSize != 32) return false;
2548 CallInst *CI = dyn_cast<CallInst>(I);
2549 if (!CI || !CI->isInlineAsm()) return false;
2550 if (CI->getNumArgOperands() <= 5) return false;
2551 // We have inline assembly with quite a few arguments.
2552 return true;
2553}
2554
2555void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2556 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002557 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2558 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002559 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2560 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002561 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002562 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002563 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002564 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002565 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002566 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002567 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2568 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002569 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002570 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2571 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002572 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002573 }
2574
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002575 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2576 std::ostringstream Name;
2577 Name << kAsanSetShadowPrefix;
2578 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002579 AsanSetShadowFunc[Val] =
2580 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002581 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002582 }
2583
Yury Gribov98b18592015-05-28 07:51:49 +00002584 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002585 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002586 AsanAllocasUnpoisonFunc =
2587 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002588 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002589}
2590
Vitaly Buka793913c2016-08-29 18:17:21 +00002591void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2592 ArrayRef<uint8_t> ShadowBytes,
2593 size_t Begin, size_t End,
2594 IRBuilder<> &IRB,
2595 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002596 if (Begin >= End)
2597 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002598
2599 const size_t LargestStoreSizeInBytes =
2600 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2601
2602 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2603
2604 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002605 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2606 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2607 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002608 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002609 if (!ShadowMask[i]) {
2610 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002611 ++i;
2612 continue;
2613 }
2614
2615 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2616 // Fit store size into the range.
2617 while (StoreSizeInBytes > End - i)
2618 StoreSizeInBytes /= 2;
2619
2620 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002621 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002622 while (j <= StoreSizeInBytes / 2)
2623 StoreSizeInBytes /= 2;
2624 }
2625
2626 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002627 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2628 if (IsLittleEndian)
2629 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2630 else
2631 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002632 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002633
2634 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2635 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002636 IRB.CreateAlignedStore(
2637 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002638
2639 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002640 }
2641}
2642
Vitaly Buka793913c2016-08-29 18:17:21 +00002643void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2644 ArrayRef<uint8_t> ShadowBytes,
2645 IRBuilder<> &IRB, Value *ShadowBase) {
2646 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2647}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002648
Vitaly Buka793913c2016-08-29 18:17:21 +00002649void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2650 ArrayRef<uint8_t> ShadowBytes,
2651 size_t Begin, size_t End,
2652 IRBuilder<> &IRB, Value *ShadowBase) {
2653 assert(ShadowMask.size() == ShadowBytes.size());
2654 size_t Done = Begin;
2655 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2656 if (!ShadowMask[i]) {
2657 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002658 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002659 }
2660 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002661 if (!AsanSetShadowFunc[Val])
2662 continue;
2663
2664 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002665 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002666 }
2667
2668 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002669 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002670 IRB.CreateCall(AsanSetShadowFunc[Val],
2671 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2672 ConstantInt::get(IntptrTy, j - i)});
2673 Done = j;
2674 }
2675 }
2676
Vitaly Buka793913c2016-08-29 18:17:21 +00002677 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002678}
2679
Kostya Serebryany6805de52013-09-10 13:16:56 +00002680// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2681// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2682static int StackMallocSizeClass(uint64_t LocalStackSize) {
2683 assert(LocalStackSize <= kMaxStackMallocSize);
2684 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002685 for (int i = 0;; i++, MaxSize *= 2)
2686 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002687 llvm_unreachable("impossible LocalStackSize");
2688}
2689
Vitaly Buka74443f02017-07-18 22:28:03 +00002690void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002691 Instruction *CopyInsertPoint = &F.front().front();
2692 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2693 // Insert after the dynamic shadow location is determined
2694 CopyInsertPoint = CopyInsertPoint->getNextNode();
2695 assert(CopyInsertPoint);
2696 }
2697 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002698 const DataLayout &DL = F.getParent()->getDataLayout();
2699 for (Argument &Arg : F.args()) {
2700 if (Arg.hasByValAttr()) {
2701 Type *Ty = Arg.getType()->getPointerElementType();
2702 unsigned Align = Arg.getParamAlignment();
2703 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2704
2705 const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2706 "Arg" + llvm::to_string(Arg.getArgNo());
2707 AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2708 AI->setAlignment(Align);
2709 Arg.replaceAllUsesWith(AI);
2710
2711 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2712 IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2713 }
2714 }
2715}
2716
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002717PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2718 Value *ValueIfTrue,
2719 Instruction *ThenTerm,
2720 Value *ValueIfFalse) {
2721 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2722 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2723 PHI->addIncoming(ValueIfFalse, CondBlock);
2724 BasicBlock *ThenBlock = ThenTerm->getParent();
2725 PHI->addIncoming(ValueIfTrue, ThenBlock);
2726 return PHI;
2727}
2728
2729Value *FunctionStackPoisoner::createAllocaForLayout(
2730 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2731 AllocaInst *Alloca;
2732 if (Dynamic) {
2733 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2734 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2735 "MyAlloca");
2736 } else {
2737 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2738 nullptr, "MyAlloca");
2739 assert(Alloca->isStaticAlloca());
2740 }
2741 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2742 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2743 Alloca->setAlignment(FrameAlignment);
2744 return IRB.CreatePointerCast(Alloca, IntptrTy);
2745}
2746
Yury Gribov98b18592015-05-28 07:51:49 +00002747void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2748 BasicBlock &FirstBB = *F.begin();
2749 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2750 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2751 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2752 DynamicAllocaLayout->setAlignment(32);
2753}
2754
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002755void FunctionStackPoisoner::processDynamicAllocas() {
2756 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2757 assert(DynamicAllocaPoisonCallVec.empty());
2758 return;
2759 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002760
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002761 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2762 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002763 assert(APC.InsBefore);
2764 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002765 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002766 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002767
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002768 IRBuilder<> IRB(APC.InsBefore);
2769 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002770 // Dynamic allocas will be unpoisoned unconditionally below in
2771 // unpoisonDynamicAllocas.
2772 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002773 }
2774
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002775 // Handle dynamic allocas.
2776 createDynamicAllocasInitStorage();
2777 for (auto &AI : DynamicAllocaVec)
2778 handleDynamicAllocaCall(AI);
2779 unpoisonDynamicAllocas();
2780}
Yury Gribov98b18592015-05-28 07:51:49 +00002781
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002782void FunctionStackPoisoner::processStaticAllocas() {
2783 if (AllocaVec.empty()) {
2784 assert(StaticAllocaPoisonCallVec.empty());
2785 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002786 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002787
Kostya Serebryany6805de52013-09-10 13:16:56 +00002788 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002789 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002790 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002791 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002792
2793 Instruction *InsBefore = AllocaVec[0];
2794 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002795 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002796
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002797 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2798 // debug info is broken, because only entry-block allocas are treated as
2799 // regular stack slots.
2800 auto InsBeforeB = InsBefore->getParent();
2801 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002802 for (auto *AI : StaticAllocasToMoveUp)
2803 if (AI->getParent() == InsBeforeB)
2804 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002805
Reid Kleckner2f907552015-07-21 17:40:14 +00002806 // If we have a call to llvm.localescape, keep it in the entry block.
2807 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2808
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002809 SmallVector<ASanStackVariableDescription, 16> SVD;
2810 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002811 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002812 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002813 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002814 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002815 AI->getAlignment(),
2816 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002817 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002818 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002819 SVD.push_back(D);
2820 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002821
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002822 // Minimal header size (left redzone) is 4 pointers,
2823 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00002824 size_t Granularity = 1ULL << Mapping.Scale;
2825 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00002826 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00002827 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002828
Vitaly Buka5910a922016-10-18 23:29:52 +00002829 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2830 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2831 for (auto &Desc : SVD)
2832 AllocaToSVDMap[Desc.AI] = &Desc;
2833
2834 // Update SVD with information from lifetime intrinsics.
2835 for (const auto &APC : StaticAllocaPoisonCallVec) {
2836 assert(APC.InsBefore);
2837 assert(APC.AI);
2838 assert(ASan.isInterestingAlloca(*APC.AI));
2839 assert(APC.AI->isStaticAlloca());
2840
2841 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2842 Desc.LifetimeSize = Desc.Size;
2843 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2844 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2845 if (LifetimeLoc->getFile() == FnLoc->getFile())
2846 if (unsigned Line = LifetimeLoc->getLine())
2847 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2848 }
2849 }
2850 }
2851
2852 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2853 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002854 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002855 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2856 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002857 bool DoDynamicAlloca = ClDynamicAllocaStack;
2858 // Don't do dynamic alloca or stack malloc if:
2859 // 1) There is inline asm: too often it makes assumptions on which registers
2860 // are available.
2861 // 2) There is a returns_twice call (typically setjmp), which is
2862 // optimization-hostile, and doesn't play well with introduced indirect
2863 // register-relative calculation of local variable addresses.
2864 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2865 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002866
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002867 Value *StaticAlloca =
2868 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2869
2870 Value *FakeStack;
2871 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002872
2873 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002874 // void *FakeStack = __asan_option_detect_stack_use_after_return
2875 // ? __asan_stack_malloc_N(LocalStackSize)
2876 // : nullptr;
2877 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002878 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2879 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2880 Value *UseAfterReturnIsEnabled =
2881 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002882 Constant::getNullValue(IRB.getInt32Ty()));
2883 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002884 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002885 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002886 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002887 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2888 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2889 Value *FakeStackValue =
2890 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2891 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002892 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002893 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002894 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002895 ConstantInt::get(IntptrTy, 0));
2896
2897 Value *NoFakeStack =
2898 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2899 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2900 IRBIf.SetInsertPoint(Term);
2901 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2902 Value *AllocaValue =
2903 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2904 IRB.SetInsertPoint(InsBefore);
2905 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2906 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2907 } else {
2908 // void *FakeStack = nullptr;
2909 // void *LocalStackBase = alloca(LocalStackSize);
2910 FakeStack = ConstantInt::get(IntptrTy, 0);
2911 LocalStackBase =
2912 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002913 }
2914
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002915 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002916 for (const auto &Desc : SVD) {
2917 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002918 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002919 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002920 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002921 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002922 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002923 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002924
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002925 // The left-most redzone has enough space for at least 4 pointers.
2926 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002927 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2928 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2929 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002930 // Write the frame description constant to redzone[1].
2931 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002932 IRB.CreateAdd(LocalStackBase,
2933 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2934 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002935 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002936 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002937 /*AllowMerging*/ true);
2938 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002939 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002940 // Write the PC to redzone[2].
2941 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002942 IRB.CreateAdd(LocalStackBase,
2943 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2944 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002945 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002946
Vitaly Buka793913c2016-08-29 18:17:21 +00002947 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2948
2949 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002950 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002951 // As mask we must use most poisoned case: red zones and after scope.
2952 // As bytes we can use either the same or just red zones only.
2953 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2954
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002955 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002956 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2957
2958 // Poison static allocas near lifetime intrinsics.
2959 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002960 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002961 assert(Desc.Offset % L.Granularity == 0);
2962 size_t Begin = Desc.Offset / L.Granularity;
2963 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2964
2965 IRBuilder<> IRB(APC.InsBefore);
2966 copyToShadow(ShadowAfterScope,
2967 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2968 IRB, ShadowBase);
2969 }
2970 }
2971
2972 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002973 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002974
Kostya Serebryany530e2072013-12-23 14:15:08 +00002975 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002976 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002977 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002978 // Mark the current frame as retired.
2979 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2980 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002981 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002982 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002983 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002984 // // In use-after-return mode, poison the whole stack frame.
2985 // if StackMallocIdx <= 4
2986 // // For small sizes inline the whole thing:
2987 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002988 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002989 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002990 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002991 // else
2992 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002993 Value *Cmp =
2994 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002995 TerminatorInst *ThenTerm, *ElseTerm;
2996 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2997
2998 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002999 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003000 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003001 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3002 kAsanStackUseAfterReturnMagic);
3003 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3004 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003005 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003006 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003007 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3008 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3009 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3010 IRBPoison.CreateStore(
3011 Constant::getNullValue(IRBPoison.getInt8Ty()),
3012 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3013 } else {
3014 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003015 IRBPoison.CreateCall(
3016 AsanStackFreeFunc[StackMallocIdx],
3017 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003018 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003019
3020 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003021 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003022 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003023 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003024 }
3025 }
3026
Kostya Serebryany09959942012-10-19 06:20:53 +00003027 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003028 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003029}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003030
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003031void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003032 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003033 // For now just insert the call to ASan runtime.
3034 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3035 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003036 IRB.CreateCall(
3037 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3038 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003039}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003040
3041// Handling llvm.lifetime intrinsics for a given %alloca:
3042// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3043// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3044// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3045// could be poisoned by previous llvm.lifetime.end instruction, as the
3046// variable may go in and out of scope several times, e.g. in loops).
3047// (3) if we poisoned at least one %alloca in a function,
3048// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003049
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003050AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3051 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003052 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003053 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003054 // See if we've already calculated (or started to calculate) alloca for a
3055 // given value.
3056 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003057 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003058 // Store 0 while we're calculating alloca for value V to avoid
3059 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003060 AllocaForValue[V] = nullptr;
3061 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003062 if (CastInst *CI = dyn_cast<CastInst>(V))
3063 Res = findAllocaForValue(CI->getOperand(0));
3064 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003065 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003066 // Allow self-referencing phi-nodes.
3067 if (IncValue == PN) continue;
3068 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3069 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003070 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3071 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003072 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003073 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003074 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3075 Res = findAllocaForValue(EP->getPointerOperand());
3076 } else {
3077 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003078 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003079 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003080 return Res;
3081}
Yury Gribov55441bb2014-11-21 10:29:50 +00003082
Yury Gribov98b18592015-05-28 07:51:49 +00003083void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003084 IRBuilder<> IRB(AI);
3085
Yury Gribov55441bb2014-11-21 10:29:50 +00003086 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3087 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3088
3089 Value *Zero = Constant::getNullValue(IntptrTy);
3090 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3091 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003092
3093 // Since we need to extend alloca with additional memory to locate
3094 // redzones, and OldSize is number of allocated blocks with
3095 // ElementSize size, get allocated memory size in bytes by
3096 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003097 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003098 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003099 Value *OldSize =
3100 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3101 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003102
3103 // PartialSize = OldSize % 32
3104 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3105
3106 // Misalign = kAllocaRzSize - PartialSize;
3107 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3108
3109 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3110 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3111 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3112
3113 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3114 // Align is added to locate left redzone, PartialPadding for possible
3115 // partial redzone and kAllocaRzSize for right redzone respectively.
3116 Value *AdditionalChunkSize = IRB.CreateAdd(
3117 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3118
3119 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3120
3121 // Insert new alloca with new NewSize and Align params.
3122 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3123 NewAlloca->setAlignment(Align);
3124
3125 // NewAddress = Address + Align
3126 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3127 ConstantInt::get(IntptrTy, Align));
3128
Yury Gribov98b18592015-05-28 07:51:49 +00003129 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003130 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003131
3132 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3133 // for unpoisoning stuff.
3134 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3135
Yury Gribov55441bb2014-11-21 10:29:50 +00003136 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3137
Yury Gribov98b18592015-05-28 07:51:49 +00003138 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003139 AI->replaceAllUsesWith(NewAddressPtr);
3140
Yury Gribov98b18592015-05-28 07:51:49 +00003141 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003142 AI->eraseFromParent();
3143}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003144
3145// isSafeAccess returns true if Addr is always inbounds with respect to its
3146// base object. For example, it is a field access or an array access with
3147// constant inbounds index.
3148bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3149 Value *Addr, uint64_t TypeSize) const {
3150 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3151 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003152 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003153 int64_t Offset = SizeOffset.second.getSExtValue();
3154 // Three checks are required to ensure safety:
3155 // . Offset >= 0 (since the offset is given from the base ptr)
3156 // . Size >= Offset (unsigned)
3157 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003158 return Offset >= 0 && Size >= uint64_t(Offset) &&
3159 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003160}