blob: 33e0206e604129f747b8864906e1d5fe15c3ea65 [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:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000019#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000021#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/StringExtras.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000023#include "llvm/ADT/StringRef.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000025#include "llvm/ADT/Twine.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000026#include "llvm/Analysis/MemoryBuiltins.h"
27#include "llvm/Analysis/TargetLibraryInfo.h"
28#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000029#include "llvm/BinaryFormat/MachO.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000030#include "llvm/IR/Argument.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000031#include "llvm/IR/Attributes.h"
32#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000033#include "llvm/IR/CallSite.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000034#include "llvm/IR/Comdat.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000037#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/DataLayout.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000039#include "llvm/IR/DebugInfoMetadata.h"
40#include "llvm/IR/DebugLoc.h"
41#include "llvm/IR/DerivedTypes.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000042#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000043#include "llvm/IR/Function.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000044#include "llvm/IR/GlobalAlias.h"
45#include "llvm/IR/GlobalValue.h"
46#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/IRBuilder.h"
48#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000049#include "llvm/IR/InstVisitor.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000050#include "llvm/IR/InstrTypes.h"
51#include "llvm/IR/Instruction.h"
52#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000053#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000054#include "llvm/IR/Intrinsics.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000056#include "llvm/IR/MDBuilder.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000057#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Module.h"
59#include "llvm/IR/Type.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000060#include "llvm/IR/Use.h"
61#include "llvm/IR/Value.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000062#include "llvm/MC/MCSectionMachO.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000063#include "llvm/Pass.h"
64#include "llvm/Support/Casting.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065#include "llvm/Support/CommandLine.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066#include "llvm/Support/Debug.h"
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000067#include "llvm/Support/ErrorHandling.h"
68#include "llvm/Support/MathExtras.h"
Vitaly Buka74443f02017-07-18 22:28:03 +000069#include "llvm/Support/ScopedPrinter.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000070#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000071#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000072#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000073#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000074#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000075#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000076#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077#include <algorithm>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000078#include <cassert>
79#include <cstddef>
80#include <cstdint>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000081#include <iomanip>
Vitaly Buka793913c2016-08-29 18:17:21 +000082#include <limits>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000083#include <memory>
Vitaly Buka3455b9b2016-08-20 18:34:39 +000084#include <sstream>
Chandler Carruthed0881b2012-12-03 16:50:05 +000085#include <string>
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000086#include <tuple>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000087
88using namespace llvm;
89
Chandler Carruth964daaa2014-04-22 02:55:47 +000090#define DEBUG_TYPE "asan"
91
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000092static const uint64_t kDefaultShadowScale = 3;
93static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
94static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +000095static const uint64_t kDynamicShadowSentinel =
96 std::numeric_limits<uint64_t>::max();
Anna Zaks3b50e702016-02-02 22:05:07 +000097static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Anna Zaks3b50e702016-02-02 22:05:07 +000098static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
99static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000100static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000101static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000102static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000103static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +0000104static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +0000105static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +0000106static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000107static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
108static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000109static const uint64_t kNetBSD_ShadowOffset64 = 1ULL << 46;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000110static const uint64_t kPS4CPU_ShadowOffset64 = 1ULL << 40;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +0000111static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000112
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000113// The shadow memory space is dynamically allocated.
114static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000115
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000116static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117static const size_t kMaxStackMallocSize = 1 << 16; // 64K
118static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
119static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
120
Craig Topperd3a34f82013-07-16 01:17:10 +0000121static const char *const kAsanModuleCtorName = "asan.module_ctor";
122static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000123static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +0000124static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000125static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +0000126static const char *const kAsanUnregisterGlobalsName =
127 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000128static const char *const kAsanRegisterImageGlobalsName =
129 "__asan_register_image_globals";
130static const char *const kAsanUnregisterImageGlobalsName =
131 "__asan_unregister_image_globals";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000132static const char *const kAsanRegisterElfGlobalsName =
133 "__asan_register_elf_globals";
134static const char *const kAsanUnregisterElfGlobalsName =
135 "__asan_unregister_elf_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +0000136static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
137static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +0000138static const char *const kAsanInitName = "__asan_init";
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000139static const char *const kAsanVersionCheckNamePrefix =
140 "__asan_version_mismatch_check_v";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000141static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
142static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000143static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000144static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000145static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
146static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000147static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000148static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000149static const char *const kSanCovGenPrefix = "__sancov_gen_";
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000150static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000151static const char *const kAsanPoisonStackMemoryName =
152 "__asan_poison_stack_memory";
153static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000154 "__asan_unpoison_stack_memory";
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000155
156// ASan version script has __asan_* wildcard. Triple underscore prevents a
157// linker (gold) warning about attempting to export a local symbol.
Ryan Govostes653f9d02016-03-28 20:28:57 +0000158static const char *const kAsanGlobalsRegisteredFlagName =
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000159 "___asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000160
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +0000161static const char *const kAsanOptionDetectUseAfterReturn =
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000162 "__asan_option_detect_stack_use_after_return";
163
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000164static const char *const kAsanShadowMemoryDynamicAddress =
165 "__asan_shadow_memory_dynamic_address";
166
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000167static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
168static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000169
Kostya Serebryany874dae62012-07-16 16:15:40 +0000170// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
171static const size_t kNumberOfAccessSizes = 5;
172
Yury Gribov55441bb2014-11-21 10:29:50 +0000173static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000174
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000175// Command-line flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000176
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000177static cl::opt<bool> ClEnableKasan(
178 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
179 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000180
Yury Gribovd7731982015-11-11 10:36:49 +0000181static cl::opt<bool> ClRecover(
182 "asan-recover",
183 cl::desc("Enable recovery mode (continue-after-error)."),
184 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185
186// This flag may need to be replaced with -f[no-]asan-reads.
187static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188 cl::desc("instrument read instructions"),
189 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000190
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000191static cl::opt<bool> ClInstrumentWrites(
192 "asan-instrument-writes", cl::desc("instrument write instructions"),
193 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000194
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000195static cl::opt<bool> ClInstrumentAtomics(
196 "asan-instrument-atomics",
197 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
198 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000199
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000200static cl::opt<bool> ClAlwaysSlowPath(
201 "asan-always-slow-path",
202 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
203 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000204
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000205static cl::opt<bool> ClForceDynamicShadow(
206 "asan-force-dynamic-shadow",
207 cl::desc("Load shadow address into a local variable for each function"),
208 cl::Hidden, cl::init(false));
209
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000210static cl::opt<bool>
211 ClWithIfunc("asan-with-ifunc",
212 cl::desc("Access dynamic shadow through an ifunc global on "
213 "platforms that support this"),
214 cl::Hidden, cl::init(false));
215
Kostya Serebryany874dae62012-07-16 16:15:40 +0000216// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000217// in any given BB. Normally, this should be set to unlimited (INT_MAX),
218// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
219// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000220static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
221 "asan-max-ins-per-bb", cl::init(10000),
222 cl::desc("maximal number of instructions to instrument in any given BB"),
223 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000224
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000225// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000226static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
227 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000228static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
229 "asan-max-inline-poisoning-size",
230 cl::desc(
231 "Inline shadow poisoning for blocks up to the given size in bytes."),
232 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000233
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000234static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000235 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000236 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000237
Vitaly Buka74443f02017-07-18 22:28:03 +0000238static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
239 cl::desc("Create redzones for byval "
240 "arguments (extra copy "
241 "required)"), cl::Hidden,
242 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000243
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000244static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
245 cl::desc("Check stack-use-after-scope"),
246 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000247
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000248// This flag may need to be replaced with -f[no]asan-globals.
249static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000250 cl::desc("Handle global objects"), cl::Hidden,
251 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000252
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000253static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000254 cl::desc("Handle C++ initializer order"),
255 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000256
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000257static cl::opt<bool> ClInvalidPointerPairs(
258 "asan-detect-invalid-pointer-pair",
259 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
260 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000261
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000262static cl::opt<unsigned> ClRealignStack(
263 "asan-realign-stack",
264 cl::desc("Realign stack to the value of this flag (power of two)"),
265 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000266
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000267static cl::opt<int> ClInstrumentationWithCallsThreshold(
268 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000269 cl::desc(
270 "If the function being instrumented contains more than "
271 "this number of memory accesses, use callbacks instead of "
272 "inline checks (-1 means never use callbacks)."),
273 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000274
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000275static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000276 "asan-memory-access-callback-prefix",
277 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
278 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000279
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000280static cl::opt<bool>
281 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
282 cl::desc("instrument dynamic allocas"),
283 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000284
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000285static cl::opt<bool> ClSkipPromotableAllocas(
286 "asan-skip-promotable-allocas",
287 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
288 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000289
290// These flags allow to change the shadow mapping.
291// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000292// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000293
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000294static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000295 cl::desc("scale of asan shadow mapping"),
296 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000297
Ryan Govostes6194ae62016-05-06 11:22:11 +0000298static cl::opt<unsigned long long> ClMappingOffset(
299 "asan-mapping-offset",
300 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
301 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000302
303// Optimization flags. Not user visible, used mostly for testing
304// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000305
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000306static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
307 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000308
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000309static cl::opt<bool> ClOptSameTemp(
310 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
311 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000312
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000313static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000314 cl::desc("Don't instrument scalar globals"),
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> ClOptStack(
318 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
319 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000320
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000321static cl::opt<bool> ClDynamicAllocaStack(
322 "asan-stack-dynamic-alloca",
323 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000324 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000325
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000326static cl::opt<uint32_t> ClForceExperiment(
327 "asan-force-experiment",
328 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
329 cl::init(0));
330
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000331static cl::opt<bool>
332 ClUsePrivateAliasForGlobals("asan-use-private-alias",
333 cl::desc("Use private aliases for global"
334 " variables"),
335 cl::Hidden, cl::init(false));
336
Ryan Govostese51401b2016-07-05 21:53:08 +0000337static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000338 ClUseGlobalsGC("asan-globals-live-support",
339 cl::desc("Use linker features to support dead "
340 "code stripping of globals"),
341 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000342
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000343// This is on by default even though there is a bug in gold:
344// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
345static cl::opt<bool>
346 ClWithComdat("asan-with-comdat",
347 cl::desc("Place ASan constructors in comdat sections"),
348 cl::Hidden, cl::init(true));
349
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000350// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000351
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000352static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
353 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000354
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000355static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
356 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000357
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000358static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
359 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000360
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000361static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
362 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000363
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000364static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000365 cl::Hidden, cl::init(-1));
366
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000367STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
368STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000369STATISTIC(NumOptimizedAccessesToGlobalVar,
370 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000371STATISTIC(NumOptimizedAccessesToStackVar,
372 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000373
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000374namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000375
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000376/// Frontend-provided metadata for source location.
377struct LocationMetadata {
378 StringRef Filename;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000379 int LineNo = 0;
380 int ColumnNo = 0;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000381
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000382 LocationMetadata() = default;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000383
384 bool empty() const { return Filename.empty(); }
385
386 void parse(MDNode *MDN) {
387 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000388 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
389 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000390 LineNo =
391 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
392 ColumnNo =
393 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000394 }
395};
396
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000397/// Frontend-provided metadata for global variables.
398class GlobalsMetadata {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000399public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000400 struct Entry {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000401 LocationMetadata SourceLoc;
402 StringRef Name;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000403 bool IsDynInit = false;
404 bool IsBlacklisted = false;
405
406 Entry() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000407 };
408
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000409 GlobalsMetadata() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000410
Keno Fischere03fae42015-12-05 14:42:34 +0000411 void reset() {
412 inited_ = false;
413 Entries.clear();
414 }
415
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000416 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000417 assert(!inited_);
418 inited_ = true;
419 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000420 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000421 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000422 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000423 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000424 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000425 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000426 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000427 // We can already have an entry for GV if it was merged with another
428 // global.
429 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000430 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
431 E.SourceLoc.parse(Loc);
432 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
433 E.Name = Name->getString();
434 ConstantInt *IsDynInit =
435 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000436 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000437 ConstantInt *IsBlacklisted =
438 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000439 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000440 }
441 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000442
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000443 /// Returns metadata entry for a given global.
444 Entry get(GlobalVariable *G) const {
445 auto Pos = Entries.find(G);
446 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000447 }
448
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000449private:
450 bool inited_ = false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000451 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000452};
453
Alexey Samsonov1345d352013-01-16 13:23:28 +0000454/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000455/// shadow = (mem >> Scale) ADD-or-OR Offset.
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000456/// If InGlobal is true, then
457/// extern char __asan_shadow[];
458/// shadow = (mem >> Scale) + &__asan_shadow
Alexey Samsonov1345d352013-01-16 13:23:28 +0000459struct ShadowMapping {
460 int Scale;
461 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000462 bool OrShadowOffset;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000463 bool InGlobal;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000464};
465
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000466} // end anonymous namespace
467
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000468static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
469 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000470 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000471 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000472 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000473 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000474 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000475 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000476 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
477 TargetTriple.getArch() == Triple::ppc64le;
478 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
479 bool IsX86 = TargetTriple.getArch() == Triple::x86;
480 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
481 bool IsMIPS32 = TargetTriple.getArch() == Triple::mips ||
482 TargetTriple.getArch() == Triple::mipsel;
483 bool IsMIPS64 = TargetTriple.getArch() == Triple::mips64 ||
484 TargetTriple.getArch() == Triple::mips64el;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000485 bool IsArmOrThumb = TargetTriple.isARM() || TargetTriple.isThumb();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000486 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000487 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000488 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000489
490 ShadowMapping Mapping;
491
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000492 if (LongSize == 32) {
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000493 if (IsAndroid)
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000494 Mapping.Offset = kDynamicShadowSentinel;
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000495 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000496 Mapping.Offset = kMIPS32_ShadowOffset32;
497 else if (IsFreeBSD)
498 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000499 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000500 // If we're targeting iOS and x86, the binary is built for iOS simulator.
501 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000502 else if (IsWindows)
503 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000504 else
505 Mapping.Offset = kDefaultShadowOffset32;
506 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000507 // Fuchsia is always PIE, which means that the beginning of the address
508 // space is always available.
509 if (IsFuchsia)
510 Mapping.Offset = 0;
511 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000512 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000513 else if (IsSystemZ)
514 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000515 else if (IsFreeBSD)
516 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000517 else if (IsNetBSD)
518 Mapping.Offset = kNetBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000519 else if (IsPS4CPU)
520 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000521 else if (IsLinux && IsX86_64) {
522 if (IsKasan)
523 Mapping.Offset = kLinuxKasan_ShadowOffset64;
524 else
525 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000526 } else if (IsWindows && IsX86_64) {
527 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000528 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000529 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000530 else if (IsIOS)
531 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000532 // We are using dynamic shadow offset on the 64-bit devices.
533 Mapping.Offset =
534 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000535 else if (IsAArch64)
536 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000537 else
538 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000539 }
540
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000541 if (ClForceDynamicShadow) {
542 Mapping.Offset = kDynamicShadowSentinel;
543 }
544
Alexey Samsonov1345d352013-01-16 13:23:28 +0000545 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000546 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000547 Mapping.Scale = ClMappingScale;
548 }
549
Ryan Govostes3f37df02016-05-06 10:25:22 +0000550 if (ClMappingOffset.getNumOccurrences() > 0) {
551 Mapping.Offset = ClMappingOffset;
552 }
553
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000554 // OR-ing shadow offset if more efficient (at least on x86) if the offset
555 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000556 // offset is not necessary 1/8-th of the address space. On SystemZ,
557 // we could OR the constant in a single instruction, but it's more
558 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000559 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
560 !(Mapping.Offset & (Mapping.Offset - 1)) &&
561 Mapping.Offset != kDynamicShadowSentinel;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000562 Mapping.InGlobal = ClWithIfunc && IsAndroid && IsArmOrThumb;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000563
Alexey Samsonov1345d352013-01-16 13:23:28 +0000564 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000565}
566
Alexey Samsonov1345d352013-01-16 13:23:28 +0000567static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000568 // Redzone used for stack and globals is at least 32 bytes.
569 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000570 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000571}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000572
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000573namespace {
574
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000575/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000576struct AddressSanitizer : public FunctionPass {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000577 // Pass identification, replacement for typeid
578 static char ID;
579
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000580 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
581 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000582 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000583 Recover(Recover || ClRecover),
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000584 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000585 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
586 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000587
Mehdi Amini117296c2016-10-01 02:56:57 +0000588 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000589 return "AddressSanitizerFunctionPass";
590 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000591
Yury Gribov3ae427d2014-12-01 08:47:58 +0000592 void getAnalysisUsage(AnalysisUsage &AU) const override {
593 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000594 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000595 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000596
Vitaly Buka21a9e572016-07-28 22:50:50 +0000597 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000598 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000599 if (AI.isArrayAllocation()) {
600 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000601 assert(CI && "non-constant array size");
602 ArraySize = CI->getZExtValue();
603 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000604 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000606 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000607 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000608 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000609
Anna Zaks8ed1d812015-02-27 03:12:36 +0000610 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000611 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000612
Anna Zaks8ed1d812015-02-27 03:12:36 +0000613 /// If it is an interesting memory access, return the PointerOperand
614 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000615 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
616 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000617 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000618 uint64_t *TypeSize, unsigned *Alignment,
619 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000620
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000621 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000622 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000623 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000624 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
625 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000626 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000627 void instrumentUnusualSizeOrAlignment(Instruction *I,
628 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000629 uint32_t TypeSize, bool IsWrite,
630 Value *SizeArgument, bool UseCalls,
631 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000632 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
633 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000634 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000635 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000636 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000637 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000638 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000639 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000640 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000641 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000642 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000643 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000644 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000645
Yury Gribov3ae427d2014-12-01 08:47:58 +0000646 DominatorTree &getDominatorTree() const { return *DT; }
647
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000648private:
649 friend struct FunctionStackPoisoner;
650
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000651 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000652
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000653 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000654 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000655 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
656 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000657
Reid Kleckner2f907552015-07-21 17:40:14 +0000658 /// Helper to cleanup per-function state.
659 struct FunctionStateRAII {
660 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000661
Reid Kleckner2f907552015-07-21 17:40:14 +0000662 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
663 assert(Pass->ProcessedAllocas.empty() &&
664 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000665 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000666 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000667
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000668 ~FunctionStateRAII() {
669 Pass->LocalDynamicShadow = nullptr;
670 Pass->ProcessedAllocas.clear();
671 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000672 };
673
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000674 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000675 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000676 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000677 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000678 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000679 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000680 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000681 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000682 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000683 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000684 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000685 Constant *AsanShadowGlobal;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000686
687 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000688 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
689 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000690
691 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000692 Function *AsanErrorCallbackSized[2][2];
693 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000694
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000695 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000696 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000697 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000698 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000699 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000700};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000701
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000702class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000703public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000704 // Pass identification, replacement for typeid
705 static char ID;
706
Yury Gribovd7731982015-11-11 10:36:49 +0000707 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000708 bool Recover = false,
709 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000710 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000711 Recover(Recover || ClRecover),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000712 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
713 // Not a typo: ClWithComdat is almost completely pointless without
714 // ClUseGlobalsGC (because then it only works on modules without
715 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
716 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
717 // argument is designed as workaround. Therefore, disable both
718 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
719 // do globals-gc.
720 UseCtorComdat(UseGlobalsGC && ClWithComdat) {}
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000721
Craig Topper3e4c6972014-03-05 09:10:37 +0000722 bool runOnModule(Module &M) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000723 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000724
Mehdi Amini117296c2016-10-01 02:56:57 +0000725private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000726 void initializeCallbacks(Module &M);
727
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000728 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000729 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
730 ArrayRef<GlobalVariable *> ExtendedGlobals,
731 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000732 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
733 ArrayRef<GlobalVariable *> ExtendedGlobals,
734 ArrayRef<Constant *> MetadataInitializers,
735 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000736 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
737 ArrayRef<GlobalVariable *> ExtendedGlobals,
738 ArrayRef<Constant *> MetadataInitializers);
739 void
740 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
741 ArrayRef<GlobalVariable *> ExtendedGlobals,
742 ArrayRef<Constant *> MetadataInitializers);
743
744 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
745 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000746 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
747 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000748 IRBuilder<> CreateAsanModuleDtor(Module &M);
749
Kostya Serebryany20a79972012-11-22 03:18:50 +0000750 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000751 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000752 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000753 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000754 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000755 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000756 return RedzoneSizeForScale(Mapping.Scale);
757 }
Evgeniy Stepanov989299c2017-11-10 22:27:48 +0000758 int GetAsanVersion(const Module &M) const;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000759
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000760 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000761 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000762 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000763 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000764 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000765 Type *IntptrTy;
766 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000767 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000768 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000769 Function *AsanPoisonGlobals;
770 Function *AsanUnpoisonGlobals;
771 Function *AsanRegisterGlobals;
772 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000773 Function *AsanRegisterImageGlobals;
774 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000775 Function *AsanRegisterElfGlobals;
776 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000777
778 Function *AsanCtorFunction = nullptr;
779 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000780};
781
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000782// Stack poisoning does not play well with exception handling.
783// When an exception is thrown, we essentially bypass the code
784// that unpoisones the stack. This is why the run-time library has
785// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
786// stack in the interceptor. This however does not work inside the
787// actual function which catches the exception. Most likely because the
788// compiler hoists the load of the shadow value somewhere too high.
789// This causes asan to report a non-existing bug on 453.povray.
790// It sounds like an LLVM bug.
791struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
792 Function &F;
793 AddressSanitizer &ASan;
794 DIBuilder DIB;
795 LLVMContext *C;
796 Type *IntptrTy;
797 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000798 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000799
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000800 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000801 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000802 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000803 unsigned StackAlignment;
804
Kostya Serebryany6805de52013-09-10 13:16:56 +0000805 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000806 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000807 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000808 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000809 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000810
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000811 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
812 struct AllocaPoisonCall {
813 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000814 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000815 uint64_t Size;
816 bool DoPoison;
817 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000818 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
819 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000820
Yury Gribov98b18592015-05-28 07:51:49 +0000821 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
822 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
823 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000824 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000825
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000826 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000827 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000828 AllocaForValueMapTy AllocaForValue;
829
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000830 bool HasNonEmptyInlineAsm = false;
831 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000832 std::unique_ptr<CallInst> EmptyInlineAsm;
833
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000834 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000835 : F(F),
836 ASan(ASan),
837 DIB(*F.getParent(), /*AllowUnresolved*/ false),
838 C(ASan.C),
839 IntptrTy(ASan.IntptrTy),
840 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
841 Mapping(ASan.Mapping),
842 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000843 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000844
845 bool runOnFunction() {
846 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000847
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000848 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000849 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000850
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000851 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000852 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000853
Yury Gribov55441bb2014-11-21 10:29:50 +0000854 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000855
856 initializeCallbacks(*F.getParent());
857
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000858 processDynamicAllocas();
859 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000860
861 if (ClDebugStack) {
862 DEBUG(dbgs() << F);
863 }
864 return true;
865 }
866
Vitaly Buka74443f02017-07-18 22:28:03 +0000867 // Arguments marked with the "byval" attribute are implicitly copied without
868 // using an alloca instruction. To produce redzones for those arguments, we
869 // copy them a second time into memory allocated with an alloca instruction.
870 void copyArgsPassedByValToAllocas();
871
Yury Gribov55441bb2014-11-21 10:29:50 +0000872 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000873 // poisoned red zones around all of them.
874 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000875 void processStaticAllocas();
876 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000877
Yury Gribov98b18592015-05-28 07:51:49 +0000878 void createDynamicAllocasInitStorage();
879
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000880 // ----------------------- Visitors.
881 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000882 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000883
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000884 /// \brief Collect all Resume instructions.
885 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
886
887 /// \brief Collect all CatchReturnInst instructions.
888 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
889
Yury Gribov98b18592015-05-28 07:51:49 +0000890 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
891 Value *SavedStack) {
892 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000893 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
894 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
895 // need to adjust extracted SP to compute the address of the most recent
896 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
897 // this purpose.
898 if (!isa<ReturnInst>(InstBefore)) {
899 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
900 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
901 {IntptrTy});
902
903 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
904
905 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
906 DynamicAreaOffset);
907 }
908
Yury Gribov781bce22015-05-28 08:03:28 +0000909 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000910 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000911 }
912
Yury Gribov55441bb2014-11-21 10:29:50 +0000913 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000914 void unpoisonDynamicAllocas() {
915 for (auto &Ret : RetVec)
916 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000917
Yury Gribov98b18592015-05-28 07:51:49 +0000918 for (auto &StackRestoreInst : StackRestoreVec)
919 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
920 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000921 }
922
Yury Gribov55441bb2014-11-21 10:29:50 +0000923 // Deploy and poison redzones around dynamic alloca call. To do this, we
924 // should replace this call with another one with changed parameters and
925 // replace all its uses with new address, so
926 // addr = alloca type, old_size, align
927 // is replaced by
928 // new_size = (old_size + additional_size) * sizeof(type)
929 // tmp = alloca i8, new_size, max(align, 32)
930 // addr = tmp + 32 (first 32 bytes are for the left redzone).
931 // Additional_size is added to make new memory allocation contain not only
932 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000933 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000934
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000935 /// \brief Collect Alloca instructions we want (and can) handle.
936 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000937 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000938 if (AI.isStaticAlloca()) {
939 // Skip over allocas that are present *before* the first instrumented
940 // alloca, we don't want to move those around.
941 if (AllocaVec.empty())
942 return;
943
944 StaticAllocasToMoveUp.push_back(&AI);
945 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000946 return;
947 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000948
949 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000950 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000951 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000952 else
953 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000954 }
955
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000956 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
957 /// errors.
958 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000959 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000960 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000961 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000962 if (!ASan.UseAfterScope)
963 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000964 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000965 return;
966 // Found lifetime intrinsic, add ASan instrumentation if necessary.
967 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
968 // If size argument is undefined, don't do anything.
969 if (Size->isMinusOne()) return;
970 // Check that size doesn't saturate uint64_t and can
971 // be stored in IntptrTy.
972 const uint64_t SizeValue = Size->getValue().getLimitedValue();
973 if (SizeValue == ~0ULL ||
974 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
975 return;
976 // Find alloca instruction that corresponds to llvm.lifetime argument.
977 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000978 if (!AI || !ASan.isInterestingAlloca(*AI))
979 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000980 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000981 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000982 if (AI->isStaticAlloca())
983 StaticAllocaPoisonCallVec.push_back(APC);
984 else if (ClInstrumentDynamicAllocas)
985 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000986 }
987
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000988 void visitCallSite(CallSite CS) {
989 Instruction *I = CS.getInstruction();
990 if (CallInst *CI = dyn_cast<CallInst>(I)) {
991 HasNonEmptyInlineAsm |=
992 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
993 HasReturnsTwiceCall |= CI->canReturnTwice();
994 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000995 }
996
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000997 // ---------------------- Helpers.
998 void initializeCallbacks(Module &M);
999
Yury Gribov3ae427d2014-12-01 08:47:58 +00001000 bool doesDominateAllExits(const Instruction *I) const {
1001 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001002 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001003 }
1004 return true;
1005 }
1006
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001007 /// Finds alloca where the value comes from.
1008 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +00001009
1010 // Copies bytes from ShadowBytes into shadow memory for indexes where
1011 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1012 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1013 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1014 IRBuilder<> &IRB, Value *ShadowBase);
1015 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1016 size_t Begin, size_t End, IRBuilder<> &IRB,
1017 Value *ShadowBase);
1018 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1019 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1020 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1021
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001022 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001023
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001024 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1025 bool Dynamic);
1026 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1027 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001028};
1029
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001030} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001031
1032char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001033
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001034INITIALIZE_PASS_BEGIN(
1035 AddressSanitizer, "asan",
1036 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1037 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001038INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001039INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001040INITIALIZE_PASS_END(
1041 AddressSanitizer, "asan",
1042 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1043 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001044
Yury Gribovd7731982015-11-11 10:36:49 +00001045FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001046 bool Recover,
1047 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001048 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001049 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001050}
1051
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001052char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001053
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001054INITIALIZE_PASS(
1055 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001056 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001057 "ModulePass",
1058 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001059
Yury Gribovd7731982015-11-11 10:36:49 +00001060ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001061 bool Recover,
1062 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +00001063 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001064 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001065}
1066
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001067static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001068 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001069 assert(Res < kNumberOfAccessSizes);
1070 return Res;
1071}
1072
Bill Wendling58f8cef2013-08-06 22:52:42 +00001073// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001074static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1075 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001076 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001077 // We use private linkage for module-local strings. If they can be merged
1078 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001079 GlobalVariable *GV =
1080 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001081 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001082 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +00001083 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1084 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001085}
1086
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001087/// \brief Create a global describing a source location.
1088static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1089 LocationMetadata MD) {
1090 Constant *LocData[] = {
1091 createPrivateGlobalForString(M, MD.Filename, true),
1092 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1093 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1094 };
1095 auto LocStruct = ConstantStruct::getAnon(LocData);
1096 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1097 GlobalValue::PrivateLinkage, LocStruct,
1098 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001099 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001100 return GV;
1101}
1102
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001103/// \brief Check if \p G has been created by a trusted compiler pass.
1104static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1105 // Do not instrument asan globals.
1106 if (G->getName().startswith(kAsanGenPrefix) ||
1107 G->getName().startswith(kSanCovGenPrefix) ||
1108 G->getName().startswith(kODRGenPrefix))
1109 return true;
1110
1111 // Do not instrument gcov counter arrays.
1112 if (G->getName() == "__llvm_gcov_ctr")
1113 return true;
1114
1115 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001116}
1117
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001118Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1119 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001120 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001121 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001122 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001123 Value *ShadowBase;
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00001124 if (Mapping.InGlobal)
1125 return IRB.CreatePtrToInt(
1126 IRB.CreateGEP(AsanShadowGlobal,
1127 {ConstantInt::get(IntptrTy, 0), Shadow}),
1128 IntptrTy);
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001129 if (LocalDynamicShadow)
1130 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001131 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001132 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1133 if (Mapping.OrShadowOffset)
1134 return IRB.CreateOr(Shadow, ShadowBase);
1135 else
1136 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001137}
1138
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001139// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001140void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1141 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001142 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001143 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001144 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001145 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1146 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1147 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001148 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001149 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001150 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001151 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1152 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1153 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001154 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001155 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001156}
1157
Anna Zaks8ed1d812015-02-27 03:12:36 +00001158/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001159bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001160 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1161
1162 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1163 return PreviouslySeenAllocaInfo->getSecond();
1164
Yury Gribov98b18592015-05-28 07:51:49 +00001165 bool IsInteresting =
1166 (AI.getAllocatedType()->isSized() &&
1167 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001168 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001169 // We are only interested in allocas not promotable to registers.
1170 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001171 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1172 // inalloca allocas are not treated as static, and we don't want
1173 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001174 !AI.isUsedWithInAlloca() &&
1175 // swifterror allocas are register promoted by ISel
1176 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001177
1178 ProcessedAllocas[&AI] = IsInteresting;
1179 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001180}
1181
Anna Zaks8ed1d812015-02-27 03:12:36 +00001182Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1183 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001184 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001185 unsigned *Alignment,
1186 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001187 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001188 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001189
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001190 // Do not instrument the load fetching the dynamic shadow address.
1191 if (LocalDynamicShadow == I)
1192 return nullptr;
1193
Anna Zaks8ed1d812015-02-27 03:12:36 +00001194 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001195 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001196 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001197 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001198 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001200 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001201 PtrOperand = LI->getPointerOperand();
1202 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001203 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001204 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001206 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001207 PtrOperand = SI->getPointerOperand();
1208 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001209 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001210 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001211 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001212 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001213 PtrOperand = RMW->getPointerOperand();
1214 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001215 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001216 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001217 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001218 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001219 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001220 } else if (auto CI = dyn_cast<CallInst>(I)) {
1221 auto *F = dyn_cast<Function>(CI->getCalledValue());
1222 if (F && (F->getName().startswith("llvm.masked.load.") ||
1223 F->getName().startswith("llvm.masked.store."))) {
1224 unsigned OpOffset = 0;
1225 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001226 if (!ClInstrumentWrites)
1227 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001228 // Masked store has an initial operand for the value.
1229 OpOffset = 1;
1230 *IsWrite = true;
1231 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001232 if (!ClInstrumentReads)
1233 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001234 *IsWrite = false;
1235 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001236
1237 auto BasePtr = CI->getOperand(0 + OpOffset);
1238 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1239 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1240 if (auto AlignmentConstant =
1241 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1242 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1243 else
1244 *Alignment = 1; // No alignment guarantees. We probably got Undef
1245 if (MaybeMask)
1246 *MaybeMask = CI->getOperand(2 + OpOffset);
1247 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001248 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001249 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001250
Anna Zaks644d9d32016-06-22 00:15:52 +00001251 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001252 // Do not instrument acesses from different address spaces; we cannot deal
1253 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001254 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1255 if (PtrTy->getPointerAddressSpace() != 0)
1256 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001257
1258 // Ignore swifterror addresses.
1259 // swifterror memory addresses are mem2reg promoted by instruction
1260 // selection. As such they cannot have regular uses like an instrumentation
1261 // function and it makes no sense to track them as memory.
1262 if (PtrOperand->isSwiftError())
1263 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001264 }
1265
Anna Zaks8ed1d812015-02-27 03:12:36 +00001266 // Treat memory accesses to promotable allocas as non-interesting since they
1267 // will not cause memory violations. This greatly speeds up the instrumented
1268 // executable at -O0.
1269 if (ClSkipPromotableAllocas)
1270 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1271 return isInterestingAlloca(*AI) ? AI : nullptr;
1272
1273 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001274}
1275
Kostya Serebryany796f6552014-02-27 12:45:36 +00001276static bool isPointerOperand(Value *V) {
1277 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1278}
1279
1280// This is a rough heuristic; it may cause both false positives and
1281// false negatives. The proper implementation requires cooperation with
1282// the frontend.
1283static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1284 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001285 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001286 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001287 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001288 } else {
1289 return false;
1290 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001291 return isPointerOperand(I->getOperand(0)) &&
1292 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001293}
1294
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001295bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1296 // If a global variable does not have dynamic initialization we don't
1297 // have to instrument it. However, if a global does not have initializer
1298 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001299 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001300}
1301
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001302void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1303 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001304 IRBuilder<> IRB(I);
1305 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1306 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001307 for (Value *&i : Param) {
1308 if (i->getType()->isPointerTy())
1309 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001310 }
David Blaikieff6409d2015-05-18 22:13:54 +00001311 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001312}
1313
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001314static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001315 Instruction *InsertBefore, Value *Addr,
1316 unsigned Alignment, unsigned Granularity,
1317 uint32_t TypeSize, bool IsWrite,
1318 Value *SizeArgument, bool UseCalls,
1319 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001320 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1321 // if the data is properly aligned.
1322 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1323 TypeSize == 128) &&
1324 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001325 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1326 nullptr, UseCalls, Exp);
1327 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1328 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001329}
1330
1331static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1332 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001333 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001334 Value *Addr, unsigned Alignment,
1335 unsigned Granularity, uint32_t TypeSize,
1336 bool IsWrite, Value *SizeArgument,
1337 bool UseCalls, uint32_t Exp) {
1338 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1339 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1340 unsigned Num = VTy->getVectorNumElements();
1341 auto Zero = ConstantInt::get(IntptrTy, 0);
1342 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001343 Value *InstrumentedAddress = nullptr;
1344 Instruction *InsertBefore = I;
1345 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1346 // dyn_cast as we might get UndefValue
1347 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001348 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001349 // Mask is constant false, so no instrumentation needed.
1350 continue;
1351 // If we have a true or undef value, fall through to doInstrumentAddress
1352 // with InsertBefore == I
1353 }
1354 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001355 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001356 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1357 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1358 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001359 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001360
1361 IRBuilder<> IRB(InsertBefore);
1362 InstrumentedAddress =
1363 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1364 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1365 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1366 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001367 }
1368}
1369
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001370void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001371 Instruction *I, bool UseCalls,
1372 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001373 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001374 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001375 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001376 Value *MaybeMask = nullptr;
1377 Value *Addr =
1378 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001379 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001380
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001381 // Optimization experiments.
1382 // The experiments can be used to evaluate potential optimizations that remove
1383 // instrumentation (assess false negatives). Instead of completely removing
1384 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1385 // experiments that want to remove instrumentation of this instruction).
1386 // If Exp is non-zero, this pass will emit special calls into runtime
1387 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1388 // make runtime terminate the program in a special way (with a different
1389 // exit status). Then you run the new compiler on a buggy corpus, collect
1390 // the special terminations (ideally, you don't see them at all -- no false
1391 // negatives) and make the decision on the optimization.
1392 uint32_t Exp = ClForceExperiment;
1393
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001394 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001395 // If initialization order checking is disabled, a simple access to a
1396 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001397 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001398 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001399 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1400 NumOptimizedAccessesToGlobalVar++;
1401 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001402 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001403 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001404
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001405 if (ClOpt && ClOptStack) {
1406 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001407 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001408 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1409 NumOptimizedAccessesToStackVar++;
1410 return;
1411 }
1412 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001413
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001414 if (IsWrite)
1415 NumInstrumentedWrites++;
1416 else
1417 NumInstrumentedReads++;
1418
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001419 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001420 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001421 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1422 Alignment, Granularity, TypeSize, IsWrite,
1423 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001424 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001425 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001426 IsWrite, nullptr, UseCalls, Exp);
1427 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001428}
1429
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001430Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1431 Value *Addr, bool IsWrite,
1432 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001433 Value *SizeArgument,
1434 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001435 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001436 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1437 CallInst *Call = nullptr;
1438 if (SizeArgument) {
1439 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001440 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1441 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001442 else
David Blaikieff6409d2015-05-18 22:13:54 +00001443 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1444 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001445 } else {
1446 if (Exp == 0)
1447 Call =
1448 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1449 else
David Blaikieff6409d2015-05-18 22:13:54 +00001450 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1451 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001452 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001453
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001454 // We don't do Call->setDoesNotReturn() because the BB already has
1455 // UnreachableInst at the end.
1456 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001457 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001458 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001459}
1460
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001461Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001462 Value *ShadowValue,
1463 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001464 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001465 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001466 Value *LastAccessedByte =
1467 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001468 // (Addr & (Granularity - 1)) + size - 1
1469 if (TypeSize / 8 > 1)
1470 LastAccessedByte = IRB.CreateAdd(
1471 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1472 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001473 LastAccessedByte =
1474 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001475 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1476 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1477}
1478
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001479void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001480 Instruction *InsertBefore, Value *Addr,
1481 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001482 Value *SizeArgument, bool UseCalls,
1483 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001484 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001485 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001486 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1487
1488 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001489 if (Exp == 0)
1490 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1491 AddrLong);
1492 else
David Blaikieff6409d2015-05-18 22:13:54 +00001493 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1494 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001495 return;
1496 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001497
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001498 Type *ShadowTy =
1499 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001500 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1501 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1502 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001503 Value *ShadowValue =
1504 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001505
1506 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001507 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001508 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001509
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001510 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001511 // We use branch weights for the slow path check, to indicate that the slow
1512 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001513 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1514 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001515 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001516 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001517 IRB.SetInsertPoint(CheckTerm);
1518 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001519 if (Recover) {
1520 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1521 } else {
1522 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001523 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001524 CrashTerm = new UnreachableInst(*C, CrashBlock);
1525 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1526 ReplaceInstWithInst(CheckTerm, NewTerm);
1527 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001528 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001529 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001531
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001532 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001533 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001534 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001535}
1536
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001537// Instrument unusual size or unusual alignment.
1538// We can not do it with a single check, so we do 1-byte check for the first
1539// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1540// to report the actual access size.
1541void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001542 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1543 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1544 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001545 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1546 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1547 if (UseCalls) {
1548 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001549 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1550 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001551 else
David Blaikieff6409d2015-05-18 22:13:54 +00001552 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1553 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001554 } else {
1555 Value *LastByte = IRB.CreateIntToPtr(
1556 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1557 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001558 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1559 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001560 }
1561}
1562
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001563void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1564 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001565 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001566 IRBuilder<> IRB(&GlobalInit.front(),
1567 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001568
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001569 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001570 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1571 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001572
1573 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001574 for (auto &BB : GlobalInit.getBasicBlockList())
1575 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001576 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001577}
1578
1579void AddressSanitizerModule::createInitializerPoisonCalls(
1580 Module &M, GlobalValue *ModuleName) {
1581 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001582 if (!GV)
1583 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001584
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001585 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1586 if (!CA)
1587 return;
1588
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001589 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001590 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001591 ConstantStruct *CS = cast<ConstantStruct>(OP);
1592
1593 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001594 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001595 if (F->getName() == kAsanModuleCtorName) continue;
1596 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1597 // Don't instrument CTORs that will run before asan.module_ctor.
1598 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1599 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001600 }
1601 }
1602}
1603
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001604bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001605 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001606 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001607
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001608 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001609 if (!Ty->isSized()) return false;
1610 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001611 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001612 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001613 // Don't handle ODR linkage types and COMDATs since other modules may be built
1614 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001615 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1616 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1617 G->getLinkage() != GlobalVariable::InternalLinkage)
1618 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001619 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001620 // Two problems with thread-locals:
1621 // - The address of the main thread's copy can't be computed at link-time.
1622 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001623 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001624 // For now, just ignore this Global if the alignment is large.
1625 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001626
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001627 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001628 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001629
Anna Zaks11904602015-06-09 00:58:08 +00001630 // Globals from llvm.metadata aren't emitted, do not instrument them.
1631 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001632 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001633 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001634
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001635 // Do not instrument function pointers to initialization and termination
1636 // routines: dynamic linker will not properly handle redzones.
1637 if (Section.startswith(".preinit_array") ||
1638 Section.startswith(".init_array") ||
1639 Section.startswith(".fini_array")) {
1640 return false;
1641 }
1642
Anna Zaks11904602015-06-09 00:58:08 +00001643 // Callbacks put into the CRT initializer/terminator sections
1644 // should not be instrumented.
1645 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1646 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1647 if (Section.startswith(".CRT")) {
1648 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1649 return false;
1650 }
1651
Kuba Brecka1001bb52014-12-05 22:19:18 +00001652 if (TargetTriple.isOSBinFormatMachO()) {
1653 StringRef ParsedSegment, ParsedSection;
1654 unsigned TAA = 0, StubSize = 0;
1655 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001656 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1657 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001658 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001659
1660 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1661 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1662 // them.
1663 if (ParsedSegment == "__OBJC" ||
1664 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1665 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1666 return false;
1667 }
1668 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1669 // Constant CFString instances are compiled in the following way:
1670 // -- the string buffer is emitted into
1671 // __TEXT,__cstring,cstring_literals
1672 // -- the constant NSConstantString structure referencing that buffer
1673 // is placed into __DATA,__cfstring
1674 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1675 // Moreover, it causes the linker to crash on OS X 10.7
1676 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1677 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1678 return false;
1679 }
1680 // The linker merges the contents of cstring_literals and removes the
1681 // trailing zeroes.
1682 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1683 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1684 return false;
1685 }
1686 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001687 }
1688
1689 return true;
1690}
1691
Ryan Govostes653f9d02016-03-28 20:28:57 +00001692// On Mach-O platforms, we emit global metadata in a separate section of the
1693// binary in order to allow the linker to properly dead strip. This is only
1694// supported on recent versions of ld64.
1695bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1696 if (!TargetTriple.isOSBinFormatMachO())
1697 return false;
1698
1699 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1700 return true;
1701 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001702 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001703 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1704 return true;
1705
1706 return false;
1707}
1708
Reid Kleckner01660a32016-11-21 20:40:37 +00001709StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1710 switch (TargetTriple.getObjectFormat()) {
1711 case Triple::COFF: return ".ASAN$GL";
1712 case Triple::ELF: return "asan_globals";
1713 case Triple::MachO: return "__DATA,__asan_globals,regular";
1714 default: break;
1715 }
1716 llvm_unreachable("unsupported object format");
1717}
1718
Alexey Samsonov788381b2012-12-25 12:28:20 +00001719void AddressSanitizerModule::initializeCallbacks(Module &M) {
1720 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001721
Alexey Samsonov788381b2012-12-25 12:28:20 +00001722 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001723 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001724 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001725 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001726 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001727 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001728 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001729
Alexey Samsonov788381b2012-12-25 12:28:20 +00001730 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001731 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001732 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001733 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001734 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1735 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001736 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001737 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001738
1739 // Declare the functions that find globals in a shared object and then invoke
1740 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001741 AsanRegisterImageGlobals =
1742 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001743 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001744 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001745
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001746 AsanUnregisterImageGlobals =
1747 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001748 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001749 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001750
1751 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1752 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1753 IntptrTy, IntptrTy, IntptrTy));
1754 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1755
1756 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1757 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1758 IntptrTy, IntptrTy, IntptrTy));
1759 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001760}
1761
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001762// Put the metadata and the instrumented global in the same group. This ensures
1763// that the metadata is discarded if the instrumented global is discarded.
1764void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001765 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001766 Module &M = *G->getParent();
1767 Comdat *C = G->getComdat();
1768 if (!C) {
1769 if (!G->hasName()) {
1770 // If G is unnamed, it must be internal. Give it an artificial name
1771 // so we can put it in a comdat.
1772 assert(G->hasLocalLinkage());
1773 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1774 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001775
1776 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1777 std::string Name = G->getName();
1778 Name += InternalSuffix;
1779 C = M.getOrInsertComdat(Name);
1780 } else {
1781 C = M.getOrInsertComdat(G->getName());
1782 }
1783
Reid Klecknerc212cc82017-10-31 16:16:08 +00001784 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF. Also upgrade private
1785 // linkage to internal linkage so that a symbol table entry is emitted. This
1786 // is necessary in order to create the comdat group.
1787 if (TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001788 C->setSelectionKind(Comdat::NoDuplicates);
Reid Klecknerc212cc82017-10-31 16:16:08 +00001789 if (G->hasPrivateLinkage())
1790 G->setLinkage(GlobalValue::InternalLinkage);
1791 }
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001792 G->setComdat(C);
1793 }
1794
1795 assert(G->hasComdat());
1796 Metadata->setComdat(G->getComdat());
1797}
1798
1799// Create a separate metadata global and put it in the appropriate ASan
1800// global registration section.
1801GlobalVariable *
1802AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1803 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001804 auto Linkage = TargetTriple.isOSBinFormatMachO()
1805 ? GlobalVariable::InternalLinkage
1806 : GlobalVariable::PrivateLinkage;
1807 GlobalVariable *Metadata = new GlobalVariable(
1808 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001809 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001810 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001811 return Metadata;
1812}
1813
1814IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001815 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001816 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1817 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1818 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001819
1820 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1821}
1822
1823void AddressSanitizerModule::InstrumentGlobalsCOFF(
1824 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1825 ArrayRef<Constant *> MetadataInitializers) {
1826 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001827 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001828
1829 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001830 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001831 GlobalVariable *G = ExtendedGlobals[i];
1832 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001833 CreateMetadataGlobal(M, Initializer, G->getName());
1834
1835 // The MSVC linker always inserts padding when linking incrementally. We
1836 // cope with that by aligning each struct to its size, which must be a power
1837 // of two.
1838 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1839 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1840 "global metadata will not be padded appropriately");
1841 Metadata->setAlignment(SizeOfGlobalStruct);
1842
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001843 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001844 }
1845}
1846
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001847void AddressSanitizerModule::InstrumentGlobalsELF(
1848 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1849 ArrayRef<Constant *> MetadataInitializers,
1850 const std::string &UniqueModuleId) {
1851 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1852
1853 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1854 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1855 GlobalVariable *G = ExtendedGlobals[i];
1856 GlobalVariable *Metadata =
1857 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1858 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1859 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1860 MetadataGlobals[i] = Metadata;
1861
1862 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1863 }
1864
1865 // Update llvm.compiler.used, adding the new metadata globals. This is
1866 // needed so that during LTO these variables stay alive.
1867 if (!MetadataGlobals.empty())
1868 appendToCompilerUsed(M, MetadataGlobals);
1869
1870 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1871 // to look up the loaded image that contains it. Second, we can store in it
1872 // whether registration has already occurred, to prevent duplicate
1873 // registration.
1874 //
1875 // Common linkage ensures that there is only one global per shared library.
1876 GlobalVariable *RegisteredFlag = new GlobalVariable(
1877 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1878 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1879 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1880
1881 // Create start and stop symbols.
1882 GlobalVariable *StartELFMetadata = new GlobalVariable(
1883 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1884 "__start_" + getGlobalMetadataSection());
1885 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1886 GlobalVariable *StopELFMetadata = new GlobalVariable(
1887 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1888 "__stop_" + getGlobalMetadataSection());
1889 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1890
1891 // Create a call to register the globals with the runtime.
1892 IRB.CreateCall(AsanRegisterElfGlobals,
1893 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1894 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1895 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1896
1897 // We also need to unregister globals at the end, e.g., when a shared library
1898 // gets closed.
1899 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1900 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1901 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1902 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1903 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1904}
1905
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001906void AddressSanitizerModule::InstrumentGlobalsMachO(
1907 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1908 ArrayRef<Constant *> MetadataInitializers) {
1909 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1910
1911 // On recent Mach-O platforms, use a structure which binds the liveness of
1912 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1913 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001914 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001915 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1916
1917 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1918 Constant *Initializer = MetadataInitializers[i];
1919 GlobalVariable *G = ExtendedGlobals[i];
1920 GlobalVariable *Metadata =
1921 CreateMetadataGlobal(M, Initializer, G->getName());
1922
1923 // On recent Mach-O platforms, we emit the global metadata in a way that
1924 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001925 auto LivenessBinder =
1926 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1927 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001928 GlobalVariable *Liveness = new GlobalVariable(
1929 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1930 Twine("__asan_binder_") + G->getName());
1931 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1932 LivenessGlobals[i] = Liveness;
1933 }
1934
1935 // Update llvm.compiler.used, adding the new liveness globals. This is
1936 // needed so that during LTO these variables stay alive. The alternative
1937 // would be to have the linker handling the LTO symbols, but libLTO
1938 // current API does not expose access to the section for each symbol.
1939 if (!LivenessGlobals.empty())
1940 appendToCompilerUsed(M, LivenessGlobals);
1941
1942 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1943 // to look up the loaded image that contains it. Second, we can store in it
1944 // whether registration has already occurred, to prevent duplicate
1945 // registration.
1946 //
1947 // common linkage ensures that there is only one global per shared library.
1948 GlobalVariable *RegisteredFlag = new GlobalVariable(
1949 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1950 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1951 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1952
1953 IRB.CreateCall(AsanRegisterImageGlobals,
1954 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1955
1956 // We also need to unregister globals at the end, e.g., when a shared library
1957 // gets closed.
1958 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1959 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1960 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1961}
1962
1963void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1964 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1965 ArrayRef<Constant *> MetadataInitializers) {
1966 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1967 unsigned N = ExtendedGlobals.size();
1968 assert(N > 0);
1969
1970 // On platforms that don't have a custom metadata section, we emit an array
1971 // of global metadata structures.
1972 ArrayType *ArrayOfGlobalStructTy =
1973 ArrayType::get(MetadataInitializers[0]->getType(), N);
1974 auto AllGlobals = new GlobalVariable(
1975 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1976 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1977
1978 IRB.CreateCall(AsanRegisterGlobals,
1979 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1980 ConstantInt::get(IntptrTy, N)});
1981
1982 // We also need to unregister globals at the end, e.g., when a shared library
1983 // gets closed.
1984 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1985 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1986 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1987 ConstantInt::get(IntptrTy, N)});
1988}
1989
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001990// This function replaces all global variables with new variables that have
1991// trailing redzones. It also creates a function that poisons
1992// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001993// Sets *CtorComdat to true if the global registration code emitted into the
1994// asan constructor is comdat-compatible.
1995bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1996 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001997 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001998
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001999 SmallVector<GlobalVariable *, 16> GlobalsToChange;
2000
Alexey Samsonova02e6642014-05-29 18:40:48 +00002001 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002002 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002003 }
2004
2005 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002006 if (n == 0) {
2007 *CtorComdat = true;
2008 return false;
2009 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002010
Reid Kleckner78565832016-11-29 01:32:21 +00002011 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00002012
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002013 // A global is described by a structure
2014 // size_t beg;
2015 // size_t size;
2016 // size_t size_with_redzone;
2017 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002018 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002019 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002020 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002021 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002022 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002023 StructType *GlobalStructTy =
2024 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002025 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002026 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2027 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002028
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002029 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002030
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002031 // We shouldn't merge same module names, as this string serves as unique
2032 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002033 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002034 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002035
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002036 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002037 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002038 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002039
2040 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002041 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002042 // Create string holding the global name (use global name from metadata
2043 // if it's available, otherwise just write the name of global variable).
2044 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002045 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002046 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002047
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002048 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002049 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002050 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002051 // MinRZ <= RZ <= kMaxGlobalRedzone
2052 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002053 uint64_t RZ = std::max(
2054 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002055 uint64_t RightRedzoneSize = RZ;
2056 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002057 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002058 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002059 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2060
Serge Gueltone38003f2017-05-09 19:31:13 +00002061 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2062 Constant *NewInitializer = ConstantStruct::get(
2063 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002064
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002065 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002066 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2067 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2068 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002069 GlobalVariable *NewGlobal =
2070 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2071 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002072 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002073 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002074
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002075 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2076 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2077 G->isConstant()) {
2078 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2079 if (Seq && Seq->isCString())
2080 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2081 }
2082
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002083 // Transfer the debug info. The payload starts at offset zero so we can
2084 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002085 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002086 G->getDebugInfo(GVs);
2087 for (auto *GV : GVs)
2088 NewGlobal->addDebugInfo(GV);
2089
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002090 Value *Indices2[2];
2091 Indices2[0] = IRB.getInt32(0);
2092 Indices2[1] = IRB.getInt32(0);
2093
2094 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002095 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002096 NewGlobal->takeName(G);
2097 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002098 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002099
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002100 Constant *SourceLoc;
2101 if (!MD.SourceLoc.empty()) {
2102 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2103 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2104 } else {
2105 SourceLoc = ConstantInt::get(IntptrTy, 0);
2106 }
2107
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002108 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2109 GlobalValue *InstrumentedGlobal = NewGlobal;
2110
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002111 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002112 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2113 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002114 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2115 // Create local alias for NewGlobal to avoid crash on ODR between
2116 // instrumented and non-instrumented libraries.
2117 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2118 NameForGlobal + M.getName(), NewGlobal);
2119
2120 // With local aliases, we need to provide another externally visible
2121 // symbol __odr_asan_XXX to detect ODR violation.
2122 auto *ODRIndicatorSym =
2123 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2124 Constant::getNullValue(IRB.getInt8Ty()),
2125 kODRGenPrefix + NameForGlobal, nullptr,
2126 NewGlobal->getThreadLocalMode());
2127
2128 // Set meaningful attributes for indicator symbol.
2129 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2130 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2131 ODRIndicatorSym->setAlignment(1);
2132 ODRIndicator = ODRIndicatorSym;
2133 InstrumentedGlobal = GA;
2134 }
2135
Reid Kleckner01660a32016-11-21 20:40:37 +00002136 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002137 GlobalStructTy,
2138 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002139 ConstantInt::get(IntptrTy, SizeInBytes),
2140 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2141 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002142 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002143 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002144 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002145
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002146 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002147
Kostya Serebryany20343352012-10-17 13:40:06 +00002148 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002149
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002150 Initializers[i] = Initializer;
2151 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002152
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002153 std::string ELFUniqueModuleId =
2154 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2155 : "";
2156
2157 if (!ELFUniqueModuleId.empty()) {
2158 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2159 *CtorComdat = true;
2160 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002161 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002162 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002163 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2164 } else {
2165 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002166 }
2167
Reid Kleckner01660a32016-11-21 20:40:37 +00002168 // Create calls for poisoning before initializers run and unpoisoning after.
2169 if (HasDynamicallyInitializedGlobals)
2170 createInitializerPoisonCalls(M, ModuleName);
2171
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002172 DEBUG(dbgs() << M);
2173 return true;
2174}
2175
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002176int AddressSanitizerModule::GetAsanVersion(const Module &M) const {
2177 int LongSize = M.getDataLayout().getPointerSizeInBits();
2178 bool isAndroid = Triple(M.getTargetTriple()).isAndroid();
2179 int Version = 8;
2180 // 32-bit Android is one version ahead because of the switch to dynamic
2181 // shadow.
2182 Version += (LongSize == 32 && isAndroid);
2183 return Version;
2184}
2185
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002186bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002187 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002188 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002189 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002190 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002191 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002192 initializeCallbacks(M);
2193
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002194 if (CompileKernel)
2195 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002196
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002197 // Create a module constructor. A destructor is created lazily because not all
2198 // platforms, and not all modules need it.
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002199 std::string VersionCheckName =
2200 kAsanVersionCheckNamePrefix + std::to_string(GetAsanVersion(M));
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002201 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2202 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002203 /*InitArgs=*/{}, VersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002204
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002205 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002206 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002207 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002208 if (ClGlobals) {
2209 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002210 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2211 }
2212
2213 // Put the constructor and destructor in comdat if both
2214 // (1) global instrumentation is not TU-specific
2215 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002216 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002217 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2218 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2219 AsanCtorFunction);
2220 if (AsanDtorFunction) {
2221 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2222 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2223 AsanDtorFunction);
2224 }
2225 } else {
2226 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2227 if (AsanDtorFunction)
2228 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002229 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002230
2231 return Changed;
2232}
2233
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002234void AddressSanitizer::initializeCallbacks(Module &M) {
2235 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002236 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002237 // IsWrite, TypeSize and Exp are encoded in the function name.
2238 for (int Exp = 0; Exp < 2; Exp++) {
2239 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2240 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2241 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002242 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002243 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002244
2245 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2246 SmallVector<Type *, 2> Args1{1, IntptrTy};
2247 if (Exp) {
2248 Type *ExpType = Type::getInt32Ty(*C);
2249 Args2.push_back(ExpType);
2250 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002251 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002252 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2253 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2254 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2255 EndingStr,
2256 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002257
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002258 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2259 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2260 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2261 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002262
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002263 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2264 AccessSizeIndex++) {
2265 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2266 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2267 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2268 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2269 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002270
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002271 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2272 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2273 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2274 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2275 }
2276 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002277 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002278
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002279 const std::string MemIntrinCallbackPrefix =
2280 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002281 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002282 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002283 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002284 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002285 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002286 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002287 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002288 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002289 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002290
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002291 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002292 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002293
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002294 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002295 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002296 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002297 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002298 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2299 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2300 StringRef(""), StringRef(""),
2301 /*hasSideEffects=*/true);
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002302 if (Mapping.InGlobal)
2303 AsanShadowGlobal = M.getOrInsertGlobal("__asan_shadow",
2304 ArrayType::get(IRB.getInt8Ty(), 0));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002305}
2306
2307// virtual
2308bool AddressSanitizer::doInitialization(Module &M) {
2309 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002310 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002311
2312 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002313 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002314 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002315 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002316
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002317 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002318 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002319}
2320
Keno Fischere03fae42015-12-05 14:42:34 +00002321bool AddressSanitizer::doFinalization(Module &M) {
2322 GlobalsMD.reset();
2323 return false;
2324}
2325
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002326bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2327 // For each NSObject descendant having a +load method, this method is invoked
2328 // by the ObjC runtime before any of the static constructors is called.
2329 // Therefore we need to instrument such methods with a call to __asan_init
2330 // at the beginning in order to initialize our runtime before any access to
2331 // the shadow memory.
2332 // We cannot just ignore these methods, because they may call other
2333 // instrumented functions.
2334 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002335 Function *AsanInitFunction =
2336 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002337 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002338 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002339 return true;
2340 }
2341 return false;
2342}
2343
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002344void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2345 // Generate code only when dynamic addressing is needed.
Evgeniy Stepanov989299c2017-11-10 22:27:48 +00002346 if (Mapping.Offset != kDynamicShadowSentinel || Mapping.InGlobal)
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002347 return;
2348
2349 IRBuilder<> IRB(&F.front().front());
2350 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2351 kAsanShadowMemoryDynamicAddress, IntptrTy);
2352 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2353}
2354
Reid Kleckner2f907552015-07-21 17:40:14 +00002355void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2356 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2357 // to it as uninteresting. This assumes we haven't started processing allocas
2358 // yet. This check is done up front because iterating the use list in
2359 // isInterestingAlloca would be algorithmically slower.
2360 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2361
2362 // Try to get the declaration of llvm.localescape. If it's not in the module,
2363 // we can exit early.
2364 if (!F.getParent()->getFunction("llvm.localescape")) return;
2365
2366 // Look for a call to llvm.localescape call in the entry block. It can't be in
2367 // any other block.
2368 for (Instruction &I : F.getEntryBlock()) {
2369 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2370 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2371 // We found a call. Mark all the allocas passed in as uninteresting.
2372 for (Value *Arg : II->arg_operands()) {
2373 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2374 assert(AI && AI->isStaticAlloca() &&
2375 "non-static alloca arg to localescape");
2376 ProcessedAllocas[AI] = false;
2377 }
2378 break;
2379 }
2380 }
2381}
2382
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002383bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002384 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002385 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002386 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002387
Etienne Bergeron78582b22016-09-15 15:45:05 +00002388 bool FunctionModified = false;
2389
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002390 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002391 // This function needs to be called even if the function body is not
2392 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002393 if (maybeInsertAsanInitAtFunctionEntry(F))
2394 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002395
2396 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002397 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002398
Etienne Bergeron752f8832016-09-14 17:18:37 +00002399 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2400
2401 initializeCallbacks(*F.getParent());
2402 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002403
Reid Kleckner2f907552015-07-21 17:40:14 +00002404 FunctionStateRAII CleanupObj(this);
2405
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002406 maybeInsertDynamicShadowAtFunctionEntry(F);
2407
Reid Kleckner2f907552015-07-21 17:40:14 +00002408 // We can't instrument allocas used with llvm.localescape. Only static allocas
2409 // can be passed to that intrinsic.
2410 markEscapedLocalAllocas(F);
2411
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002412 // We want to instrument every address only once per basic block (unless there
2413 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002414 SmallSet<Value *, 16> TempsToInstrument;
2415 SmallVector<Instruction *, 16> ToInstrument;
2416 SmallVector<Instruction *, 8> NoReturnCalls;
2417 SmallVector<BasicBlock *, 16> AllBlocks;
2418 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002419 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002420 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002421 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002422 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002423 const TargetLibraryInfo *TLI =
2424 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002425
2426 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002427 for (auto &BB : F) {
2428 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002429 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002430 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002431 for (auto &Inst : BB) {
2432 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002433 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002434 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002435 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002436 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002437 // If we have a mask, skip instrumentation if we've already
2438 // instrumented the full object. But don't add to TempsToInstrument
2439 // because we might get another load/store with a different mask.
2440 if (MaybeMask) {
2441 if (TempsToInstrument.count(Addr))
2442 continue; // We've seen this (whole) temp in the current BB.
2443 } else {
2444 if (!TempsToInstrument.insert(Addr).second)
2445 continue; // We've seen this temp in the current BB.
2446 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002447 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002448 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002449 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2450 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002451 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002452 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002453 // ok, take it.
2454 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002455 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002456 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002457 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002458 // A call inside BB.
2459 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002460 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002461 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002462 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2463 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002464 continue;
2465 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002466 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002467 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002468 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002469 }
2470 }
2471
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002472 bool UseCalls =
2473 CompileKernel ||
2474 (ClInstrumentationWithCallsThreshold >= 0 &&
2475 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002476 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002477 ObjectSizeOpts ObjSizeOpts;
2478 ObjSizeOpts.RoundToAlign = true;
2479 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002480
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002481 // Instrument.
2482 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002483 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002484 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2485 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002486 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002487 instrumentMop(ObjSizeVis, Inst, UseCalls,
2488 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002489 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002490 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002491 }
2492 NumInstrumented++;
2493 }
2494
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002495 FunctionStackPoisoner FSP(F, *this);
2496 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002497
2498 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2499 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002500 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002501 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002502 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002503 }
2504
Alexey Samsonova02e6642014-05-29 18:40:48 +00002505 for (auto Inst : PointerComparisonsOrSubtracts) {
2506 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002507 NumInstrumented++;
2508 }
2509
Etienne Bergeron78582b22016-09-15 15:45:05 +00002510 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2511 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002512
Etienne Bergeron78582b22016-09-15 15:45:05 +00002513 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2514 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002515
Etienne Bergeron78582b22016-09-15 15:45:05 +00002516 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002517}
2518
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002519// Workaround for bug 11395: we don't want to instrument stack in functions
2520// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2521// FIXME: remove once the bug 11395 is fixed.
2522bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2523 if (LongSize != 32) return false;
2524 CallInst *CI = dyn_cast<CallInst>(I);
2525 if (!CI || !CI->isInlineAsm()) return false;
2526 if (CI->getNumArgOperands() <= 5) return false;
2527 // We have inline assembly with quite a few arguments.
2528 return true;
2529}
2530
2531void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2532 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002533 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2534 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002535 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2536 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002537 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002538 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002539 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002540 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002541 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002542 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002543 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2544 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002545 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002546 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2547 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002548 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002549 }
2550
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002551 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2552 std::ostringstream Name;
2553 Name << kAsanSetShadowPrefix;
2554 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002555 AsanSetShadowFunc[Val] =
2556 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002557 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002558 }
2559
Yury Gribov98b18592015-05-28 07:51:49 +00002560 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002561 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002562 AsanAllocasUnpoisonFunc =
2563 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002564 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002565}
2566
Vitaly Buka793913c2016-08-29 18:17:21 +00002567void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2568 ArrayRef<uint8_t> ShadowBytes,
2569 size_t Begin, size_t End,
2570 IRBuilder<> &IRB,
2571 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002572 if (Begin >= End)
2573 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002574
2575 const size_t LargestStoreSizeInBytes =
2576 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2577
2578 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2579
2580 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002581 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2582 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2583 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002584 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002585 if (!ShadowMask[i]) {
2586 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002587 ++i;
2588 continue;
2589 }
2590
2591 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2592 // Fit store size into the range.
2593 while (StoreSizeInBytes > End - i)
2594 StoreSizeInBytes /= 2;
2595
2596 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002597 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002598 while (j <= StoreSizeInBytes / 2)
2599 StoreSizeInBytes /= 2;
2600 }
2601
2602 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002603 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2604 if (IsLittleEndian)
2605 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2606 else
2607 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002608 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002609
2610 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2611 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002612 IRB.CreateAlignedStore(
2613 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002614
2615 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002616 }
2617}
2618
Vitaly Buka793913c2016-08-29 18:17:21 +00002619void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2620 ArrayRef<uint8_t> ShadowBytes,
2621 IRBuilder<> &IRB, Value *ShadowBase) {
2622 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2623}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002624
Vitaly Buka793913c2016-08-29 18:17:21 +00002625void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2626 ArrayRef<uint8_t> ShadowBytes,
2627 size_t Begin, size_t End,
2628 IRBuilder<> &IRB, Value *ShadowBase) {
2629 assert(ShadowMask.size() == ShadowBytes.size());
2630 size_t Done = Begin;
2631 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2632 if (!ShadowMask[i]) {
2633 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002634 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002635 }
2636 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002637 if (!AsanSetShadowFunc[Val])
2638 continue;
2639
2640 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002641 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002642 }
2643
2644 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002645 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002646 IRB.CreateCall(AsanSetShadowFunc[Val],
2647 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2648 ConstantInt::get(IntptrTy, j - i)});
2649 Done = j;
2650 }
2651 }
2652
Vitaly Buka793913c2016-08-29 18:17:21 +00002653 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002654}
2655
Kostya Serebryany6805de52013-09-10 13:16:56 +00002656// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2657// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2658static int StackMallocSizeClass(uint64_t LocalStackSize) {
2659 assert(LocalStackSize <= kMaxStackMallocSize);
2660 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002661 for (int i = 0;; i++, MaxSize *= 2)
2662 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002663 llvm_unreachable("impossible LocalStackSize");
2664}
2665
Vitaly Buka74443f02017-07-18 22:28:03 +00002666void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002667 Instruction *CopyInsertPoint = &F.front().front();
2668 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2669 // Insert after the dynamic shadow location is determined
2670 CopyInsertPoint = CopyInsertPoint->getNextNode();
2671 assert(CopyInsertPoint);
2672 }
2673 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002674 const DataLayout &DL = F.getParent()->getDataLayout();
2675 for (Argument &Arg : F.args()) {
2676 if (Arg.hasByValAttr()) {
2677 Type *Ty = Arg.getType()->getPointerElementType();
2678 unsigned Align = Arg.getParamAlignment();
2679 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2680
2681 const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2682 "Arg" + llvm::to_string(Arg.getArgNo());
2683 AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2684 AI->setAlignment(Align);
2685 Arg.replaceAllUsesWith(AI);
2686
2687 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2688 IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2689 }
2690 }
2691}
2692
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002693PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2694 Value *ValueIfTrue,
2695 Instruction *ThenTerm,
2696 Value *ValueIfFalse) {
2697 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2698 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2699 PHI->addIncoming(ValueIfFalse, CondBlock);
2700 BasicBlock *ThenBlock = ThenTerm->getParent();
2701 PHI->addIncoming(ValueIfTrue, ThenBlock);
2702 return PHI;
2703}
2704
2705Value *FunctionStackPoisoner::createAllocaForLayout(
2706 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2707 AllocaInst *Alloca;
2708 if (Dynamic) {
2709 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2710 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2711 "MyAlloca");
2712 } else {
2713 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2714 nullptr, "MyAlloca");
2715 assert(Alloca->isStaticAlloca());
2716 }
2717 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2718 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2719 Alloca->setAlignment(FrameAlignment);
2720 return IRB.CreatePointerCast(Alloca, IntptrTy);
2721}
2722
Yury Gribov98b18592015-05-28 07:51:49 +00002723void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2724 BasicBlock &FirstBB = *F.begin();
2725 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2726 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2727 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2728 DynamicAllocaLayout->setAlignment(32);
2729}
2730
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002731void FunctionStackPoisoner::processDynamicAllocas() {
2732 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2733 assert(DynamicAllocaPoisonCallVec.empty());
2734 return;
2735 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002736
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002737 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2738 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002739 assert(APC.InsBefore);
2740 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002741 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002742 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002743
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002744 IRBuilder<> IRB(APC.InsBefore);
2745 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002746 // Dynamic allocas will be unpoisoned unconditionally below in
2747 // unpoisonDynamicAllocas.
2748 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002749 }
2750
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002751 // Handle dynamic allocas.
2752 createDynamicAllocasInitStorage();
2753 for (auto &AI : DynamicAllocaVec)
2754 handleDynamicAllocaCall(AI);
2755 unpoisonDynamicAllocas();
2756}
Yury Gribov98b18592015-05-28 07:51:49 +00002757
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002758void FunctionStackPoisoner::processStaticAllocas() {
2759 if (AllocaVec.empty()) {
2760 assert(StaticAllocaPoisonCallVec.empty());
2761 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002762 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002763
Kostya Serebryany6805de52013-09-10 13:16:56 +00002764 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002765 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002766 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002767 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002768
2769 Instruction *InsBefore = AllocaVec[0];
2770 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002771 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002772
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002773 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2774 // debug info is broken, because only entry-block allocas are treated as
2775 // regular stack slots.
2776 auto InsBeforeB = InsBefore->getParent();
2777 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002778 for (auto *AI : StaticAllocasToMoveUp)
2779 if (AI->getParent() == InsBeforeB)
2780 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002781
Reid Kleckner2f907552015-07-21 17:40:14 +00002782 // If we have a call to llvm.localescape, keep it in the entry block.
2783 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2784
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002785 SmallVector<ASanStackVariableDescription, 16> SVD;
2786 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002787 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002788 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002789 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002790 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002791 AI->getAlignment(),
2792 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002793 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002794 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002795 SVD.push_back(D);
2796 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002797
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002798 // Minimal header size (left redzone) is 4 pointers,
2799 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2800 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002801 const ASanStackFrameLayout &L =
2802 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002803
Vitaly Buka5910a922016-10-18 23:29:52 +00002804 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2805 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2806 for (auto &Desc : SVD)
2807 AllocaToSVDMap[Desc.AI] = &Desc;
2808
2809 // Update SVD with information from lifetime intrinsics.
2810 for (const auto &APC : StaticAllocaPoisonCallVec) {
2811 assert(APC.InsBefore);
2812 assert(APC.AI);
2813 assert(ASan.isInterestingAlloca(*APC.AI));
2814 assert(APC.AI->isStaticAlloca());
2815
2816 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2817 Desc.LifetimeSize = Desc.Size;
2818 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2819 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2820 if (LifetimeLoc->getFile() == FnLoc->getFile())
2821 if (unsigned Line = LifetimeLoc->getLine())
2822 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2823 }
2824 }
2825 }
2826
2827 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2828 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002829 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002830 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2831 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002832 bool DoDynamicAlloca = ClDynamicAllocaStack;
2833 // Don't do dynamic alloca or stack malloc if:
2834 // 1) There is inline asm: too often it makes assumptions on which registers
2835 // are available.
2836 // 2) There is a returns_twice call (typically setjmp), which is
2837 // optimization-hostile, and doesn't play well with introduced indirect
2838 // register-relative calculation of local variable addresses.
2839 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2840 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002841
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002842 Value *StaticAlloca =
2843 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2844
2845 Value *FakeStack;
2846 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002847
2848 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002849 // void *FakeStack = __asan_option_detect_stack_use_after_return
2850 // ? __asan_stack_malloc_N(LocalStackSize)
2851 // : nullptr;
2852 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002853 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2854 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2855 Value *UseAfterReturnIsEnabled =
2856 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002857 Constant::getNullValue(IRB.getInt32Ty()));
2858 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002859 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002860 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002861 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002862 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2863 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2864 Value *FakeStackValue =
2865 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2866 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002867 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002868 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002869 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002870 ConstantInt::get(IntptrTy, 0));
2871
2872 Value *NoFakeStack =
2873 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2874 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2875 IRBIf.SetInsertPoint(Term);
2876 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2877 Value *AllocaValue =
2878 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2879 IRB.SetInsertPoint(InsBefore);
2880 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2881 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2882 } else {
2883 // void *FakeStack = nullptr;
2884 // void *LocalStackBase = alloca(LocalStackSize);
2885 FakeStack = ConstantInt::get(IntptrTy, 0);
2886 LocalStackBase =
2887 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002888 }
2889
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002890 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002891 for (const auto &Desc : SVD) {
2892 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002893 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002894 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002895 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002896 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002897 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002898 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002899
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002900 // The left-most redzone has enough space for at least 4 pointers.
2901 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002902 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2903 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2904 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002905 // Write the frame description constant to redzone[1].
2906 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002907 IRB.CreateAdd(LocalStackBase,
2908 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2909 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002910 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002911 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002912 /*AllowMerging*/ true);
2913 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002914 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002915 // Write the PC to redzone[2].
2916 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002917 IRB.CreateAdd(LocalStackBase,
2918 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2919 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002920 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002921
Vitaly Buka793913c2016-08-29 18:17:21 +00002922 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2923
2924 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002925 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002926 // As mask we must use most poisoned case: red zones and after scope.
2927 // As bytes we can use either the same or just red zones only.
2928 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2929
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002930 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002931 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2932
2933 // Poison static allocas near lifetime intrinsics.
2934 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002935 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002936 assert(Desc.Offset % L.Granularity == 0);
2937 size_t Begin = Desc.Offset / L.Granularity;
2938 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2939
2940 IRBuilder<> IRB(APC.InsBefore);
2941 copyToShadow(ShadowAfterScope,
2942 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2943 IRB, ShadowBase);
2944 }
2945 }
2946
2947 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002948 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002949
Kostya Serebryany530e2072013-12-23 14:15:08 +00002950 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002951 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002952 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002953 // Mark the current frame as retired.
2954 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2955 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002956 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002957 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002958 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002959 // // In use-after-return mode, poison the whole stack frame.
2960 // if StackMallocIdx <= 4
2961 // // For small sizes inline the whole thing:
2962 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002963 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002964 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002965 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002966 // else
2967 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002968 Value *Cmp =
2969 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002970 TerminatorInst *ThenTerm, *ElseTerm;
2971 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2972
2973 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002974 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002975 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002976 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2977 kAsanStackUseAfterReturnMagic);
2978 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2979 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002980 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002981 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002982 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2983 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2984 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2985 IRBPoison.CreateStore(
2986 Constant::getNullValue(IRBPoison.getInt8Ty()),
2987 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2988 } else {
2989 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002990 IRBPoison.CreateCall(
2991 AsanStackFreeFunc[StackMallocIdx],
2992 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002993 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002994
2995 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002996 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002997 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002998 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002999 }
3000 }
3001
Kostya Serebryany09959942012-10-19 06:20:53 +00003002 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003003 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00003004}
Alexey Samsonov261177a2012-12-04 01:34:23 +00003005
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003006void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00003007 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00003008 // For now just insert the call to ASan runtime.
3009 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
3010 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00003011 IRB.CreateCall(
3012 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
3013 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00003014}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003015
3016// Handling llvm.lifetime intrinsics for a given %alloca:
3017// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
3018// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
3019// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
3020// could be poisoned by previous llvm.lifetime.end instruction, as the
3021// variable may go in and out of scope several times, e.g. in loops).
3022// (3) if we poisoned at least one %alloca in a function,
3023// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003024
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003025AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
3026 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00003027 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00003028 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003029 // See if we've already calculated (or started to calculate) alloca for a
3030 // given value.
3031 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003032 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003033 // Store 0 while we're calculating alloca for value V to avoid
3034 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00003035 AllocaForValue[V] = nullptr;
3036 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003037 if (CastInst *CI = dyn_cast<CastInst>(V))
3038 Res = findAllocaForValue(CI->getOperand(0));
3039 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003040 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003041 // Allow self-referencing phi-nodes.
3042 if (IncValue == PN) continue;
3043 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3044 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003045 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3046 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003047 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003048 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003049 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3050 Res = findAllocaForValue(EP->getPointerOperand());
3051 } else {
3052 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003053 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003054 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003055 return Res;
3056}
Yury Gribov55441bb2014-11-21 10:29:50 +00003057
Yury Gribov98b18592015-05-28 07:51:49 +00003058void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003059 IRBuilder<> IRB(AI);
3060
Yury Gribov55441bb2014-11-21 10:29:50 +00003061 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3062 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3063
3064 Value *Zero = Constant::getNullValue(IntptrTy);
3065 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3066 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003067
3068 // Since we need to extend alloca with additional memory to locate
3069 // redzones, and OldSize is number of allocated blocks with
3070 // ElementSize size, get allocated memory size in bytes by
3071 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003072 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003073 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003074 Value *OldSize =
3075 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3076 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003077
3078 // PartialSize = OldSize % 32
3079 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3080
3081 // Misalign = kAllocaRzSize - PartialSize;
3082 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3083
3084 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3085 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3086 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3087
3088 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3089 // Align is added to locate left redzone, PartialPadding for possible
3090 // partial redzone and kAllocaRzSize for right redzone respectively.
3091 Value *AdditionalChunkSize = IRB.CreateAdd(
3092 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3093
3094 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3095
3096 // Insert new alloca with new NewSize and Align params.
3097 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3098 NewAlloca->setAlignment(Align);
3099
3100 // NewAddress = Address + Align
3101 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3102 ConstantInt::get(IntptrTy, Align));
3103
Yury Gribov98b18592015-05-28 07:51:49 +00003104 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003105 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003106
3107 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3108 // for unpoisoning stuff.
3109 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3110
Yury Gribov55441bb2014-11-21 10:29:50 +00003111 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3112
Yury Gribov98b18592015-05-28 07:51:49 +00003113 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003114 AI->replaceAllUsesWith(NewAddressPtr);
3115
Yury Gribov98b18592015-05-28 07:51:49 +00003116 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003117 AI->eraseFromParent();
3118}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003119
3120// isSafeAccess returns true if Addr is always inbounds with respect to its
3121// base object. For example, it is a field access or an array access with
3122// constant inbounds index.
3123bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3124 Value *Addr, uint64_t TypeSize) const {
3125 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3126 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003127 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003128 int64_t Offset = SizeOffset.second.getSExtValue();
3129 // Three checks are required to ensure safety:
3130 // . Offset >= 0 (since the offset is given from the base ptr)
3131 // . Size >= Offset (unsigned)
3132 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003133 return Offset >= 0 && Size >= uint64_t(Offset) &&
3134 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003135}