blob: 5715c6067e946d4f0272c795e9638b1fdf801572 [file] [log] [blame]
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001//===- AddressSanitizer.cpp - memory error detector -----------------------===//
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
Hans Wennborg08b34a02017-11-13 23:47:58 +000012// https://github.com/google/sanitizers/wiki/AddressSanitizerAlgorithm
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000013//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000019#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000021#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/ADT/StringRef.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000025#include "llvm/ADT/Twine.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000026#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie2be39222018-03-21 22:34:23 +000028#include "llvm/Analysis/Utils/Local.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000029#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000030#include "llvm/BinaryFormat/MachO.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000031#include "llvm/IR/Argument.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000032#include "llvm/IR/Attributes.h"
33#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000034#include "llvm/IR/CallSite.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000035#include "llvm/IR/Comdat.h"
36#include "llvm/IR/Constant.h"
37#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000038#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000040#include "llvm/IR/DebugInfoMetadata.h"
41#include "llvm/IR/DebugLoc.h"
42#include "llvm/IR/DerivedTypes.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000043#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000044#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000045#include "llvm/IR/GlobalAlias.h"
46#include "llvm/IR/GlobalValue.h"
47#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/IRBuilder.h"
49#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000050#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000051#include "llvm/IR/InstrTypes.h"
52#include "llvm/IR/Instruction.h"
53#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000055#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000057#include "llvm/IR/MDBuilder.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000058#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Module.h"
60#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000061#include "llvm/IR/Use.h"
62#include "llvm/IR/Value.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000063#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000064#include "llvm/Pass.h"
65#include "llvm/Support/Casting.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066#include "llvm/Support/CommandLine.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000068#include "llvm/Support/ErrorHandling.h"
69#include "llvm/Support/MathExtras.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000070#include "llvm/Support/ScopedPrinter.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000071#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000072#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000073#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
75#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000076#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000078#include <cassert>
79#include <cstddef>
80#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000081#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000082#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000083#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000084#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000086#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
88using namespace llvm;
89
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "asan"
91
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const uint64_t kDefaultShadowScale = 3;
93static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000098static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Walter Lee8f1545c2017-11-16 17:03:00 +0000100static const uint64_t kSmallX86_64ShadowOffsetBase = 0x7FFFFFFF; // < 2G.
101static const uint64_t kSmallX86_64ShadowOffsetAlignMask = ~0xFFFULL;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000102static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Bill Seurer957a0762017-12-07 22:53:33 +0000103static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 44;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000104static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000105static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000106static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000107static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000108static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
109static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000110static const uint64_t kNetBSD_ShadowOffset32 = 1ULL << 30;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000111static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000112static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000113static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000114
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000115// The shadow memory space is dynamically allocated.
116static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000118static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000119static const size_t kMaxStackMallocSize = 1 << 16; // 64K
120static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
121static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
122
Craig Topperd3a34f82013-07-16 01:17:10 +0000123static const char *const kAsanModuleCtorName = "asan.module_ctor";
124static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000125static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000126static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000127static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000128static const char *const kAsanUnregisterGlobalsName =
129 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000130static const char *const kAsanRegisterImageGlobalsName =
131 "__asan_register_image_globals";
132static const char *const kAsanUnregisterImageGlobalsName =
133 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000134static const char *const kAsanRegisterElfGlobalsName =
135 "__asan_register_elf_globals";
136static const char *const kAsanUnregisterElfGlobalsName =
137 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000138static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
139static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000140static const char *const kAsanInitName = "__asan_init";
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000141static const char *const kAsanVersionCheckNamePrefix =
142 "__asan_version_mismatch_check_v";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000143static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
144static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000145static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000146static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000147static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
148static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000149static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000150static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000151static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000152static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000153static const char *const kAsanPoisonStackMemoryName =
154 "__asan_poison_stack_memory";
155static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000156 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000157
158// ASan version script has __asan_* wildcard. Triple underscore prevents a
159// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000160static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000161 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000162
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000163static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000164 "__asan_option_detect_stack_use_after_return";
165
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000166static const char *const kAsanShadowMemoryDynamicAddress =
167 "__asan_shadow_memory_dynamic_address";
168
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000169static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
170static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000171
Kostya Serebryany874dae62012-07-16 16:15:40 +0000172// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
173static const size_t kNumberOfAccessSizes = 5;
174
Yury Gribov55441bb2014-11-21 10:29:50 +0000175static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000176
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000177// Command-line flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000178
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000179static cl::opt<bool> ClEnableKasan(
180 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
181 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000182
Yury Gribovd7731982015-11-11 10:36:49 +0000183static cl::opt<bool> ClRecover(
184 "asan-recover",
185 cl::desc("Enable recovery mode (continue-after-error)."),
186 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000187
188// This flag may need to be replaced with -f[no-]asan-reads.
189static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc("instrument read instructions"),
191 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000192
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000193static cl::opt<bool> ClInstrumentWrites(
194 "asan-instrument-writes", cl::desc("instrument write instructions"),
195 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000196
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197static cl::opt<bool> ClInstrumentAtomics(
198 "asan-instrument-atomics",
199 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
200 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000201
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000202static cl::opt<bool> ClAlwaysSlowPath(
203 "asan-always-slow-path",
204 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
205 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000206
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000207static cl::opt<bool> ClForceDynamicShadow(
208 "asan-force-dynamic-shadow",
209 cl::desc("Load shadow address into a local variable for each function"),
210 cl::Hidden, cl::init(false));
211
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000212static cl::opt<bool>
213 ClWithIfunc("asan-with-ifunc",
214 cl::desc("Access dynamic shadow through an ifunc global on "
215 "platforms that support this"),
216 cl::Hidden, cl::init(true));
217
218static cl::opt<bool> ClWithIfuncSuppressRemat(
219 "asan-with-ifunc-suppress-remat",
220 cl::desc("Suppress rematerialization of dynamic shadow address by passing "
221 "it through inline asm in prologue."),
222 cl::Hidden, cl::init(true));
223
Kostya Serebryany874dae62012-07-16 16:15:40 +0000224// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000225// in any given BB. Normally, this should be set to unlimited (INT_MAX),
226// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
227// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000228static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
229 "asan-max-ins-per-bb", cl::init(10000),
230 cl::desc("maximal number of instructions to instrument in any given BB"),
231 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000232
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000233// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000234static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
235 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000236static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
237 "asan-max-inline-poisoning-size",
238 cl::desc(
239 "Inline shadow poisoning for blocks up to the given size in bytes."),
240 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000241
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000242static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000243 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000244 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000245
Vitaly Buka74443f02017-07-18 22:28:03 +0000246static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
247 cl::desc("Create redzones for byval "
248 "arguments (extra copy "
249 "required)"), cl::Hidden,
250 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000251
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000252static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
253 cl::desc("Check stack-use-after-scope"),
254 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000255
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000256// This flag may need to be replaced with -f[no]asan-globals.
257static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000258 cl::desc("Handle global objects"), cl::Hidden,
259 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000260
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000261static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000262 cl::desc("Handle C++ initializer order"),
263 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000264
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000265static cl::opt<bool> ClInvalidPointerPairs(
266 "asan-detect-invalid-pointer-pair",
267 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
268 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000269
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000270static cl::opt<unsigned> ClRealignStack(
271 "asan-realign-stack",
272 cl::desc("Realign stack to the value of this flag (power of two)"),
273 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000274
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000275static cl::opt<int> ClInstrumentationWithCallsThreshold(
276 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000277 cl::desc(
278 "If the function being instrumented contains more than "
279 "this number of memory accesses, use callbacks instead of "
280 "inline checks (-1 means never use callbacks)."),
281 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000282
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000283static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284 "asan-memory-access-callback-prefix",
285 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
286 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000287
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000288static cl::opt<bool>
289 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
290 cl::desc("instrument dynamic allocas"),
291 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000292
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000293static cl::opt<bool> ClSkipPromotableAllocas(
294 "asan-skip-promotable-allocas",
295 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
296 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000297
298// These flags allow to change the shadow mapping.
299// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000300// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000301
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000302static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000303 cl::desc("scale of asan shadow mapping"),
304 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000305
Ryan Govostes6194ae62016-05-06 11:22:11 +0000306static cl::opt<unsigned long long> ClMappingOffset(
307 "asan-mapping-offset",
308 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
309 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000310
311// Optimization flags. Not user visible, used mostly for testing
312// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000313
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
315 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000316
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000317static cl::opt<bool> ClOptSameTemp(
318 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
319 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000320
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000321static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000322 cl::desc("Don't instrument scalar globals"),
323 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000324
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000325static cl::opt<bool> ClOptStack(
326 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
327 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000328
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000329static cl::opt<bool> ClDynamicAllocaStack(
330 "asan-stack-dynamic-alloca",
331 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000332 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000333
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000334static cl::opt<uint32_t> ClForceExperiment(
335 "asan-force-experiment",
336 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
337 cl::init(0));
338
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000339static cl::opt<bool>
340 ClUsePrivateAliasForGlobals("asan-use-private-alias",
341 cl::desc("Use private aliases for global"
342 " variables"),
343 cl::Hidden, cl::init(false));
344
Ryan Govostese51401b2016-07-05 21:53:08 +0000345static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000346 ClUseGlobalsGC("asan-globals-live-support",
347 cl::desc("Use linker features to support dead "
348 "code stripping of globals"),
349 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000350
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000351// This is on by default even though there is a bug in gold:
352// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
353static cl::opt<bool>
354 ClWithComdat("asan-with-comdat",
355 cl::desc("Place ASan constructors in comdat sections"),
356 cl::Hidden, cl::init(true));
357
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000358// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000359
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000360static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
361 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000362
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000363static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
364 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000365
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000366static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
367 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000368
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000369static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
370 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000371
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000372static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000373 cl::Hidden, cl::init(-1));
374
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000375STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
376STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000377STATISTIC(NumOptimizedAccessesToGlobalVar,
378 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000379STATISTIC(NumOptimizedAccessesToStackVar,
380 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000381
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000382namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000383
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000384/// Frontend-provided metadata for source location.
385struct LocationMetadata {
386 StringRef Filename;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000387 int LineNo = 0;
388 int ColumnNo = 0;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000389
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000390 LocationMetadata() = default;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000391
392 bool empty() const { return Filename.empty(); }
393
394 void parse(MDNode *MDN) {
395 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000396 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
397 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000398 LineNo =
399 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
400 ColumnNo =
401 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000402 }
403};
404
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000405/// Frontend-provided metadata for global variables.
406class GlobalsMetadata {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000407public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000408 struct Entry {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000409 LocationMetadata SourceLoc;
410 StringRef Name;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000411 bool IsDynInit = false;
412 bool IsBlacklisted = false;
413
414 Entry() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000415 };
416
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000417 GlobalsMetadata() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000418
Keno Fischere03fae42015-12-05 14:42:34 +0000419 void reset() {
420 inited_ = false;
421 Entries.clear();
422 }
423
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000424 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000425 assert(!inited_);
426 inited_ = true;
427 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000428 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000429 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000430 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000431 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000432 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000433 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000434 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000435 // We can already have an entry for GV if it was merged with another
436 // global.
437 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000438 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
439 E.SourceLoc.parse(Loc);
440 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
441 E.Name = Name->getString();
442 ConstantInt *IsDynInit =
443 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000444 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000445 ConstantInt *IsBlacklisted =
446 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000447 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000448 }
449 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000450
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000451 /// Returns metadata entry for a given global.
452 Entry get(GlobalVariable *G) const {
453 auto Pos = Entries.find(G);
454 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000455 }
456
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000457private:
458 bool inited_ = false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000459 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000460};
461
Alexey Samsonov1345d352013-01-16 13:23:28 +0000462/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000463/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000464/// If InGlobal is true, then
465/// extern char __asan_shadow[];
466/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000467struct ShadowMapping {
468 int Scale;
469 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000470 bool OrShadowOffset;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000471 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000472};
473
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000474} // end anonymous namespace
475
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000476static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
477 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000478 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000479 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000480 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000481 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000482 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000483 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000484 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
485 TargetTriple.getArch() == Triple::ppc64le;
486 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
487 bool IsX86 = TargetTriple.getArch() == Triple::x86;
488 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
489 bool IsMIPS32 = TargetTriple.getArch() == Triple::mips ||
490 TargetTriple.getArch() == Triple::mipsel;
491 bool IsMIPS64 = TargetTriple.getArch() == Triple::mips64 ||
492 TargetTriple.getArch() == Triple::mips64el;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000493 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000494 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000495 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000496 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000497
498 ShadowMapping Mapping;
499
Walter Lee8f1545c2017-11-16 17:03:00 +0000500 Mapping.Scale = kDefaultShadowScale;
501 if (ClMappingScale.getNumOccurrences() > 0) {
502 Mapping.Scale = ClMappingScale;
503 }
504
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000505 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000506 if (IsAndroid)
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000507 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000508 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000509 Mapping.Offset = kMIPS32_ShadowOffset32;
510 else if (IsFreeBSD)
511 Mapping.Offset = kFreeBSD_ShadowOffset32;
Kamil Rytarowski02c432a2018-05-11 00:58:01 +0000512 else if (IsNetBSD)
513 Mapping.Offset = kNetBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000514 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000515 // If we're targeting iOS and x86, the binary is built for iOS simulator.
516 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000517 else if (IsWindows)
518 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000519 else
520 Mapping.Offset = kDefaultShadowOffset32;
521 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000522 // Fuchsia is always PIE, which means that the beginning of the address
523 // space is always available.
524 if (IsFuchsia)
525 Mapping.Offset = 0;
526 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000527 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000528 else if (IsSystemZ)
529 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000530 else if (IsFreeBSD)
531 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000532 else if (IsNetBSD)
533 Mapping.Offset = kNetBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000534 else if (IsPS4CPU)
535 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000536 else if (IsLinux && IsX86_64) {
537 if (IsKasan)
538 Mapping.Offset = kLinuxKasan_ShadowOffset64;
539 else
Walter Lee8f1545c2017-11-16 17:03:00 +0000540 Mapping.Offset = (kSmallX86_64ShadowOffsetBase &
541 (kSmallX86_64ShadowOffsetAlignMask << Mapping.Scale));
Etienne Bergeron70684f92016-06-21 15:07:29 +0000542 } else if (IsWindows && IsX86_64) {
543 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000544 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000545 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000546 else if (IsIOS)
547 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000548 // We are using dynamic shadow offset on the 64-bit devices.
549 Mapping.Offset =
550 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000551 else if (IsAArch64)
552 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000553 else
554 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000555 }
556
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000557 if (ClForceDynamicShadow) {
558 Mapping.Offset = kDynamicShadowSentinel;
559 }
560
Ryan Govostes3f37df02016-05-06 10:25:22 +0000561 if (ClMappingOffset.getNumOccurrences() > 0) {
562 Mapping.Offset = ClMappingOffset;
563 }
564
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000565 // OR-ing shadow offset if more efficient (at least on x86) if the offset
566 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000567 // offset is not necessary 1/8-th of the address space. On SystemZ,
568 // we could OR the constant in a single instruction, but it's more
569 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000570 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
571 !(Mapping.Offset & (Mapping.Offset - 1)) &&
572 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000573 bool IsAndroidWithIfuncSupport =
574 IsAndroid && !TargetTriple.isAndroidVersionLT(21);
575 Mapping.InGlobal = ClWithIfunc && IsAndroidWithIfuncSupport && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000576
Alexey Samsonov1345d352013-01-16 13:23:28 +0000577 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000578}
579
Alexey Samsonov1345d352013-01-16 13:23:28 +0000580static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000581 // Redzone used for stack and globals is at least 32 bytes.
582 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000583 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000584}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000585
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000586namespace {
587
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000588/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000589struct AddressSanitizer : public FunctionPass {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000590 // Pass identification, replacement for typeid
591 static char ID;
592
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000593 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
594 bool UseAfterScope = false)
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000595 : FunctionPass(ID), UseAfterScope(UseAfterScope || ClUseAfterScope) {
596 this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
597 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
598 ClEnableKasan : CompileKernel;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000599 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
600 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000601
Mehdi Amini117296c2016-10-01 02:56:57 +0000602 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000603 return "AddressSanitizerFunctionPass";
604 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000605
Yury Gribov3ae427d2014-12-01 08:47:58 +0000606 void getAnalysisUsage(AnalysisUsage &AU) const override {
607 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000608 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000609 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000610
Vitaly Buka21a9e572016-07-28 22:50:50 +0000611 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000612 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000613 if (AI.isArrayAllocation()) {
614 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000615 assert(CI && "non-constant array size");
616 ArraySize = CI->getZExtValue();
617 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000618 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000619 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000620 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000621 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000622 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000623
Anna Zaks8ed1d812015-02-27 03:12:36 +0000624 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000625 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000626
Anna Zaks8ed1d812015-02-27 03:12:36 +0000627 /// If it is an interesting memory access, return the PointerOperand
628 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000629 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
630 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000631 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000632 uint64_t *TypeSize, unsigned *Alignment,
633 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000634
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000635 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000637 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000638 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
639 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000640 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000641 void instrumentUnusualSizeOrAlignment(Instruction *I,
642 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000643 uint32_t TypeSize, bool IsWrite,
644 Value *SizeArgument, bool UseCalls,
645 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000646 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
647 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000648 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000649 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000650 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000651 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000652 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000653 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000654 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000655 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000656 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000657 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000658 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000659
Yury Gribov3ae427d2014-12-01 08:47:58 +0000660 DominatorTree &getDominatorTree() const { return *DT; }
661
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000662private:
663 friend struct FunctionStackPoisoner;
664
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000665 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000666
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000667 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000668 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000669 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
670 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000671
Reid Kleckner2f907552015-07-21 17:40:14 +0000672 /// Helper to cleanup per-function state.
673 struct FunctionStateRAII {
674 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000675
Reid Kleckner2f907552015-07-21 17:40:14 +0000676 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
677 assert(Pass->ProcessedAllocas.empty() &&
678 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000679 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000680 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000681
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000682 ~FunctionStateRAII() {
683 Pass->LocalDynamicShadow = nullptr;
684 Pass->ProcessedAllocas.clear();
685 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000686 };
687
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000688 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000689 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000690 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000691 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000692 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000693 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000694 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000695 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000696 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000697 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000698 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000699 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000700
701 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000702 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
703 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000704
705 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000706 Function *AsanErrorCallbackSized[2][2];
707 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000708
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000709 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000710 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000711 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000712 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000713 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000714};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000715
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000716class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000717public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000718 // Pass identification, replacement for typeid
719 static char ID;
720
Yury Gribovd7731982015-11-11 10:36:49 +0000721 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000722 bool Recover = false,
723 bool UseGlobalsGC = true)
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000724 : ModulePass(ID),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000725 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
726 // Not a typo: ClWithComdat is almost completely pointless without
727 // ClUseGlobalsGC (because then it only works on modules without
728 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
729 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
730 // argument is designed as workaround. Therefore, disable both
731 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
732 // do globals-gc.
Andrey Konovalov1ba9d9c2018-04-13 18:05:21 +0000733 UseCtorComdat(UseGlobalsGC && ClWithComdat) {
734 this->Recover = ClRecover.getNumOccurrences() > 0 ?
735 ClRecover : Recover;
736 this->CompileKernel = ClEnableKasan.getNumOccurrences() > 0 ?
737 ClEnableKasan : CompileKernel;
738 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000739
Craig Topper3e4c6972014-03-05 09:10:37 +0000740 bool runOnModule(Module &M) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000741 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000742
Mehdi Amini117296c2016-10-01 02:56:57 +0000743private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000744 void initializeCallbacks(Module &M);
745
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000746 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000747 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
748 ArrayRef<GlobalVariable *> ExtendedGlobals,
749 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000750 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
751 ArrayRef<GlobalVariable *> ExtendedGlobals,
752 ArrayRef<Constant *> MetadataInitializers,
753 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000754 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
755 ArrayRef<GlobalVariable *> ExtendedGlobals,
756 ArrayRef<Constant *> MetadataInitializers);
757 void
758 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
759 ArrayRef<GlobalVariable *> ExtendedGlobals,
760 ArrayRef<Constant *> MetadataInitializers);
761
762 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
763 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000764 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
765 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000766 IRBuilder<> CreateAsanModuleDtor(Module &M);
767
Kostya Serebryany20a79972012-11-22 03:18:50 +0000768 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000769 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000770 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000771 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000772 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000773 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000774 return RedzoneSizeForScale(Mapping.Scale);
775 }
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +0000776 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000777
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000778 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000779 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000780 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000781 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000782 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000783 Type *IntptrTy;
784 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000785 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000786 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000787 Function *AsanPoisonGlobals;
788 Function *AsanUnpoisonGlobals;
789 Function *AsanRegisterGlobals;
790 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000791 Function *AsanRegisterImageGlobals;
792 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000793 Function *AsanRegisterElfGlobals;
794 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000795
796 Function *AsanCtorFunction = nullptr;
797 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000798};
799
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000800// Stack poisoning does not play well with exception handling.
801// When an exception is thrown, we essentially bypass the code
802// that unpoisones the stack. This is why the run-time library has
803// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
804// stack in the interceptor. This however does not work inside the
805// actual function which catches the exception. Most likely because the
806// compiler hoists the load of the shadow value somewhere too high.
807// This causes asan to report a non-existing bug on 453.povray.
808// It sounds like an LLVM bug.
809struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
810 Function &F;
811 AddressSanitizer &ASan;
812 DIBuilder DIB;
813 LLVMContext *C;
814 Type *IntptrTy;
815 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000816 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000817
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000818 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000819 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000820 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000821 unsigned StackAlignment;
822
Kostya Serebryany6805de52013-09-10 13:16:56 +0000823 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000824 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000825 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000826 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000827 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000828
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000829 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
830 struct AllocaPoisonCall {
831 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000832 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000833 uint64_t Size;
834 bool DoPoison;
835 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000836 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
837 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000838
Yury Gribov98b18592015-05-28 07:51:49 +0000839 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
840 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
841 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000842 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000843
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000844 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000845 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000846 AllocaForValueMapTy AllocaForValue;
847
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000848 bool HasNonEmptyInlineAsm = false;
849 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000850 std::unique_ptr<CallInst> EmptyInlineAsm;
851
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000852 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000853 : F(F),
854 ASan(ASan),
855 DIB(*F.getParent(), /*AllowUnresolved*/ false),
856 C(ASan.C),
857 IntptrTy(ASan.IntptrTy),
858 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
859 Mapping(ASan.Mapping),
860 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000861 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000862
863 bool runOnFunction() {
864 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000865
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000866 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000867 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000868
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000869 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000870 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000871
Yury Gribov55441bb2014-11-21 10:29:50 +0000872 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000873
874 initializeCallbacks(*F.getParent());
875
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000876 processDynamicAllocas();
877 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000878
879 if (ClDebugStack) {
880 DEBUG(dbgs() << F);
881 }
882 return true;
883 }
884
Vitaly Buka74443f02017-07-18 22:28:03 +0000885 // Arguments marked with the "byval" attribute are implicitly copied without
886 // using an alloca instruction. To produce redzones for those arguments, we
887 // copy them a second time into memory allocated with an alloca instruction.
888 void copyArgsPassedByValToAllocas();
889
Yury Gribov55441bb2014-11-21 10:29:50 +0000890 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000891 // poisoned red zones around all of them.
892 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000893 void processStaticAllocas();
894 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000895
Yury Gribov98b18592015-05-28 07:51:49 +0000896 void createDynamicAllocasInitStorage();
897
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000898 // ----------------------- Visitors.
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000899 /// Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000900 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000901
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000902 /// Collect all Resume instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000903 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
904
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000905 /// Collect all CatchReturnInst instructions.
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000906 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
907
Yury Gribov98b18592015-05-28 07:51:49 +0000908 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
909 Value *SavedStack) {
910 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000911 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
912 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
913 // need to adjust extracted SP to compute the address of the most recent
914 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
915 // this purpose.
916 if (!isa<ReturnInst>(InstBefore)) {
917 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
918 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
919 {IntptrTy});
920
921 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
922
923 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
924 DynamicAreaOffset);
925 }
926
Yury Gribov781bce22015-05-28 08:03:28 +0000927 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000928 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000929 }
930
Yury Gribov55441bb2014-11-21 10:29:50 +0000931 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000932 void unpoisonDynamicAllocas() {
933 for (auto &Ret : RetVec)
934 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000935
Yury Gribov98b18592015-05-28 07:51:49 +0000936 for (auto &StackRestoreInst : StackRestoreVec)
937 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
938 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000939 }
940
Yury Gribov55441bb2014-11-21 10:29:50 +0000941 // Deploy and poison redzones around dynamic alloca call. To do this, we
942 // should replace this call with another one with changed parameters and
943 // replace all its uses with new address, so
944 // addr = alloca type, old_size, align
945 // is replaced by
946 // new_size = (old_size + additional_size) * sizeof(type)
947 // tmp = alloca i8, new_size, max(align, 32)
948 // addr = tmp + 32 (first 32 bytes are for the left redzone).
949 // Additional_size is added to make new memory allocation contain not only
950 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000951 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000952
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000953 /// Collect Alloca instructions we want (and can) handle.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000954 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000955 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000956 if (AI.isStaticAlloca()) {
957 // Skip over allocas that are present *before* the first instrumented
958 // alloca, we don't want to move those around.
959 if (AllocaVec.empty())
960 return;
961
962 StaticAllocasToMoveUp.push_back(&AI);
963 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000964 return;
965 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000966
967 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000968 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000969 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000970 else
971 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000972 }
973
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000974 /// Collect lifetime intrinsic calls to check for use-after-scope
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000975 /// errors.
976 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000977 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000978 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000979 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000980 if (!ASan.UseAfterScope)
981 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000982 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000983 return;
984 // Found lifetime intrinsic, add ASan instrumentation if necessary.
985 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
986 // If size argument is undefined, don't do anything.
987 if (Size->isMinusOne()) return;
988 // Check that size doesn't saturate uint64_t and can
989 // be stored in IntptrTy.
990 const uint64_t SizeValue = Size->getValue().getLimitedValue();
991 if (SizeValue == ~0ULL ||
992 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
993 return;
994 // Find alloca instruction that corresponds to llvm.lifetime argument.
995 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000996 if (!AI || !ASan.isInterestingAlloca(*AI))
997 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000998 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000999 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +00001000 if (AI->isStaticAlloca())
1001 StaticAllocaPoisonCallVec.push_back(APC);
1002 else if (ClInstrumentDynamicAllocas)
1003 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001004 }
1005
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001006 void visitCallSite(CallSite CS) {
1007 Instruction *I = CS.getInstruction();
1008 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00001009 HasNonEmptyInlineAsm |= CI->isInlineAsm() &&
1010 !CI->isIdenticalTo(EmptyInlineAsm.get()) &&
1011 I != ASan.LocalDynamicShadow;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001012 HasReturnsTwiceCall |= CI->canReturnTwice();
1013 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001014 }
1015
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001016 // ---------------------- Helpers.
1017 void initializeCallbacks(Module &M);
1018
Yury Gribov3ae427d2014-12-01 08:47:58 +00001019 bool doesDominateAllExits(const Instruction *I) const {
1020 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001021 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001022 }
1023 return true;
1024 }
1025
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001026 /// Finds alloca where the value comes from.
1027 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001028
1029 // Copies bytes from ShadowBytes into shadow memory for indexes where
1030 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1031 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1032 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1033 IRBuilder<> &IRB, Value *ShadowBase);
1034 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1035 size_t Begin, size_t End, IRBuilder<> &IRB,
1036 Value *ShadowBase);
1037 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1038 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1039 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1040
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001041 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001042
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001043 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1044 bool Dynamic);
1045 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1046 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001047};
1048
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001049} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001050
1051char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001052
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001053INITIALIZE_PASS_BEGIN(
1054 AddressSanitizer, "asan",
1055 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1056 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001057INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001058INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001059INITIALIZE_PASS_END(
1060 AddressSanitizer, "asan",
1061 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1062 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001063
Yury Gribovd7731982015-11-11 10:36:49 +00001064FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001065 bool Recover,
1066 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001067 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001068 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001069}
1070
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001071char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001072
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001073INITIALIZE_PASS(
1074 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001075 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001076 "ModulePass",
1077 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001078
Yury Gribovd7731982015-11-11 10:36:49 +00001079ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001080 bool Recover,
1081 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +00001082 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001083 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001084}
1085
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001086static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001087 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001088 assert(Res < kNumberOfAccessSizes);
1089 return Res;
1090}
1091
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001092// Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001093static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1094 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001095 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001096 // We use private linkage for module-local strings. If they can be merged
1097 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001098 GlobalVariable *GV =
1099 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001100 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001101 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +00001102 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1103 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001104}
1105
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001106/// Create a global describing a source location.
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001107static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1108 LocationMetadata MD) {
1109 Constant *LocData[] = {
1110 createPrivateGlobalForString(M, MD.Filename, true),
1111 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1112 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1113 };
1114 auto LocStruct = ConstantStruct::getAnon(LocData);
1115 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1116 GlobalValue::PrivateLinkage, LocStruct,
1117 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001118 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001119 return GV;
1120}
1121
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001122/// Check if \p G has been created by a trusted compiler pass.
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001123static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1124 // Do not instrument asan globals.
1125 if (G->getName().startswith(kAsanGenPrefix) ||
1126 G->getName().startswith(kSanCovGenPrefix) ||
1127 G->getName().startswith(kODRGenPrefix))
1128 return true;
1129
1130 // Do not instrument gcov counter arrays.
1131 if (G->getName() == "__llvm_gcov_ctr")
1132 return true;
1133
1134 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001135}
1136
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001137Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1138 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001139 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001140 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001141 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001142 Value *ShadowBase;
1143 if (LocalDynamicShadow)
1144 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001145 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001146 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1147 if (Mapping.OrShadowOffset)
1148 return IRB.CreateOr(Shadow, ShadowBase);
1149 else
1150 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001151}
1152
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001153// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001154void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1155 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001156 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001157 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001158 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001159 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1160 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1161 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001162 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001163 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001164 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001165 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1166 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1167 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001168 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001169 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001170}
1171
Anna Zaks8ed1d812015-02-27 03:12:36 +00001172/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001173bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001174 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1175
1176 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1177 return PreviouslySeenAllocaInfo->getSecond();
1178
Yury Gribov98b18592015-05-28 07:51:49 +00001179 bool IsInteresting =
1180 (AI.getAllocatedType()->isSized() &&
1181 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001182 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001183 // We are only interested in allocas not promotable to registers.
1184 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001185 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1186 // inalloca allocas are not treated as static, and we don't want
1187 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001188 !AI.isUsedWithInAlloca() &&
1189 // swifterror allocas are register promoted by ISel
1190 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001191
1192 ProcessedAllocas[&AI] = IsInteresting;
1193 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001194}
1195
Anna Zaks8ed1d812015-02-27 03:12:36 +00001196Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1197 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001198 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001199 unsigned *Alignment,
1200 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001201 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001202 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001203
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001204 // Do not instrument the load fetching the dynamic shadow address.
1205 if (LocalDynamicShadow == I)
1206 return nullptr;
1207
Anna Zaks8ed1d812015-02-27 03:12:36 +00001208 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001209 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001210 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001211 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001212 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001213 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001214 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001215 PtrOperand = LI->getPointerOperand();
1216 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001217 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001218 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001219 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001220 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001221 PtrOperand = SI->getPointerOperand();
1222 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001223 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001224 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001225 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001226 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001227 PtrOperand = RMW->getPointerOperand();
1228 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001229 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001230 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001231 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001232 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001233 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001234 } else if (auto CI = dyn_cast<CallInst>(I)) {
1235 auto *F = dyn_cast<Function>(CI->getCalledValue());
1236 if (F && (F->getName().startswith("llvm.masked.load.") ||
1237 F->getName().startswith("llvm.masked.store."))) {
1238 unsigned OpOffset = 0;
1239 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001240 if (!ClInstrumentWrites)
1241 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001242 // Masked store has an initial operand for the value.
1243 OpOffset = 1;
1244 *IsWrite = true;
1245 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001246 if (!ClInstrumentReads)
1247 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001248 *IsWrite = false;
1249 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001250
1251 auto BasePtr = CI->getOperand(0 + OpOffset);
1252 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1253 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1254 if (auto AlignmentConstant =
1255 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1256 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1257 else
1258 *Alignment = 1; // No alignment guarantees. We probably got Undef
1259 if (MaybeMask)
1260 *MaybeMask = CI->getOperand(2 + OpOffset);
1261 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001262 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001263 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001264
Anna Zaks644d9d32016-06-22 00:15:52 +00001265 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001266 // Do not instrument acesses from different address spaces; we cannot deal
1267 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001268 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1269 if (PtrTy->getPointerAddressSpace() != 0)
1270 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001271
1272 // Ignore swifterror addresses.
1273 // swifterror memory addresses are mem2reg promoted by instruction
1274 // selection. As such they cannot have regular uses like an instrumentation
1275 // function and it makes no sense to track them as memory.
1276 if (PtrOperand->isSwiftError())
1277 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001278 }
1279
Anna Zaks8ed1d812015-02-27 03:12:36 +00001280 // Treat memory accesses to promotable allocas as non-interesting since they
1281 // will not cause memory violations. This greatly speeds up the instrumented
1282 // executable at -O0.
1283 if (ClSkipPromotableAllocas)
1284 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1285 return isInterestingAlloca(*AI) ? AI : nullptr;
1286
1287 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001288}
1289
Kostya Serebryany796f6552014-02-27 12:45:36 +00001290static bool isPointerOperand(Value *V) {
1291 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1292}
1293
1294// This is a rough heuristic; it may cause both false positives and
1295// false negatives. The proper implementation requires cooperation with
1296// the frontend.
1297static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1298 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001299 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001300 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001301 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001302 } else {
1303 return false;
1304 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001305 return isPointerOperand(I->getOperand(0)) &&
1306 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001307}
1308
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001309bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1310 // If a global variable does not have dynamic initialization we don't
1311 // have to instrument it. However, if a global does not have initializer
1312 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001313 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001314}
1315
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001316void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1317 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001318 IRBuilder<> IRB(I);
1319 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1320 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001321 for (Value *&i : Param) {
1322 if (i->getType()->isPointerTy())
1323 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001324 }
David Blaikieff6409d2015-05-18 22:13:54 +00001325 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001326}
1327
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001328static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001329 Instruction *InsertBefore, Value *Addr,
1330 unsigned Alignment, unsigned Granularity,
1331 uint32_t TypeSize, bool IsWrite,
1332 Value *SizeArgument, bool UseCalls,
1333 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001334 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1335 // if the data is properly aligned.
1336 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1337 TypeSize == 128) &&
1338 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001339 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1340 nullptr, UseCalls, Exp);
1341 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1342 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001343}
1344
1345static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1346 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001347 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001348 Value *Addr, unsigned Alignment,
1349 unsigned Granularity, uint32_t TypeSize,
1350 bool IsWrite, Value *SizeArgument,
1351 bool UseCalls, uint32_t Exp) {
1352 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1353 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1354 unsigned Num = VTy->getVectorNumElements();
1355 auto Zero = ConstantInt::get(IntptrTy, 0);
1356 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001357 Value *InstrumentedAddress = nullptr;
1358 Instruction *InsertBefore = I;
1359 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1360 // dyn_cast as we might get UndefValue
1361 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001362 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001363 // Mask is constant false, so no instrumentation needed.
1364 continue;
1365 // If we have a true or undef value, fall through to doInstrumentAddress
1366 // with InsertBefore == I
1367 }
1368 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001369 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001370 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1371 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1372 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001373 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001374
1375 IRBuilder<> IRB(InsertBefore);
1376 InstrumentedAddress =
1377 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1378 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1379 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1380 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001381 }
1382}
1383
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001384void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001385 Instruction *I, bool UseCalls,
1386 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001387 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001388 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001389 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001390 Value *MaybeMask = nullptr;
1391 Value *Addr =
1392 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001393 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001394
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001395 // Optimization experiments.
1396 // The experiments can be used to evaluate potential optimizations that remove
1397 // instrumentation (assess false negatives). Instead of completely removing
1398 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1399 // experiments that want to remove instrumentation of this instruction).
1400 // If Exp is non-zero, this pass will emit special calls into runtime
1401 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1402 // make runtime terminate the program in a special way (with a different
1403 // exit status). Then you run the new compiler on a buggy corpus, collect
1404 // the special terminations (ideally, you don't see them at all -- no false
1405 // negatives) and make the decision on the optimization.
1406 uint32_t Exp = ClForceExperiment;
1407
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001408 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001409 // If initialization order checking is disabled, a simple access to a
1410 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001411 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001412 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001413 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1414 NumOptimizedAccessesToGlobalVar++;
1415 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001416 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001417 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001418
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001419 if (ClOpt && ClOptStack) {
1420 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001421 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001422 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1423 NumOptimizedAccessesToStackVar++;
1424 return;
1425 }
1426 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001427
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001428 if (IsWrite)
1429 NumInstrumentedWrites++;
1430 else
1431 NumInstrumentedReads++;
1432
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001433 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001434 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001435 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1436 Alignment, Granularity, TypeSize, IsWrite,
1437 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001438 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001439 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001440 IsWrite, nullptr, UseCalls, Exp);
1441 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001442}
1443
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001444Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1445 Value *Addr, bool IsWrite,
1446 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001447 Value *SizeArgument,
1448 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001449 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001450 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1451 CallInst *Call = nullptr;
1452 if (SizeArgument) {
1453 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001454 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1455 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001456 else
David Blaikieff6409d2015-05-18 22:13:54 +00001457 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1458 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001459 } else {
1460 if (Exp == 0)
1461 Call =
1462 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1463 else
David Blaikieff6409d2015-05-18 22:13:54 +00001464 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1465 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001466 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001467
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001468 // We don't do Call->setDoesNotReturn() because the BB already has
1469 // UnreachableInst at the end.
1470 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001471 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001472 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001473}
1474
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001475Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001476 Value *ShadowValue,
1477 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001478 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001479 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001480 Value *LastAccessedByte =
1481 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001482 // (Addr & (Granularity - 1)) + size - 1
1483 if (TypeSize / 8 > 1)
1484 LastAccessedByte = IRB.CreateAdd(
1485 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1486 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001487 LastAccessedByte =
1488 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001489 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1490 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1491}
1492
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001493void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001494 Instruction *InsertBefore, Value *Addr,
1495 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001496 Value *SizeArgument, bool UseCalls,
1497 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001498 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001500 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1501
1502 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001503 if (Exp == 0)
1504 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1505 AddrLong);
1506 else
David Blaikieff6409d2015-05-18 22:13:54 +00001507 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1508 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001509 return;
1510 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001511
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001512 Type *ShadowTy =
1513 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1515 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1516 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001517 Value *ShadowValue =
1518 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001519
1520 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001521 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001522 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001523
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001524 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001525 // We use branch weights for the slow path check, to indicate that the slow
1526 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001527 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1528 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001529 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001530 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001531 IRB.SetInsertPoint(CheckTerm);
1532 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001533 if (Recover) {
1534 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1535 } else {
1536 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001537 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001538 CrashTerm = new UnreachableInst(*C, CrashBlock);
1539 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1540 ReplaceInstWithInst(CheckTerm, NewTerm);
1541 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001542 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001543 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001544 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001545
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001546 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001547 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001548 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001549}
1550
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001551// Instrument unusual size or unusual alignment.
1552// We can not do it with a single check, so we do 1-byte check for the first
1553// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1554// to report the actual access size.
1555void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001556 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1557 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1558 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001559 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1560 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1561 if (UseCalls) {
1562 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001563 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1564 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001565 else
David Blaikieff6409d2015-05-18 22:13:54 +00001566 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1567 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001568 } else {
1569 Value *LastByte = IRB.CreateIntToPtr(
1570 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1571 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001572 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1573 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001574 }
1575}
1576
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001577void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1578 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001579 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001580 IRBuilder<> IRB(&GlobalInit.front(),
1581 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001582
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001583 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001584 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1585 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001586
1587 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001588 for (auto &BB : GlobalInit.getBasicBlockList())
1589 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001590 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001591}
1592
1593void AddressSanitizerModule::createInitializerPoisonCalls(
1594 Module &M, GlobalValue *ModuleName) {
1595 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001596 if (!GV)
1597 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001598
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001599 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1600 if (!CA)
1601 return;
1602
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001603 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001604 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001605 ConstantStruct *CS = cast<ConstantStruct>(OP);
1606
1607 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001608 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001609 if (F->getName() == kAsanModuleCtorName) continue;
1610 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1611 // Don't instrument CTORs that will run before asan.module_ctor.
1612 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1613 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001614 }
1615 }
1616}
1617
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001618bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001619 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001620 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001621
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001622 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001623 if (!Ty->isSized()) return false;
1624 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001625 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001626 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001627 // Don't handle ODR linkage types and COMDATs since other modules may be built
1628 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001629 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1630 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1631 G->getLinkage() != GlobalVariable::InternalLinkage)
1632 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001633 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001634 // Two problems with thread-locals:
1635 // - The address of the main thread's copy can't be computed at link-time.
1636 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001637 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001638 // For now, just ignore this Global if the alignment is large.
1639 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001640
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001641 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001642 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001643
Anna Zaks11904602015-06-09 00:58:08 +00001644 // Globals from llvm.metadata aren't emitted, do not instrument them.
1645 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001646 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001647 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001648
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001649 // Do not instrument function pointers to initialization and termination
1650 // routines: dynamic linker will not properly handle redzones.
1651 if (Section.startswith(".preinit_array") ||
1652 Section.startswith(".init_array") ||
1653 Section.startswith(".fini_array")) {
1654 return false;
1655 }
1656
Anna Zaks11904602015-06-09 00:58:08 +00001657 // Callbacks put into the CRT initializer/terminator sections
1658 // should not be instrumented.
Hans Wennborg08b34a02017-11-13 23:47:58 +00001659 // See https://github.com/google/sanitizers/issues/305
Anna Zaks11904602015-06-09 00:58:08 +00001660 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1661 if (Section.startswith(".CRT")) {
1662 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1663 return false;
1664 }
1665
Kuba Brecka1001bb52014-12-05 22:19:18 +00001666 if (TargetTriple.isOSBinFormatMachO()) {
1667 StringRef ParsedSegment, ParsedSection;
1668 unsigned TAA = 0, StubSize = 0;
1669 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001670 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1671 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001672 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001673
1674 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1675 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1676 // them.
1677 if (ParsedSegment == "__OBJC" ||
1678 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1679 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1680 return false;
1681 }
Hans Wennborg08b34a02017-11-13 23:47:58 +00001682 // See https://github.com/google/sanitizers/issues/32
Kuba Brecka1001bb52014-12-05 22:19:18 +00001683 // Constant CFString instances are compiled in the following way:
1684 // -- the string buffer is emitted into
1685 // __TEXT,__cstring,cstring_literals
1686 // -- the constant NSConstantString structure referencing that buffer
1687 // is placed into __DATA,__cfstring
1688 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1689 // Moreover, it causes the linker to crash on OS X 10.7
1690 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1691 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1692 return false;
1693 }
1694 // The linker merges the contents of cstring_literals and removes the
1695 // trailing zeroes.
1696 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1697 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1698 return false;
1699 }
1700 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001701 }
1702
1703 return true;
1704}
1705
Ryan Govostes653f9d02016-03-28 20:28:57 +00001706// On Mach-O platforms, we emit global metadata in a separate section of the
1707// binary in order to allow the linker to properly dead strip. This is only
1708// supported on recent versions of ld64.
1709bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1710 if (!TargetTriple.isOSBinFormatMachO())
1711 return false;
1712
1713 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1714 return true;
1715 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001716 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001717 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1718 return true;
1719
1720 return false;
1721}
1722
Reid Kleckner01660a32016-11-21 20:40:37 +00001723StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1724 switch (TargetTriple.getObjectFormat()) {
1725 case Triple::COFF: return ".ASAN$GL";
1726 case Triple::ELF: return "asan_globals";
1727 case Triple::MachO: return "__DATA,__asan_globals,regular";
1728 default: break;
1729 }
1730 llvm_unreachable("unsupported object format");
1731}
1732
Alexey Samsonov788381b2012-12-25 12:28:20 +00001733void AddressSanitizerModule::initializeCallbacks(Module &M) {
1734 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001735
Alexey Samsonov788381b2012-12-25 12:28:20 +00001736 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001737 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001738 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001739 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001740 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001741 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001742 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001743
Alexey Samsonov788381b2012-12-25 12:28:20 +00001744 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001745 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001746 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001747 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001748 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1749 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001750 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001751 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001752
1753 // Declare the functions that find globals in a shared object and then invoke
1754 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001755 AsanRegisterImageGlobals =
1756 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001757 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001758 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001759
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001760 AsanUnregisterImageGlobals =
1761 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001762 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001763 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001764
1765 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1766 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1767 IntptrTy, IntptrTy, IntptrTy));
1768 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1769
1770 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1771 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1772 IntptrTy, IntptrTy, IntptrTy));
1773 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001774}
1775
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001776// Put the metadata and the instrumented global in the same group. This ensures
1777// that the metadata is discarded if the instrumented global is discarded.
1778void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001779 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001780 Module &M = *G->getParent();
1781 Comdat *C = G->getComdat();
1782 if (!C) {
1783 if (!G->hasName()) {
1784 // If G is unnamed, it must be internal. Give it an artificial name
1785 // so we can put it in a comdat.
1786 assert(G->hasLocalLinkage());
1787 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1788 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001789
1790 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1791 std::string Name = G->getName();
1792 Name += InternalSuffix;
1793 C = M.getOrInsertComdat(Name);
1794 } else {
1795 C = M.getOrInsertComdat(G->getName());
1796 }
1797
Reid Klecknerc212cc82017-10-31 16:16:08 +00001798 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1799 // linkage to internal linkage so that a symbol table entry is emitted. This
1800 // is necessary in order to create the comdat group.
1801 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001802 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001803 if (G->hasPrivateLinkage())
1804 G->setLinkage(GlobalValue::InternalLinkage);
1805 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001806 G->setComdat(C);
1807 }
1808
1809 assert(G->hasComdat());
1810 Metadata->setComdat(G->getComdat());
1811}
1812
1813// Create a separate metadata global and put it in the appropriate ASan
1814// global registration section.
1815GlobalVariable *
1816AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1817 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001818 auto Linkage = TargetTriple.isOSBinFormatMachO()
1819 ? GlobalVariable::InternalLinkage
1820 : GlobalVariable::PrivateLinkage;
1821 GlobalVariable *Metadata = new GlobalVariable(
1822 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001823 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001824 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001825 return Metadata;
1826}
1827
1828IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001829 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001830 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1831 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1832 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001833
1834 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1835}
1836
1837void AddressSanitizerModule::InstrumentGlobalsCOFF(
1838 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1839 ArrayRef<Constant *> MetadataInitializers) {
1840 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001841 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001842
1843 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001844 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001845 GlobalVariable *G = ExtendedGlobals[i];
1846 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001847 CreateMetadataGlobal(M, Initializer, G->getName());
1848
1849 // The MSVC linker always inserts padding when linking incrementally. We
1850 // cope with that by aligning each struct to its size, which must be a power
1851 // of two.
1852 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1853 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1854 "global metadata will not be padded appropriately");
1855 Metadata->setAlignment(SizeOfGlobalStruct);
1856
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001857 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001858 }
1859}
1860
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001861void AddressSanitizerModule::InstrumentGlobalsELF(
1862 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1863 ArrayRef<Constant *> MetadataInitializers,
1864 const std::string &UniqueModuleId) {
1865 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1866
1867 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1868 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1869 GlobalVariable *G = ExtendedGlobals[i];
1870 GlobalVariable *Metadata =
1871 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1872 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1873 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1874 MetadataGlobals[i] = Metadata;
1875
1876 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1877 }
1878
1879 // Update llvm.compiler.used, adding the new metadata globals. This is
1880 // needed so that during LTO these variables stay alive.
1881 if (!MetadataGlobals.empty())
1882 appendToCompilerUsed(M, MetadataGlobals);
1883
1884 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1885 // to look up the loaded image that contains it. Second, we can store in it
1886 // whether registration has already occurred, to prevent duplicate
1887 // registration.
1888 //
1889 // Common linkage ensures that there is only one global per shared library.
1890 GlobalVariable *RegisteredFlag = new GlobalVariable(
1891 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1892 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1893 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1894
1895 // Create start and stop symbols.
1896 GlobalVariable *StartELFMetadata = new GlobalVariable(
1897 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1898 "__start_" + getGlobalMetadataSection());
1899 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1900 GlobalVariable *StopELFMetadata = new GlobalVariable(
1901 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1902 "__stop_" + getGlobalMetadataSection());
1903 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1904
1905 // Create a call to register the globals with the runtime.
1906 IRB.CreateCall(AsanRegisterElfGlobals,
1907 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1908 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1909 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1910
1911 // We also need to unregister globals at the end, e.g., when a shared library
1912 // gets closed.
1913 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1914 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1915 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1916 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1917 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1918}
1919
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001920void AddressSanitizerModule::InstrumentGlobalsMachO(
1921 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1922 ArrayRef<Constant *> MetadataInitializers) {
1923 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1924
1925 // On recent Mach-O platforms, use a structure which binds the liveness of
1926 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1927 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001928 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001929 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1930
1931 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1932 Constant *Initializer = MetadataInitializers[i];
1933 GlobalVariable *G = ExtendedGlobals[i];
1934 GlobalVariable *Metadata =
1935 CreateMetadataGlobal(M, Initializer, G->getName());
1936
1937 // On recent Mach-O platforms, we emit the global metadata in a way that
1938 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001939 auto LivenessBinder =
1940 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1941 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001942 GlobalVariable *Liveness = new GlobalVariable(
1943 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1944 Twine("__asan_binder_") + G->getName());
1945 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1946 LivenessGlobals[i] = Liveness;
1947 }
1948
1949 // Update llvm.compiler.used, adding the new liveness globals. This is
1950 // needed so that during LTO these variables stay alive. The alternative
1951 // would be to have the linker handling the LTO symbols, but libLTO
1952 // current API does not expose access to the section for each symbol.
1953 if (!LivenessGlobals.empty())
1954 appendToCompilerUsed(M, LivenessGlobals);
1955
1956 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1957 // to look up the loaded image that contains it. Second, we can store in it
1958 // whether registration has already occurred, to prevent duplicate
1959 // registration.
1960 //
1961 // common linkage ensures that there is only one global per shared library.
1962 GlobalVariable *RegisteredFlag = new GlobalVariable(
1963 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1964 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1965 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1966
1967 IRB.CreateCall(AsanRegisterImageGlobals,
1968 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1969
1970 // We also need to unregister globals at the end, e.g., when a shared library
1971 // gets closed.
1972 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1973 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1974 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1975}
1976
1977void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1978 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1979 ArrayRef<Constant *> MetadataInitializers) {
1980 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1981 unsigned N = ExtendedGlobals.size();
1982 assert(N > 0);
1983
1984 // On platforms that don't have a custom metadata section, we emit an array
1985 // of global metadata structures.
1986 ArrayType *ArrayOfGlobalStructTy =
1987 ArrayType::get(MetadataInitializers[0]->getType(), N);
1988 auto AllGlobals = new GlobalVariable(
1989 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1990 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
Walter Lee2a2b69e2017-11-16 12:57:19 +00001991 if (Mapping.Scale > 3)
1992 AllGlobals->setAlignment(1ULL << Mapping.Scale);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001993
1994 IRB.CreateCall(AsanRegisterGlobals,
1995 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1996 ConstantInt::get(IntptrTy, N)});
1997
1998 // We also need to unregister globals at the end, e.g., when a shared library
1999 // gets closed.
2000 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
2001 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
2002 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
2003 ConstantInt::get(IntptrTy, N)});
2004}
2005
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002006// This function replaces all global variables with new variables that have
2007// trailing redzones. It also creates a function that poisons
2008// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002009// Sets *CtorComdat to true if the global registration code emitted into the
2010// asan constructor is comdat-compatible.
2011bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
2012 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002013 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002014
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002015 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2016
Alexey Samsonova02e6642014-05-29 18:40:48 +00002017 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002018 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002019 }
2020
2021 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002022 if (n == 0) {
2023 *CtorComdat = true;
2024 return false;
2025 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002026
Reid Kleckner78565832016-11-29 01:32:21 +00002027 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002028
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002029 // A global is described by a structure
2030 // size_t beg;
2031 // size_t size;
2032 // size_t size_with_redzone;
2033 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002034 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002035 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002036 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002037 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002038 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002039 StructType *GlobalStructTy =
2040 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002041 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002042 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2043 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002044
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002045 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002046
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002047 // We shouldn't merge same module names, as this string serves as unique
2048 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002049 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002050 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002051
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002052 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002053 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002054 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002055
2056 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002057 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002058 // Create string holding the global name (use global name from metadata
2059 // if it's available, otherwise just write the name of global variable).
2060 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002061 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002062 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002063
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002064 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002065 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002066 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002067 // MinRZ <= RZ <= kMaxGlobalRedzone
2068 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002069 uint64_t RZ = std::max(
2070 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002071 uint64_t RightRedzoneSize = RZ;
2072 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002073 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002074 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002075 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2076
Serge Gueltone38003f2017-05-09 19:31:13 +00002077 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2078 Constant *NewInitializer = ConstantStruct::get(
2079 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002080
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002081 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002082 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2083 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2084 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002085 GlobalVariable *NewGlobal =
2086 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2087 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002088 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002089 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002090
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002091 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2092 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2093 G->isConstant()) {
2094 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2095 if (Seq && Seq->isCString())
2096 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2097 }
2098
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002099 // Transfer the debug info. The payload starts at offset zero so we can
2100 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002101 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002102 G->getDebugInfo(GVs);
2103 for (auto *GV : GVs)
2104 NewGlobal->addDebugInfo(GV);
2105
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002106 Value *Indices2[2];
2107 Indices2[0] = IRB.getInt32(0);
2108 Indices2[1] = IRB.getInt32(0);
2109
2110 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002111 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112 NewGlobal->takeName(G);
2113 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002114 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002115
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002116 Constant *SourceLoc;
2117 if (!MD.SourceLoc.empty()) {
2118 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2119 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2120 } else {
2121 SourceLoc = ConstantInt::get(IntptrTy, 0);
2122 }
2123
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002124 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2125 GlobalValue *InstrumentedGlobal = NewGlobal;
2126
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002127 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002128 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2129 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002130 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2131 // Create local alias for NewGlobal to avoid crash on ODR between
2132 // instrumented and non-instrumented libraries.
2133 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2134 NameForGlobal + M.getName(), NewGlobal);
2135
2136 // With local aliases, we need to provide another externally visible
2137 // symbol __odr_asan_XXX to detect ODR violation.
2138 auto *ODRIndicatorSym =
2139 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2140 Constant::getNullValue(IRB.getInt8Ty()),
2141 kODRGenPrefix + NameForGlobal, nullptr,
2142 NewGlobal->getThreadLocalMode());
2143
2144 // Set meaningful attributes for indicator symbol.
2145 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2146 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2147 ODRIndicatorSym->setAlignment(1);
2148 ODRIndicator = ODRIndicatorSym;
2149 InstrumentedGlobal = GA;
2150 }
2151
Reid Kleckner01660a32016-11-21 20:40:37 +00002152 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002153 GlobalStructTy,
2154 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002155 ConstantInt::get(IntptrTy, SizeInBytes),
2156 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2157 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002158 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002159 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002160 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002161
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002162 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002163
Kostya Serebryany20343352012-10-17 13:40:06 +00002164 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002165
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002166 Initializers[i] = Initializer;
2167 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002168
Kuba Mracek8842da82018-03-08 21:02:18 +00002169 // Add instrumented globals to llvm.compiler.used list to avoid LTO from
2170 // ConstantMerge'ing them.
2171 SmallVector<GlobalValue *, 16> GlobalsToAddToUsedList;
2172 for (size_t i = 0; i < n; i++) {
2173 GlobalVariable *G = NewGlobals[i];
2174 if (G->getName().empty()) continue;
2175 GlobalsToAddToUsedList.push_back(G);
2176 }
2177 appendToCompilerUsed(M, ArrayRef<GlobalValue *>(GlobalsToAddToUsedList));
2178
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002179 std::string ELFUniqueModuleId =
2180 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2181 : "";
2182
2183 if (!ELFUniqueModuleId.empty()) {
2184 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2185 *CtorComdat = true;
2186 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002187 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002188 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002189 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2190 } else {
2191 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002192 }
2193
Reid Kleckner01660a32016-11-21 20:40:37 +00002194 // Create calls for poisoning before initializers run and unpoisoning after.
2195 if (HasDynamicallyInitializedGlobals)
2196 createInitializerPoisonCalls(M, ModuleName);
2197
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002198 DEBUG(dbgs() << M);
2199 return true;
2200}
2201
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002202int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2203 int LongSize = M.getDataLayout().getPointerSizeInBits();
2204 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2205 int Version = 8;
2206 // 32-bit Android is one version ahead because of the switch to dynamic
2207 // shadow.
2208 Version += (LongSize == 32 && isAndroid);
2209 return Version;
2210}
2211
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002212bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002213 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002214 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002215 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002216 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002217 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002218 initializeCallbacks(M);
2219
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002220 if (CompileKernel)
2221 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002222
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002223 // Create a module constructor. A destructor is created lazily because not all
2224 // platforms, and not all modules need it.
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002225 std::string VersionCheckName =
2226 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002227 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2228 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002229 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002230
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002231 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002232 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002233 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002234 if (ClGlobals) {
2235 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002236 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2237 }
2238
2239 // Put the constructor and destructor in comdat if both
2240 // (1) global instrumentation is not TU-specific
2241 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002242 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002243 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2244 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2245 AsanCtorFunction);
2246 if (AsanDtorFunction) {
2247 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2248 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2249 AsanDtorFunction);
2250 }
2251 } else {
2252 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2253 if (AsanDtorFunction)
2254 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002255 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002256
2257 return Changed;
2258}
2259
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002260void AddressSanitizer::initializeCallbacks(Module &M) {
2261 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002262 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002263 // IsWrite, TypeSize and Exp are encoded in the function name.
2264 for (int Exp = 0; Exp < 2; Exp++) {
2265 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2266 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2267 const std::string ExpStr = Exp ? "exp_" : "";
Yury Gribovd7731982015-11-11 10:36:49 +00002268 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002269
2270 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2271 SmallVector<Type *, 2> Args1{1, IntptrTy};
2272 if (Exp) {
2273 Type *ExpType = Type::getInt32Ty(*C);
2274 Args2.push_back(ExpType);
2275 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002276 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002277 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2278 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Evgeniy Stepanov31475a02018-01-25 21:28:51 +00002279 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n" + EndingStr,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002280 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002281
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002282 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2283 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2284 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2285 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002286
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002287 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2288 AccessSizeIndex++) {
2289 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2290 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2291 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2292 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2293 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002294
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002295 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2296 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2297 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2298 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2299 }
2300 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002301 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002302
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002303 const std::string MemIntrinCallbackPrefix =
2304 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002305 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002306 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002307 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002308 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002309 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002310 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002311 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002312 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002313 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002314
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002315 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002316 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002317
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002318 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002319 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002320 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002321 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002322 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2323 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2324 StringRef(""), StringRef(""),
2325 /*hasSideEffects=*/true);
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002326 if (Mapping.InGlobal)
2327 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2328 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002329}
2330
2331// virtual
2332bool AddressSanitizer::doInitialization(Module &M) {
2333 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002334 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002335
2336 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002337 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002338 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002339 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002340
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002341 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002342 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002343}
2344
Keno Fischere03fae42015-12-05 14:42:34 +00002345bool AddressSanitizer::doFinalization(Module &M) {
2346 GlobalsMD.reset();
2347 return false;
2348}
2349
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002350bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2351 // For each NSObject descendant having a +load method, this method is invoked
2352 // by the ObjC runtime before any of the static constructors is called.
2353 // Therefore we need to instrument such methods with a call to __asan_init
2354 // at the beginning in order to initialize our runtime before any access to
2355 // the shadow memory.
2356 // We cannot just ignore these methods, because they may call other
2357 // instrumented functions.
2358 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002359 Function *AsanInitFunction =
2360 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002361 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002362 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002363 return true;
2364 }
2365 return false;
2366}
2367
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002368void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2369 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanovcff19ee2017-11-15 00:11:51 +00002370 if (Mapping.Offset != kDynamicShadowSentinel)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002371 return;
2372
2373 IRBuilder<> IRB(&F.front().front());
Evgeniy Stepanov8e7018d2017-11-20 17:41:57 +00002374 if (Mapping.InGlobal) {
2375 if (ClWithIfuncSuppressRemat) {
2376 // An empty inline asm with input reg == output reg.
2377 // An opaque pointer-to-int cast, basically.
2378 InlineAsm *Asm = InlineAsm::get(
2379 FunctionType::get(IntptrTy, {AsanShadowGlobal->getType()}, false),
2380 StringRef(""), StringRef("=r,0"),
2381 /*hasSideEffects=*/false);
2382 LocalDynamicShadow =
2383 IRB.CreateCall(Asm, {AsanShadowGlobal}, ".asan.shadow");
2384 } else {
2385 LocalDynamicShadow =
2386 IRB.CreatePointerCast(AsanShadowGlobal, IntptrTy, ".asan.shadow");
2387 }
2388 } else {
2389 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2390 kAsanShadowMemoryDynamicAddress, IntptrTy);
2391 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2392 }
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002393}
2394
Reid Kleckner2f907552015-07-21 17:40:14 +00002395void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2396 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2397 // to it as uninteresting. This assumes we haven't started processing allocas
2398 // yet. This check is done up front because iterating the use list in
2399 // isInterestingAlloca would be algorithmically slower.
2400 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2401
2402 // Try to get the declaration of llvm.localescape. If it's not in the module,
2403 // we can exit early.
2404 if (!F.getParent()->getFunction("llvm.localescape")) return;
2405
2406 // Look for a call to llvm.localescape call in the entry block. It can't be in
2407 // any other block.
2408 for (Instruction &I : F.getEntryBlock()) {
2409 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2410 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2411 // We found a call. Mark all the allocas passed in as uninteresting.
2412 for (Value *Arg : II->arg_operands()) {
2413 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2414 assert(AI && AI->isStaticAlloca() &&
2415 "non-static alloca arg to localescape");
2416 ProcessedAllocas[AI] = false;
2417 }
2418 break;
2419 }
2420 }
2421}
2422
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002423bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002424 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002425 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002426 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002427
Etienne Bergeron78582b22016-09-15 15:45:05 +00002428 bool FunctionModified = false;
2429
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002430 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002431 // This function needs to be called even if the function body is not
2432 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002433 if (maybeInsertAsanInitAtFunctionEntry(F))
2434 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002435
2436 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002437 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002438
Etienne Bergeron752f8832016-09-14 17:18:37 +00002439 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2440
2441 initializeCallbacks(*F.getParent());
2442 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002443
Reid Kleckner2f907552015-07-21 17:40:14 +00002444 FunctionStateRAII CleanupObj(this);
2445
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002446 maybeInsertDynamicShadowAtFunctionEntry(F);
2447
Reid Kleckner2f907552015-07-21 17:40:14 +00002448 // We can't instrument allocas used with llvm.localescape. Only static allocas
2449 // can be passed to that intrinsic.
2450 markEscapedLocalAllocas(F);
2451
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002452 // We want to instrument every address only once per basic block (unless there
2453 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002454 SmallSet<Value *, 16> TempsToInstrument;
2455 SmallVector<Instruction *, 16> ToInstrument;
2456 SmallVector<Instruction *, 8> NoReturnCalls;
2457 SmallVector<BasicBlock *, 16> AllBlocks;
2458 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002459 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002460 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002461 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002462 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002463 const TargetLibraryInfo *TLI =
2464 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002465
2466 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002467 for (auto &BB : F) {
2468 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002469 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002470 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002471 for (auto &Inst : BB) {
2472 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002473 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002474 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002475 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002476 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002477 // If we have a mask, skip instrumentation if we've already
2478 // instrumented the full object. But don't add to TempsToInstrument
2479 // because we might get another load/store with a different mask.
2480 if (MaybeMask) {
2481 if (TempsToInstrument.count(Addr))
2482 continue; // We've seen this (whole) temp in the current BB.
2483 } else {
2484 if (!TempsToInstrument.insert(Addr).second)
2485 continue; // We've seen this temp in the current BB.
2486 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002487 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002488 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002489 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2490 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002491 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002492 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002493 // ok, take it.
2494 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002495 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002496 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002497 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002498 // A call inside BB.
2499 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002500 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002501 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002502 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2503 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002504 continue;
2505 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002506 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002507 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002508 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002509 }
2510 }
2511
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002512 bool UseCalls =
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002513 (ClInstrumentationWithCallsThreshold >= 0 &&
2514 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002515 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002516 ObjectSizeOpts ObjSizeOpts;
2517 ObjSizeOpts.RoundToAlign = true;
2518 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002519
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002520 // Instrument.
2521 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002522 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002523 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2524 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002525 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002526 instrumentMop(ObjSizeVis, Inst, UseCalls,
2527 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002528 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002529 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002530 }
2531 NumInstrumented++;
2532 }
2533
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002534 FunctionStackPoisoner FSP(F, *this);
2535 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002536
2537 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
Hans Wennborg08b34a02017-11-13 23:47:58 +00002538 // See e.g. https://github.com/google/sanitizers/issues/37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002539 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002540 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002541 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002542 }
2543
Alexey Samsonova02e6642014-05-29 18:40:48 +00002544 for (auto Inst : PointerComparisonsOrSubtracts) {
2545 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002546 NumInstrumented++;
2547 }
2548
Etienne Bergeron78582b22016-09-15 15:45:05 +00002549 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2550 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002551
Etienne Bergeron78582b22016-09-15 15:45:05 +00002552 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2553 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002554
Etienne Bergeron78582b22016-09-15 15:45:05 +00002555 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002556}
2557
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002558// Workaround for bug 11395: we don't want to instrument stack in functions
2559// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2560// FIXME: remove once the bug 11395 is fixed.
2561bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2562 if (LongSize != 32) return false;
2563 CallInst *CI = dyn_cast<CallInst>(I);
2564 if (!CI || !CI->isInlineAsm()) return false;
2565 if (CI->getNumArgOperands() <= 5) return false;
2566 // We have inline assembly with quite a few arguments.
2567 return true;
2568}
2569
2570void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2571 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002572 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2573 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002574 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2575 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002576 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002577 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002578 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002579 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002580 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002581 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002582 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2583 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002584 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002585 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2586 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002587 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002588 }
2589
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002590 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2591 std::ostringstream Name;
2592 Name << kAsanSetShadowPrefix;
2593 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002594 AsanSetShadowFunc[Val] =
2595 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002596 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002597 }
2598
Yury Gribov98b18592015-05-28 07:51:49 +00002599 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002600 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002601 AsanAllocasUnpoisonFunc =
2602 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002603 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002604}
2605
Vitaly Buka793913c2016-08-29 18:17:21 +00002606void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2607 ArrayRef<uint8_t> ShadowBytes,
2608 size_t Begin, size_t End,
2609 IRBuilder<> &IRB,
2610 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002611 if (Begin >= End)
2612 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002613
2614 const size_t LargestStoreSizeInBytes =
2615 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2616
2617 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2618
2619 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002620 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2621 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2622 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002623 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002624 if (!ShadowMask[i]) {
2625 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002626 ++i;
2627 continue;
2628 }
2629
2630 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2631 // Fit store size into the range.
2632 while (StoreSizeInBytes > End - i)
2633 StoreSizeInBytes /= 2;
2634
2635 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002636 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002637 while (j <= StoreSizeInBytes / 2)
2638 StoreSizeInBytes /= 2;
2639 }
2640
2641 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002642 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2643 if (IsLittleEndian)
2644 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2645 else
2646 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002647 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002648
2649 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2650 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002651 IRB.CreateAlignedStore(
2652 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002653
2654 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002655 }
2656}
2657
Vitaly Buka793913c2016-08-29 18:17:21 +00002658void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2659 ArrayRef<uint8_t> ShadowBytes,
2660 IRBuilder<> &IRB, Value *ShadowBase) {
2661 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2662}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002663
Vitaly Buka793913c2016-08-29 18:17:21 +00002664void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2665 ArrayRef<uint8_t> ShadowBytes,
2666 size_t Begin, size_t End,
2667 IRBuilder<> &IRB, Value *ShadowBase) {
2668 assert(ShadowMask.size() == ShadowBytes.size());
2669 size_t Done = Begin;
2670 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2671 if (!ShadowMask[i]) {
2672 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002673 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002674 }
2675 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002676 if (!AsanSetShadowFunc[Val])
2677 continue;
2678
2679 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002680 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002681 }
2682
2683 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002684 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002685 IRB.CreateCall(AsanSetShadowFunc[Val],
2686 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2687 ConstantInt::get(IntptrTy, j - i)});
2688 Done = j;
2689 }
2690 }
2691
Vitaly Buka793913c2016-08-29 18:17:21 +00002692 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002693}
2694
Kostya Serebryany6805de52013-09-10 13:16:56 +00002695// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2696// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2697static int StackMallocSizeClass(uint64_t LocalStackSize) {
2698 assert(LocalStackSize <= kMaxStackMallocSize);
2699 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002700 for (int i = 0;; i++, MaxSize *= 2)
2701 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002702 llvm_unreachable("impossible LocalStackSize");
2703}
2704
Vitaly Buka74443f02017-07-18 22:28:03 +00002705void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002706 Instruction *CopyInsertPoint = &F.front().front();
2707 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2708 // Insert after the dynamic shadow location is determined
2709 CopyInsertPoint = CopyInsertPoint->getNextNode();
2710 assert(CopyInsertPoint);
2711 }
2712 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002713 const DataLayout &DL = F.getParent()->getDataLayout();
2714 for (Argument &Arg : F.args()) {
2715 if (Arg.hasByValAttr()) {
2716 Type *Ty = Arg.getType()->getPointerElementType();
2717 unsigned Align = Arg.getParamAlignment();
2718 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2719
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002720 AllocaInst *AI = IRB.CreateAlloca(
2721 Ty, nullptr,
2722 (Arg.hasName() ? Arg.getName() : "Arg" + Twine(Arg.getArgNo())) +
2723 ".byval");
Vitaly Buka74443f02017-07-18 22:28:03 +00002724 AI->setAlignment(Align);
2725 Arg.replaceAllUsesWith(AI);
2726
2727 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
Daniel Neilsona98d9d92018-02-08 21:26:12 +00002728 IRB.CreateMemCpy(AI, Align, &Arg, Align, AllocSize);
Vitaly Buka74443f02017-07-18 22:28:03 +00002729 }
2730 }
2731}
2732
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002733PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2734 Value *ValueIfTrue,
2735 Instruction *ThenTerm,
2736 Value *ValueIfFalse) {
2737 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2738 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2739 PHI->addIncoming(ValueIfFalse, CondBlock);
2740 BasicBlock *ThenBlock = ThenTerm->getParent();
2741 PHI->addIncoming(ValueIfTrue, ThenBlock);
2742 return PHI;
2743}
2744
2745Value *FunctionStackPoisoner::createAllocaForLayout(
2746 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2747 AllocaInst *Alloca;
2748 if (Dynamic) {
2749 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2750 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2751 "MyAlloca");
2752 } else {
2753 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2754 nullptr, "MyAlloca");
2755 assert(Alloca->isStaticAlloca());
2756 }
2757 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2758 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2759 Alloca->setAlignment(FrameAlignment);
2760 return IRB.CreatePointerCast(Alloca, IntptrTy);
2761}
2762
Yury Gribov98b18592015-05-28 07:51:49 +00002763void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2764 BasicBlock &FirstBB = *F.begin();
2765 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2766 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2767 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2768 DynamicAllocaLayout->setAlignment(32);
2769}
2770
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002771void FunctionStackPoisoner::processDynamicAllocas() {
2772 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2773 assert(DynamicAllocaPoisonCallVec.empty());
2774 return;
2775 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002776
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002777 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2778 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002779 assert(APC.InsBefore);
2780 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002781 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002782 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002783
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002784 IRBuilder<> IRB(APC.InsBefore);
2785 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002786 // Dynamic allocas will be unpoisoned unconditionally below in
2787 // unpoisonDynamicAllocas.
2788 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002789 }
2790
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002791 // Handle dynamic allocas.
2792 createDynamicAllocasInitStorage();
2793 for (auto &AI : DynamicAllocaVec)
2794 handleDynamicAllocaCall(AI);
2795 unpoisonDynamicAllocas();
2796}
Yury Gribov98b18592015-05-28 07:51:49 +00002797
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002798void FunctionStackPoisoner::processStaticAllocas() {
2799 if (AllocaVec.empty()) {
2800 assert(StaticAllocaPoisonCallVec.empty());
2801 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002802 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002803
Kostya Serebryany6805de52013-09-10 13:16:56 +00002804 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002805 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002806 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002807 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002808
2809 Instruction *InsBefore = AllocaVec[0];
2810 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002811 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002812
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002813 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2814 // debug info is broken, because only entry-block allocas are treated as
2815 // regular stack slots.
2816 auto InsBeforeB = InsBefore->getParent();
2817 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002818 for (auto *AI : StaticAllocasToMoveUp)
2819 if (AI->getParent() == InsBeforeB)
2820 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002821
Reid Kleckner2f907552015-07-21 17:40:14 +00002822 // If we have a call to llvm.localescape, keep it in the entry block.
2823 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2824
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002825 SmallVector<ASanStackVariableDescription, 16> SVD;
2826 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002827 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002828 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002829 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002830 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002831 AI->getAlignment(),
2832 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002833 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002834 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002835 SVD.push_back(D);
2836 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002837
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002838 // Minimal header size (left redzone) is 4 pointers,
2839 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
Walter Lee2a2b69e2017-11-16 12:57:19 +00002840 size_t Granularity = 1ULL << Mapping.Scale;
2841 size_t MinHeaderSize = std::max((size_t)ASan.LongSize / 2, Granularity);
Vitaly Bukadb331d82016-08-29 17:41:29 +00002842 const ASanStackFrameLayout &L =
Walter Lee2a2b69e2017-11-16 12:57:19 +00002843 ComputeASanStackFrameLayout(SVD, Granularity, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002844
Vitaly Buka5910a922016-10-18 23:29:52 +00002845 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2846 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2847 for (auto &Desc : SVD)
2848 AllocaToSVDMap[Desc.AI] = &Desc;
2849
2850 // Update SVD with information from lifetime intrinsics.
2851 for (const auto &APC : StaticAllocaPoisonCallVec) {
2852 assert(APC.InsBefore);
2853 assert(APC.AI);
2854 assert(ASan.isInterestingAlloca(*APC.AI));
2855 assert(APC.AI->isStaticAlloca());
2856
2857 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2858 Desc.LifetimeSize = Desc.Size;
2859 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2860 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2861 if (LifetimeLoc->getFile() == FnLoc->getFile())
2862 if (unsigned Line = LifetimeLoc->getLine())
2863 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2864 }
2865 }
2866 }
2867
2868 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2869 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002870 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002871 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2872 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002873 bool DoDynamicAlloca = ClDynamicAllocaStack;
2874 // Don't do dynamic alloca or stack malloc if:
2875 // 1) There is inline asm: too often it makes assumptions on which registers
2876 // are available.
2877 // 2) There is a returns_twice call (typically setjmp), which is
2878 // optimization-hostile, and doesn't play well with introduced indirect
2879 // register-relative calculation of local variable addresses.
2880 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2881 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002882
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002883 Value *StaticAlloca =
2884 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2885
2886 Value *FakeStack;
2887 Value *LocalStackBase;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002888 Value *LocalStackBaseAlloca;
2889 bool Deref;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002890
2891 if (DoStackMalloc) {
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002892 LocalStackBaseAlloca =
2893 IRB.CreateAlloca(IntptrTy, nullptr, "asan_local_stack_base");
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002894 // void *FakeStack = __asan_option_detect_stack_use_after_return
2895 // ? __asan_stack_malloc_N(LocalStackSize)
2896 // : nullptr;
2897 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002898 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2899 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2900 Value *UseAfterReturnIsEnabled =
2901 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002902 Constant::getNullValue(IRB.getInt32Ty()));
2903 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002904 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002905 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002906 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002907 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2908 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2909 Value *FakeStackValue =
2910 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2911 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002912 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002913 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002914 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002915 ConstantInt::get(IntptrTy, 0));
2916
2917 Value *NoFakeStack =
2918 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2919 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2920 IRBIf.SetInsertPoint(Term);
2921 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2922 Value *AllocaValue =
2923 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002924
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002925 IRB.SetInsertPoint(InsBefore);
2926 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2927 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002928 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2929 IRB.CreateStore(LocalStackBase, LocalStackBaseAlloca);
2930 Deref = true;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002931 } else {
2932 // void *FakeStack = nullptr;
2933 // void *LocalStackBase = alloca(LocalStackSize);
2934 FakeStack = ConstantInt::get(IntptrTy, 0);
2935 LocalStackBase =
2936 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002937 LocalStackBaseAlloca = LocalStackBase;
2938 Deref = false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002939 }
2940
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002941 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002942 for (const auto &Desc : SVD) {
2943 AllocaInst *AI = Desc.AI;
Adrian Prantl3c6c14d2017-12-11 20:43:21 +00002944 replaceDbgDeclareForAlloca(AI, LocalStackBaseAlloca, DIB, Deref,
2945 Desc.Offset, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002946 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002947 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002948 AI->getType());
Alexey Samsonov261177a2012-12-04 01:34:23 +00002949 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002950 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002951
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002952 // The left-most redzone has enough space for at least 4 pointers.
2953 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002954 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2955 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2956 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002957 // Write the frame description constant to redzone[1].
2958 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002959 IRB.CreateAdd(LocalStackBase,
2960 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2961 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002962 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002963 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002964 /*AllowMerging*/ true);
2965 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002966 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002967 // Write the PC to redzone[2].
2968 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002969 IRB.CreateAdd(LocalStackBase,
2970 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2971 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002972 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002973
Vitaly Buka793913c2016-08-29 18:17:21 +00002974 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2975
2976 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002977 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002978 // As mask we must use most poisoned case: red zones and after scope.
2979 // As bytes we can use either the same or just red zones only.
2980 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2981
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002982 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002983 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2984
2985 // Poison static allocas near lifetime intrinsics.
2986 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002987 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002988 assert(Desc.Offset % L.Granularity == 0);
2989 size_t Begin = Desc.Offset / L.Granularity;
2990 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2991
2992 IRBuilder<> IRB(APC.InsBefore);
2993 copyToShadow(ShadowAfterScope,
2994 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2995 IRB, ShadowBase);
2996 }
2997 }
2998
2999 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00003000 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00003001
Kostya Serebryany530e2072013-12-23 14:15:08 +00003002 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00003003 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003004 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003005 // Mark the current frame as retired.
3006 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
3007 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003008 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00003009 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003010 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00003011 // // In use-after-return mode, poison the whole stack frame.
3012 // if StackMallocIdx <= 4
3013 // // For small sizes inline the whole thing:
3014 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003015 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00003016 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003017 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00003018 // else
3019 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003020 Value *Cmp =
3021 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00003022 TerminatorInst *ThenTerm, *ElseTerm;
3023 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
3024
3025 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003026 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003027 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00003028 ShadowAfterReturn.resize(ClassSize / L.Granularity,
3029 kAsanStackUseAfterReturnMagic);
3030 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
3031 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003032 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00003033 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003034 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
3035 Value *SavedFlagPtr = IRBPoison.CreateLoad(
3036 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
3037 IRBPoison.CreateStore(
3038 Constant::getNullValue(IRBPoison.getInt8Ty()),
3039 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
3040 } else {
3041 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00003042 IRBPoison.CreateCall(
3043 AsanStackFreeFunc[StackMallocIdx],
3044 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00003045 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00003046
3047 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003048 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00003049 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00003050 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003051 }
3052 }
3053
Kostya Serebryany09959942012-10-19 06:20:53 +00003054 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003055 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003056}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003057
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003058void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003059 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003060 // For now just insert the call to ASan runtime.
3061 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3062 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003063 IRB.CreateCall(
3064 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3065 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003066}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003067
3068// Handling llvm.lifetime intrinsics for a given %alloca:
3069// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3070// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3071// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3072// could be poisoned by previous llvm.lifetime.end instruction, as the
3073// variable may go in and out of scope several times, e.g. in loops).
3074// (3) if we poisoned at least one %alloca in a function,
3075// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003076
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003077AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3078 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003079 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003080 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003081 // See if we've already calculated (or started to calculate) alloca for a
3082 // given value.
3083 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003084 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003085 // Store 0 while we're calculating alloca for value V to avoid
3086 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003087 AllocaForValue[V] = nullptr;
3088 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003089 if (CastInst *CI = dyn_cast<CastInst>(V))
3090 Res = findAllocaForValue(CI->getOperand(0));
3091 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003092 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003093 // Allow self-referencing phi-nodes.
3094 if (IncValue == PN) continue;
3095 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3096 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003097 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3098 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003099 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003100 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003101 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3102 Res = findAllocaForValue(EP->getPointerOperand());
3103 } else {
3104 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003105 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003106 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003107 return Res;
3108}
Yury Gribov55441bb2014-11-21 10:29:50 +00003109
Yury Gribov98b18592015-05-28 07:51:49 +00003110void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003111 IRBuilder<> IRB(AI);
3112
Yury Gribov55441bb2014-11-21 10:29:50 +00003113 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3114 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3115
3116 Value *Zero = Constant::getNullValue(IntptrTy);
3117 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3118 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003119
3120 // Since we need to extend alloca with additional memory to locate
3121 // redzones, and OldSize is number of allocated blocks with
3122 // ElementSize size, get allocated memory size in bytes by
3123 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003124 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003125 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003126 Value *OldSize =
3127 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3128 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003129
3130 // PartialSize = OldSize % 32
3131 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3132
3133 // Misalign = kAllocaRzSize - PartialSize;
3134 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3135
3136 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3137 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3138 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3139
3140 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3141 // Align is added to locate left redzone, PartialPadding for possible
3142 // partial redzone and kAllocaRzSize for right redzone respectively.
3143 Value *AdditionalChunkSize = IRB.CreateAdd(
3144 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3145
3146 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3147
3148 // Insert new alloca with new NewSize and Align params.
3149 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3150 NewAlloca->setAlignment(Align);
3151
3152 // NewAddress = Address + Align
3153 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3154 ConstantInt::get(IntptrTy, Align));
3155
Yury Gribov98b18592015-05-28 07:51:49 +00003156 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003157 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003158
3159 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3160 // for unpoisoning stuff.
3161 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3162
Yury Gribov55441bb2014-11-21 10:29:50 +00003163 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3164
Yury Gribov98b18592015-05-28 07:51:49 +00003165 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003166 AI->replaceAllUsesWith(NewAddressPtr);
3167
Yury Gribov98b18592015-05-28 07:51:49 +00003168 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003169 AI->eraseFromParent();
3170}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003171
3172// isSafeAccess returns true if Addr is always inbounds with respect to its
3173// base object. For example, it is a field access or an array access with
3174// constant inbounds index.
3175bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3176 Value *Addr, uint64_t TypeSize) const {
3177 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3178 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003179 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003180 int64_t Offset = SizeOffset.second.getSExtValue();
3181 // Three checks are required to ensure safety:
3182 // . Offset >= 0 (since the offset is given from the base ptr)
3183 // . Size >= Offset (unsigned)
3184 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003185 return Offset >= 0 && Size >= uint64_t(Offset) &&
3186 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003187}