blob: 81ad5b477e0061140312683335d89d89194e420c [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";
139static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000140 "__asan_version_mismatch_check_v8";
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
Kostya Serebryany874dae62012-07-16 16:15:40 +0000210// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000211// in any given BB. Normally, this should be set to unlimited (INT_MAX),
212// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
213// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000214static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
215 "asan-max-ins-per-bb", cl::init(10000),
216 cl::desc("maximal number of instructions to instrument in any given BB"),
217 cl::Hidden);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000218
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000219// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000220static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
221 cl::Hidden, cl::init(true));
Vitaly Buka1f9e1352016-08-20 20:23:50 +0000222static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
223 "asan-max-inline-poisoning-size",
224 cl::desc(
225 "Inline shadow poisoning for blocks up to the given size in bytes."),
226 cl::Hidden, cl::init(64));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000227
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000228static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Mike Aizatsky243b71f2016-04-21 22:00:13 +0000229 cl::desc("Check stack-use-after-return"),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000230 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000231
Vitaly Buka74443f02017-07-18 22:28:03 +0000232static cl::opt<bool> ClRedzoneByvalArgs("asan-redzone-byval-args",
233 cl::desc("Create redzones for byval "
234 "arguments (extra copy "
235 "required)"), cl::Hidden,
236 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000237
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000238static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
239 cl::desc("Check stack-use-after-scope"),
240 cl::Hidden, cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000241
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000242// This flag may need to be replaced with -f[no]asan-globals.
243static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000244 cl::desc("Handle global objects"), cl::Hidden,
245 cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000246
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000247static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000248 cl::desc("Handle C++ initializer order"),
249 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000250
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000251static cl::opt<bool> ClInvalidPointerPairs(
252 "asan-detect-invalid-pointer-pair",
253 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
254 cl::init(false));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000255
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000256static cl::opt<unsigned> ClRealignStack(
257 "asan-realign-stack",
258 cl::desc("Realign stack to the value of this flag (power of two)"),
259 cl::Hidden, cl::init(32));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000260
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000261static cl::opt<int> ClInstrumentationWithCallsThreshold(
262 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000263 cl::desc(
264 "If the function being instrumented contains more than "
265 "this number of memory accesses, use callbacks instead of "
266 "inline checks (-1 means never use callbacks)."),
267 cl::Hidden, cl::init(7000));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000268
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000269static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000270 "asan-memory-access-callback-prefix",
271 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
272 cl::init("__asan_"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000273
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000274static cl::opt<bool>
275 ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
276 cl::desc("instrument dynamic allocas"),
277 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000278
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000279static cl::opt<bool> ClSkipPromotableAllocas(
280 "asan-skip-promotable-allocas",
281 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
282 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000283
284// These flags allow to change the shadow mapping.
285// The shadow mapping looks like
Ryan Govostes3f37df02016-05-06 10:25:22 +0000286// Shadow = (Mem >> scale) + offset
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000287
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000288static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000289 cl::desc("scale of asan shadow mapping"),
290 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000291
Ryan Govostes6194ae62016-05-06 11:22:11 +0000292static cl::opt<unsigned long long> ClMappingOffset(
293 "asan-mapping-offset",
294 cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
295 cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000296
297// Optimization flags. Not user visible, used mostly for testing
298// and benchmarking the tool.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000299
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
301 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000302
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000303static cl::opt<bool> ClOptSameTemp(
304 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
305 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000306
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000307static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000308 cl::desc("Don't instrument scalar globals"),
309 cl::Hidden, cl::init(true));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000310
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311static cl::opt<bool> ClOptStack(
312 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
313 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000314
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000315static cl::opt<bool> ClDynamicAllocaStack(
316 "asan-stack-dynamic-alloca",
317 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000318 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000319
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000320static cl::opt<uint32_t> ClForceExperiment(
321 "asan-force-experiment",
322 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
323 cl::init(0));
324
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000325static cl::opt<bool>
326 ClUsePrivateAliasForGlobals("asan-use-private-alias",
327 cl::desc("Use private aliases for global"
328 " variables"),
329 cl::Hidden, cl::init(false));
330
Ryan Govostese51401b2016-07-05 21:53:08 +0000331static cl::opt<bool>
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000332 ClUseGlobalsGC("asan-globals-live-support",
333 cl::desc("Use linker features to support dead "
334 "code stripping of globals"),
335 cl::Hidden, cl::init(true));
Ryan Govostese51401b2016-07-05 21:53:08 +0000336
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000337// This is on by default even though there is a bug in gold:
338// https://sourceware.org/bugzilla/show_bug.cgi?id=19002
339static cl::opt<bool>
340 ClWithComdat("asan-with-comdat",
341 cl::desc("Place ASan constructors in comdat sections"),
342 cl::Hidden, cl::init(true));
343
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000344// Debug flags.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000345
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000346static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
347 cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000348
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000349static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
350 cl::Hidden, cl::init(0));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000351
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000352static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
353 cl::desc("Debug func"));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000354
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000355static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
356 cl::Hidden, cl::init(-1));
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000357
Etienne Bergeron7f0e3152016-09-22 14:57:24 +0000358static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000359 cl::Hidden, cl::init(-1));
360
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000361STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
362STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000363STATISTIC(NumOptimizedAccessesToGlobalVar,
364 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000365STATISTIC(NumOptimizedAccessesToStackVar,
366 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000367
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000368namespace {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000369
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000370/// Frontend-provided metadata for source location.
371struct LocationMetadata {
372 StringRef Filename;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000373 int LineNo = 0;
374 int ColumnNo = 0;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000375
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000376 LocationMetadata() = default;
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000377
378 bool empty() const { return Filename.empty(); }
379
380 void parse(MDNode *MDN) {
381 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000382 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
383 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000384 LineNo =
385 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
386 ColumnNo =
387 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000388 }
389};
390
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000391/// Frontend-provided metadata for global variables.
392class GlobalsMetadata {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000393public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000394 struct Entry {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000395 LocationMetadata SourceLoc;
396 StringRef Name;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000397 bool IsDynInit = false;
398 bool IsBlacklisted = false;
399
400 Entry() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000401 };
402
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000403 GlobalsMetadata() = default;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000404
Keno Fischere03fae42015-12-05 14:42:34 +0000405 void reset() {
406 inited_ = false;
407 Entries.clear();
408 }
409
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000410 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000411 assert(!inited_);
412 inited_ = true;
413 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000414 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000415 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000416 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000417 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000418 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000419 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000420 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000421 // We can already have an entry for GV if it was merged with another
422 // global.
423 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000424 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
425 E.SourceLoc.parse(Loc);
426 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
427 E.Name = Name->getString();
428 ConstantInt *IsDynInit =
429 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000430 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000431 ConstantInt *IsBlacklisted =
432 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000433 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000434 }
435 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000436
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000437 /// Returns metadata entry for a given global.
438 Entry get(GlobalVariable *G) const {
439 auto Pos = Entries.find(G);
440 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000441 }
442
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000443private:
444 bool inited_ = false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000445 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000446};
447
Alexey Samsonov1345d352013-01-16 13:23:28 +0000448/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000449/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000450struct ShadowMapping {
451 int Scale;
452 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000453 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000454};
455
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000456} // end anonymous namespace
457
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000458static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
459 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000460 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000461 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000462 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000463 bool IsNetBSD = TargetTriple.isOSNetBSD();
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000464 bool IsPS4CPU = TargetTriple.isPS4CPU();
Simon Pilgrima2794102014-11-22 19:12:10 +0000465 bool IsLinux = TargetTriple.isOSLinux();
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000466 bool IsPPC64 = TargetTriple.getArch() == Triple::ppc64 ||
467 TargetTriple.getArch() == Triple::ppc64le;
468 bool IsSystemZ = TargetTriple.getArch() == Triple::systemz;
469 bool IsX86 = TargetTriple.getArch() == Triple::x86;
470 bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
471 bool IsMIPS32 = TargetTriple.getArch() == Triple::mips ||
472 TargetTriple.getArch() == Triple::mipsel;
473 bool IsMIPS64 = TargetTriple.getArch() == Triple::mips64 ||
474 TargetTriple.getArch() == Triple::mips64el;
475 bool IsAArch64 = TargetTriple.getArch() == Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000476 bool IsWindows = TargetTriple.isOSWindows();
Petr Hosek6f168572017-02-27 22:49:37 +0000477 bool IsFuchsia = TargetTriple.isOSFuchsia();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000478
479 ShadowMapping Mapping;
480
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000481 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000482 // Android is always PIE, which means that the beginning of the address
483 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000484 if (IsAndroid)
485 Mapping.Offset = 0;
486 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000487 Mapping.Offset = kMIPS32_ShadowOffset32;
488 else if (IsFreeBSD)
489 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000490 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000491 // If we're targeting iOS and x86, the binary is built for iOS simulator.
492 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000493 else if (IsWindows)
494 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000495 else
496 Mapping.Offset = kDefaultShadowOffset32;
497 } else { // LongSize == 64
Petr Hosek6f168572017-02-27 22:49:37 +0000498 // Fuchsia is always PIE, which means that the beginning of the address
499 // space is always available.
500 if (IsFuchsia)
501 Mapping.Offset = 0;
502 else if (IsPPC64)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000503 Mapping.Offset = kPPC64_ShadowOffset64;
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000504 else if (IsSystemZ)
505 Mapping.Offset = kSystemZ_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000506 else if (IsFreeBSD)
507 Mapping.Offset = kFreeBSD_ShadowOffset64;
Kamil Rytarowskia9f404f82017-08-28 22:13:52 +0000508 else if (IsNetBSD)
509 Mapping.Offset = kNetBSD_ShadowOffset64;
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000510 else if (IsPS4CPU)
511 Mapping.Offset = kPS4CPU_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000512 else if (IsLinux && IsX86_64) {
513 if (IsKasan)
514 Mapping.Offset = kLinuxKasan_ShadowOffset64;
515 else
516 Mapping.Offset = kSmallX86_64ShadowOffset;
Etienne Bergeron70684f92016-06-21 15:07:29 +0000517 } else if (IsWindows && IsX86_64) {
518 Mapping.Offset = kWindowsShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000519 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000520 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000521 else if (IsIOS)
522 // If we're targeting iOS and x86, the binary is built for iOS simulator.
Anna Zaks9a6a6ef2016-10-05 20:34:13 +0000523 // We are using dynamic shadow offset on the 64-bit devices.
524 Mapping.Offset =
525 IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
Renato Golinaf213722015-02-03 11:20:45 +0000526 else if (IsAArch64)
527 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000528 else
529 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000530 }
531
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000532 if (ClForceDynamicShadow) {
533 Mapping.Offset = kDynamicShadowSentinel;
534 }
535
Alexey Samsonov1345d352013-01-16 13:23:28 +0000536 Mapping.Scale = kDefaultShadowScale;
Ryan Govostes3f37df02016-05-06 10:25:22 +0000537 if (ClMappingScale.getNumOccurrences() > 0) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000538 Mapping.Scale = ClMappingScale;
539 }
540
Ryan Govostes3f37df02016-05-06 10:25:22 +0000541 if (ClMappingOffset.getNumOccurrences() > 0) {
542 Mapping.Offset = ClMappingOffset;
543 }
544
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000545 // OR-ing shadow offset if more efficient (at least on x86) if the offset
546 // is a power of two, but on ppc64 we have to use add since the shadow
Marcin Koscielnicki57290f92016-04-30 09:57:34 +0000547 // offset is not necessary 1/8-th of the address space. On SystemZ,
548 // we could OR the constant in a single instruction, but it's more
549 // efficient to load it once and use indexed addressing.
Filipe Cabecinhas33dd4862017-02-23 17:10:28 +0000550 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ && !IsPS4CPU &&
551 !(Mapping.Offset & (Mapping.Offset - 1)) &&
552 Mapping.Offset != kDynamicShadowSentinel;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000553
Alexey Samsonov1345d352013-01-16 13:23:28 +0000554 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000555}
556
Alexey Samsonov1345d352013-01-16 13:23:28 +0000557static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000558 // Redzone used for stack and globals is at least 32 bytes.
559 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000560 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000561}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000562
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000563namespace {
564
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000565/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000566struct AddressSanitizer : public FunctionPass {
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000567 // Pass identification, replacement for typeid
568 static char ID;
569
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000570 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
571 bool UseAfterScope = false)
Yury Gribovd7731982015-11-11 10:36:49 +0000572 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000573 Recover(Recover || ClRecover),
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000574 UseAfterScope(UseAfterScope || ClUseAfterScope) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000575 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
576 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000577
Mehdi Amini117296c2016-10-01 02:56:57 +0000578 StringRef getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000579 return "AddressSanitizerFunctionPass";
580 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000581
Yury Gribov3ae427d2014-12-01 08:47:58 +0000582 void getAnalysisUsage(AnalysisUsage &AU) const override {
583 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000584 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000585 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000586
Vitaly Buka21a9e572016-07-28 22:50:50 +0000587 uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000588 uint64_t ArraySize = 1;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000589 if (AI.isArrayAllocation()) {
590 const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000591 assert(CI && "non-constant array size");
592 ArraySize = CI->getZExtValue();
593 }
Vitaly Buka21a9e572016-07-28 22:50:50 +0000594 Type *Ty = AI.getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000595 uint64_t SizeInBytes =
Vitaly Buka21a9e572016-07-28 22:50:50 +0000596 AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000597 return SizeInBytes * ArraySize;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000598 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000599
Anna Zaks8ed1d812015-02-27 03:12:36 +0000600 /// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +0000601 bool isInterestingAlloca(const AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000602
Anna Zaks8ed1d812015-02-27 03:12:36 +0000603 /// If it is an interesting memory access, return the PointerOperand
604 /// and set IsWrite/Alignment. Otherwise return nullptr.
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000605 /// MaybeMask is an output parameter for the mask Value, if we're looking at a
606 /// masked load/store.
Anna Zaks8ed1d812015-02-27 03:12:36 +0000607 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +0000608 uint64_t *TypeSize, unsigned *Alignment,
609 Value **MaybeMask = nullptr);
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000610
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000611 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000612 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000613 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000614 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
615 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000616 Value *SizeArgument, bool UseCalls, uint32_t Exp);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +0000617 void instrumentUnusualSizeOrAlignment(Instruction *I,
618 Instruction *InsertBefore, Value *Addr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000619 uint32_t TypeSize, bool IsWrite,
620 Value *SizeArgument, bool UseCalls,
621 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000622 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
623 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000624 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000625 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000626 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000627 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000628 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000629 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000630 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000631 void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000632 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000633 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000634 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000635
Yury Gribov3ae427d2014-12-01 08:47:58 +0000636 DominatorTree &getDominatorTree() const { return *DT; }
637
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000638private:
639 friend struct FunctionStackPoisoner;
640
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000641 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000642
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000643 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000644 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000645 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
646 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000647
Reid Kleckner2f907552015-07-21 17:40:14 +0000648 /// Helper to cleanup per-function state.
649 struct FunctionStateRAII {
650 AddressSanitizer *Pass;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000651
Reid Kleckner2f907552015-07-21 17:40:14 +0000652 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
653 assert(Pass->ProcessedAllocas.empty() &&
654 "last pass forgot to clear cache");
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000655 assert(!Pass->LocalDynamicShadow);
Reid Kleckner2f907552015-07-21 17:40:14 +0000656 }
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000657
Etienne Bergeron0ca05682016-09-30 17:46:32 +0000658 ~FunctionStateRAII() {
659 Pass->LocalDynamicShadow = nullptr;
660 Pass->ProcessedAllocas.clear();
661 }
Reid Kleckner2f907552015-07-21 17:40:14 +0000662 };
663
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000664 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000665 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000666 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000667 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000668 bool Recover;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000669 bool UseAfterScope;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000670 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000671 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000672 DominatorTree *DT;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000673 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000674 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000675
676 // These arrays is indexed by AccessIsWrite, Experiment and log2(AccessSize).
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000677 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
678 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000679
680 // These arrays is indexed by AccessIsWrite and Experiment.
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000681 Function *AsanErrorCallbackSized[2][2];
682 Function *AsanMemoryAccessCallbackSized[2][2];
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000683
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000684 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000685 InlineAsm *EmptyAsm;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000686 Value *LocalDynamicShadow = nullptr;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000687 GlobalsMetadata GlobalsMD;
Vitaly Buka21a9e572016-07-28 22:50:50 +0000688 DenseMap<const AllocaInst *, bool> ProcessedAllocas;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000689};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000690
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000691class AddressSanitizerModule : public ModulePass {
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000692public:
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000693 // Pass identification, replacement for typeid
694 static char ID;
695
Yury Gribovd7731982015-11-11 10:36:49 +0000696 explicit AddressSanitizerModule(bool CompileKernel = false,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000697 bool Recover = false,
698 bool UseGlobalsGC = true)
Yury Gribovd7731982015-11-11 10:36:49 +0000699 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000700 Recover(Recover || ClRecover),
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000701 UseGlobalsGC(UseGlobalsGC && ClUseGlobalsGC),
702 // Not a typo: ClWithComdat is almost completely pointless without
703 // ClUseGlobalsGC (because then it only works on modules without
704 // globals, which are rare); it is a prerequisite for ClUseGlobalsGC;
705 // and both suffer from gold PR19002 for which UseGlobalsGC constructor
706 // argument is designed as workaround. Therefore, disable both
707 // ClWithComdat and ClUseGlobalsGC unless the frontend says it's ok to
708 // do globals-gc.
709 UseCtorComdat(UseGlobalsGC && ClWithComdat) {}
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000710
Craig Topper3e4c6972014-03-05 09:10:37 +0000711 bool runOnModule(Module &M) override;
Mehdi Amini117296c2016-10-01 02:56:57 +0000712 StringRef getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000713
Mehdi Amini117296c2016-10-01 02:56:57 +0000714private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000715 void initializeCallbacks(Module &M);
716
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000717 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000718 void InstrumentGlobalsCOFF(IRBuilder<> &IRB, Module &M,
719 ArrayRef<GlobalVariable *> ExtendedGlobals,
720 ArrayRef<Constant *> MetadataInitializers);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000721 void InstrumentGlobalsELF(IRBuilder<> &IRB, Module &M,
722 ArrayRef<GlobalVariable *> ExtendedGlobals,
723 ArrayRef<Constant *> MetadataInitializers,
724 const std::string &UniqueModuleId);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000725 void InstrumentGlobalsMachO(IRBuilder<> &IRB, Module &M,
726 ArrayRef<GlobalVariable *> ExtendedGlobals,
727 ArrayRef<Constant *> MetadataInitializers);
728 void
729 InstrumentGlobalsWithMetadataArray(IRBuilder<> &IRB, Module &M,
730 ArrayRef<GlobalVariable *> ExtendedGlobals,
731 ArrayRef<Constant *> MetadataInitializers);
732
733 GlobalVariable *CreateMetadataGlobal(Module &M, Constant *Initializer,
734 StringRef OriginalName);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000735 void SetComdatForGlobalMetadata(GlobalVariable *G, GlobalVariable *Metadata,
736 StringRef InternalSuffix);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +0000737 IRBuilder<> CreateAsanModuleDtor(Module &M);
738
Kostya Serebryany20a79972012-11-22 03:18:50 +0000739 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000740 bool ShouldUseMachOGlobalsSection() const;
Reid Kleckner01660a32016-11-21 20:40:37 +0000741 StringRef getGlobalMetadataSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000742 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000743 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000744 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000745 return RedzoneSizeForScale(Mapping.Scale);
746 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000747
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000748 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000749 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000750 bool Recover;
Evgeniy Stepanov9e536082017-04-24 19:34:13 +0000751 bool UseGlobalsGC;
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +0000752 bool UseCtorComdat;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000753 Type *IntptrTy;
754 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000755 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000756 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000757 Function *AsanPoisonGlobals;
758 Function *AsanUnpoisonGlobals;
759 Function *AsanRegisterGlobals;
760 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000761 Function *AsanRegisterImageGlobals;
762 Function *AsanUnregisterImageGlobals;
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000763 Function *AsanRegisterElfGlobals;
764 Function *AsanUnregisterElfGlobals;
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +0000765
766 Function *AsanCtorFunction = nullptr;
767 Function *AsanDtorFunction = nullptr;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000768};
769
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000770// Stack poisoning does not play well with exception handling.
771// When an exception is thrown, we essentially bypass the code
772// that unpoisones the stack. This is why the run-time library has
773// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
774// stack in the interceptor. This however does not work inside the
775// actual function which catches the exception. Most likely because the
776// compiler hoists the load of the shadow value somewhere too high.
777// This causes asan to report a non-existing bug on 453.povray.
778// It sounds like an LLVM bug.
779struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
780 Function &F;
781 AddressSanitizer &ASan;
782 DIBuilder DIB;
783 LLVMContext *C;
784 Type *IntptrTy;
785 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000786 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000787
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000788 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000789 SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000790 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000791 unsigned StackAlignment;
792
Kostya Serebryany6805de52013-09-10 13:16:56 +0000793 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000794 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Vitaly Buka3455b9b2016-08-20 18:34:39 +0000795 Function *AsanSetShadowFunc[0x100] = {};
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000796 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000797 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000798
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000799 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
800 struct AllocaPoisonCall {
801 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000802 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000803 uint64_t Size;
804 bool DoPoison;
805 };
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000806 SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
807 SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000808
Yury Gribov98b18592015-05-28 07:51:49 +0000809 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
810 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
811 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000812 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000813
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000814 // Maps Value to an AllocaInst from which the Value is originated.
Eugene Zelenkobff0ef02017-10-19 22:07:16 +0000815 using AllocaForValueMapTy = DenseMap<Value *, AllocaInst *>;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000816 AllocaForValueMapTy AllocaForValue;
817
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000818 bool HasNonEmptyInlineAsm = false;
819 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000820 std::unique_ptr<CallInst> EmptyInlineAsm;
821
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000822 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000823 : F(F),
824 ASan(ASan),
825 DIB(*F.getParent(), /*AllowUnresolved*/ false),
826 C(ASan.C),
827 IntptrTy(ASan.IntptrTy),
828 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
829 Mapping(ASan.Mapping),
830 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000831 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000832
833 bool runOnFunction() {
834 if (!ClStack) return false;
Vitaly Buka74443f02017-07-18 22:28:03 +0000835
Matt Morehouse49e5aca2017-08-09 17:59:43 +0000836 if (ClRedzoneByvalArgs)
Vitaly Buka629047de2017-08-07 07:12:34 +0000837 copyArgsPassedByValToAllocas();
Vitaly Buka74443f02017-07-18 22:28:03 +0000838
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000839 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000840 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000841
Yury Gribov55441bb2014-11-21 10:29:50 +0000842 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000843
844 initializeCallbacks(*F.getParent());
845
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000846 processDynamicAllocas();
847 processStaticAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000848
849 if (ClDebugStack) {
850 DEBUG(dbgs() << F);
851 }
852 return true;
853 }
854
Vitaly Buka74443f02017-07-18 22:28:03 +0000855 // Arguments marked with the "byval" attribute are implicitly copied without
856 // using an alloca instruction. To produce redzones for those arguments, we
857 // copy them a second time into memory allocated with an alloca instruction.
858 void copyArgsPassedByValToAllocas();
859
Yury Gribov55441bb2014-11-21 10:29:50 +0000860 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000861 // poisoned red zones around all of them.
862 // Then unpoison everything back before the function returns.
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000863 void processStaticAllocas();
864 void processDynamicAllocas();
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000865
Yury Gribov98b18592015-05-28 07:51:49 +0000866 void createDynamicAllocasInitStorage();
867
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000868 // ----------------------- Visitors.
869 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000870 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000871
Vitaly Bukae3a032a2016-07-22 22:04:38 +0000872 /// \brief Collect all Resume instructions.
873 void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
874
875 /// \brief Collect all CatchReturnInst instructions.
876 void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
877
Yury Gribov98b18592015-05-28 07:51:49 +0000878 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
879 Value *SavedStack) {
880 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000881 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
882 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
883 // need to adjust extracted SP to compute the address of the most recent
884 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
885 // this purpose.
886 if (!isa<ReturnInst>(InstBefore)) {
887 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
888 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
889 {IntptrTy});
890
891 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
892
893 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
894 DynamicAreaOffset);
895 }
896
Yury Gribov781bce22015-05-28 08:03:28 +0000897 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000898 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000899 }
900
Yury Gribov55441bb2014-11-21 10:29:50 +0000901 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000902 void unpoisonDynamicAllocas() {
903 for (auto &Ret : RetVec)
904 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000905
Yury Gribov98b18592015-05-28 07:51:49 +0000906 for (auto &StackRestoreInst : StackRestoreVec)
907 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
908 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000909 }
910
Yury Gribov55441bb2014-11-21 10:29:50 +0000911 // Deploy and poison redzones around dynamic alloca call. To do this, we
912 // should replace this call with another one with changed parameters and
913 // replace all its uses with new address, so
914 // addr = alloca type, old_size, align
915 // is replaced by
916 // new_size = (old_size + additional_size) * sizeof(type)
917 // tmp = alloca i8, new_size, max(align, 32)
918 // addr = tmp + 32 (first 32 bytes are for the left redzone).
919 // Additional_size is added to make new memory allocation contain not only
920 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000921 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000922
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000923 /// \brief Collect Alloca instructions we want (and can) handle.
924 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000925 if (!ASan.isInterestingAlloca(AI)) {
Kuba Breckaa49dcbb2016-11-08 21:30:41 +0000926 if (AI.isStaticAlloca()) {
927 // Skip over allocas that are present *before* the first instrumented
928 // alloca, we don't want to move those around.
929 if (AllocaVec.empty())
930 return;
931
932 StaticAllocasToMoveUp.push_back(&AI);
933 }
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000934 return;
935 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000936
937 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Kuba Brecka7d03ce42016-06-27 15:57:08 +0000938 if (!AI.isStaticAlloca())
Yury Gribov98b18592015-05-28 07:51:49 +0000939 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000940 else
941 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000942 }
943
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000944 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
945 /// errors.
946 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000947 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000948 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000949 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Vitaly Buka1e75fa42016-05-27 22:55:10 +0000950 if (!ASan.UseAfterScope)
951 return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000952 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000953 return;
954 // Found lifetime intrinsic, add ASan instrumentation if necessary.
955 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
956 // If size argument is undefined, don't do anything.
957 if (Size->isMinusOne()) return;
958 // Check that size doesn't saturate uint64_t and can
959 // be stored in IntptrTy.
960 const uint64_t SizeValue = Size->getValue().getLimitedValue();
961 if (SizeValue == ~0ULL ||
962 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
963 return;
964 // Find alloca instruction that corresponds to llvm.lifetime argument.
965 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
Vitaly Bukab451f1b2016-06-09 23:31:59 +0000966 if (!AI || !ASan.isInterestingAlloca(*AI))
967 return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000968 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000969 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Vitaly Buka5b4f1212016-08-20 17:22:27 +0000970 if (AI->isStaticAlloca())
971 StaticAllocaPoisonCallVec.push_back(APC);
972 else if (ClInstrumentDynamicAllocas)
973 DynamicAllocaPoisonCallVec.push_back(APC);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000974 }
975
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000976 void visitCallSite(CallSite CS) {
977 Instruction *I = CS.getInstruction();
978 if (CallInst *CI = dyn_cast<CallInst>(I)) {
979 HasNonEmptyInlineAsm |=
980 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
981 HasReturnsTwiceCall |= CI->canReturnTwice();
982 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000983 }
984
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000985 // ---------------------- Helpers.
986 void initializeCallbacks(Module &M);
987
Yury Gribov3ae427d2014-12-01 08:47:58 +0000988 bool doesDominateAllExits(const Instruction *I) const {
989 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000990 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000991 }
992 return true;
993 }
994
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000995 /// Finds alloca where the value comes from.
996 AllocaInst *findAllocaForValue(Value *V);
Vitaly Buka793913c2016-08-29 18:17:21 +0000997
998 // Copies bytes from ShadowBytes into shadow memory for indexes where
999 // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
1000 // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
1001 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1002 IRBuilder<> &IRB, Value *ShadowBase);
1003 void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
1004 size_t Begin, size_t End, IRBuilder<> &IRB,
1005 Value *ShadowBase);
1006 void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
1007 ArrayRef<uint8_t> ShadowBytes, size_t Begin,
1008 size_t End, IRBuilder<> &IRB, Value *ShadowBase);
1009
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001010 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001011
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001012 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
1013 bool Dynamic);
1014 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
1015 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001016};
1017
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001018} // end anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001019
1020char AddressSanitizer::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001021
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001022INITIALIZE_PASS_BEGIN(
1023 AddressSanitizer, "asan",
1024 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1025 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +00001026INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +00001027INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028INITIALIZE_PASS_END(
1029 AddressSanitizer, "asan",
1030 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
1031 false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001032
Yury Gribovd7731982015-11-11 10:36:49 +00001033FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001034 bool Recover,
1035 bool UseAfterScope) {
Yury Gribovd7731982015-11-11 10:36:49 +00001036 assert(!CompileKernel || Recover);
Vitaly Buka1e75fa42016-05-27 22:55:10 +00001037 return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001038}
1039
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001040char AddressSanitizerModule::ID = 0;
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001041
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001042INITIALIZE_PASS(
1043 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001044 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001045 "ModulePass",
1046 false, false)
Eugene Zelenkobff0ef02017-10-19 22:07:16 +00001047
Yury Gribovd7731982015-11-11 10:36:49 +00001048ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001049 bool Recover,
1050 bool UseGlobalsGC) {
Yury Gribovd7731982015-11-11 10:36:49 +00001051 assert(!CompileKernel || Recover);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00001052 return new AddressSanitizerModule(CompileKernel, Recover, UseGlobalsGC);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +00001053}
1054
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001055static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +00001056 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001057 assert(Res < kNumberOfAccessSizes);
1058 return Res;
1059}
1060
Bill Wendling58f8cef2013-08-06 22:52:42 +00001061// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001062static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
1063 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +00001064 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001065 // We use private linkage for module-local strings. If they can be merged
1066 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001067 GlobalVariable *GV =
1068 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001069 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001070 if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +00001071 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
1072 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001073}
1074
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001075/// \brief Create a global describing a source location.
1076static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
1077 LocationMetadata MD) {
1078 Constant *LocData[] = {
1079 createPrivateGlobalForString(M, MD.Filename, true),
1080 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
1081 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
1082 };
1083 auto LocStruct = ConstantStruct::getAnon(LocData);
1084 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
1085 GlobalValue::PrivateLinkage, LocStruct,
1086 kAsanGenPrefix);
Peter Collingbourne96efdd62016-06-14 21:01:22 +00001087 GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001088 return GV;
1089}
1090
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001091/// \brief Check if \p G has been created by a trusted compiler pass.
1092static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
1093 // Do not instrument asan globals.
1094 if (G->getName().startswith(kAsanGenPrefix) ||
1095 G->getName().startswith(kSanCovGenPrefix) ||
1096 G->getName().startswith(kODRGenPrefix))
1097 return true;
1098
1099 // Do not instrument gcov counter arrays.
1100 if (G->getName() == "__llvm_gcov_ctr")
1101 return true;
1102
1103 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001104}
1105
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001106Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
1107 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +00001108 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001109 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001110 // (Shadow >> scale) | offset
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001111 Value *ShadowBase;
1112 if (LocalDynamicShadow)
1113 ShadowBase = LocalDynamicShadow;
Etienne Bergeron6ba51762016-09-19 15:58:38 +00001114 else
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001115 ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
1116 if (Mapping.OrShadowOffset)
1117 return IRB.CreateOr(Shadow, ShadowBase);
1118 else
1119 return IRB.CreateAdd(Shadow, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001120}
1121
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001122// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001123void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1124 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001125 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001126 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001127 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +00001128 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1129 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1130 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001131 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +00001132 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001133 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +00001134 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1135 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1136 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001137 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001138 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001139}
1140
Anna Zaks8ed1d812015-02-27 03:12:36 +00001141/// Check if we want (and can) handle this alloca.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001142bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001143 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
1144
1145 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
1146 return PreviouslySeenAllocaInfo->getSecond();
1147
Yury Gribov98b18592015-05-28 07:51:49 +00001148 bool IsInteresting =
1149 (AI.getAllocatedType()->isSized() &&
1150 // alloca() may be called with 0 size, ignore it.
Vitaly Buka21a9e572016-07-28 22:50:50 +00001151 ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
Yury Gribov98b18592015-05-28 07:51:49 +00001152 // We are only interested in allocas not promotable to registers.
1153 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +00001154 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
1155 // inalloca allocas are not treated as static, and we don't want
1156 // dynamic alloca instrumentation for them as well.
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001157 !AI.isUsedWithInAlloca() &&
1158 // swifterror allocas are register promoted by ISel
1159 !AI.isSwiftError());
Anna Zaksbf28d3a2015-03-27 18:52:01 +00001160
1161 ProcessedAllocas[&AI] = IsInteresting;
1162 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001163}
1164
Anna Zaks8ed1d812015-02-27 03:12:36 +00001165Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1166 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001167 uint64_t *TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001168 unsigned *Alignment,
1169 Value **MaybeMask) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +00001170 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001171 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001172
Etienne Bergeron0ca05682016-09-30 17:46:32 +00001173 // Do not instrument the load fetching the dynamic shadow address.
1174 if (LocalDynamicShadow == I)
1175 return nullptr;
1176
Anna Zaks8ed1d812015-02-27 03:12:36 +00001177 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001178 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001179 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001180 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001181 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001182 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001183 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001184 PtrOperand = LI->getPointerOperand();
1185 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001186 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001187 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001188 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001189 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +00001190 PtrOperand = SI->getPointerOperand();
1191 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001192 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001193 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001194 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001195 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001196 PtrOperand = RMW->getPointerOperand();
1197 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +00001198 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +00001199 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001200 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001201 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +00001202 PtrOperand = XCHG->getPointerOperand();
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001203 } else if (auto CI = dyn_cast<CallInst>(I)) {
1204 auto *F = dyn_cast<Function>(CI->getCalledValue());
1205 if (F && (F->getName().startswith("llvm.masked.load.") ||
1206 F->getName().startswith("llvm.masked.store."))) {
1207 unsigned OpOffset = 0;
1208 if (F->getName().startswith("llvm.masked.store.")) {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001209 if (!ClInstrumentWrites)
1210 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001211 // Masked store has an initial operand for the value.
1212 OpOffset = 1;
1213 *IsWrite = true;
1214 } else {
Filipe Cabecinhas1e690172016-12-14 21:56:59 +00001215 if (!ClInstrumentReads)
1216 return nullptr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001217 *IsWrite = false;
1218 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001219
1220 auto BasePtr = CI->getOperand(0 + OpOffset);
1221 auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1222 *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1223 if (auto AlignmentConstant =
1224 dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1225 *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1226 else
1227 *Alignment = 1; // No alignment guarantees. We probably got Undef
1228 if (MaybeMask)
1229 *MaybeMask = CI->getOperand(2 + OpOffset);
1230 PtrOperand = BasePtr;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001231 }
Kostya Serebryany90241602012-05-30 09:04:06 +00001232 }
Anna Zaks8ed1d812015-02-27 03:12:36 +00001233
Anna Zaks644d9d32016-06-22 00:15:52 +00001234 if (PtrOperand) {
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001235 // Do not instrument acesses from different address spaces; we cannot deal
1236 // with them.
Anna Zaks644d9d32016-06-22 00:15:52 +00001237 Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1238 if (PtrTy->getPointerAddressSpace() != 0)
1239 return nullptr;
Arnold Schwaighofer8d61e002017-02-15 20:43:43 +00001240
1241 // Ignore swifterror addresses.
1242 // swifterror memory addresses are mem2reg promoted by instruction
1243 // selection. As such they cannot have regular uses like an instrumentation
1244 // function and it makes no sense to track them as memory.
1245 if (PtrOperand->isSwiftError())
1246 return nullptr;
Anna Zaks644d9d32016-06-22 00:15:52 +00001247 }
1248
Anna Zaks8ed1d812015-02-27 03:12:36 +00001249 // Treat memory accesses to promotable allocas as non-interesting since they
1250 // will not cause memory violations. This greatly speeds up the instrumented
1251 // executable at -O0.
1252 if (ClSkipPromotableAllocas)
1253 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1254 return isInterestingAlloca(*AI) ? AI : nullptr;
1255
1256 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001257}
1258
Kostya Serebryany796f6552014-02-27 12:45:36 +00001259static bool isPointerOperand(Value *V) {
1260 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1261}
1262
1263// This is a rough heuristic; it may cause both false positives and
1264// false negatives. The proper implementation requires cooperation with
1265// the frontend.
1266static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1267 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001268 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001269 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001270 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +00001271 } else {
1272 return false;
1273 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +00001274 return isPointerOperand(I->getOperand(0)) &&
1275 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001276}
1277
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001278bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1279 // If a global variable does not have dynamic initialization we don't
1280 // have to instrument it. However, if a global does not have initializer
1281 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001282 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001283}
1284
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001285void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1286 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +00001287 IRBuilder<> IRB(I);
1288 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1289 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
Benjamin Kramer135f7352016-06-26 12:28:59 +00001290 for (Value *&i : Param) {
1291 if (i->getType()->isPointerTy())
1292 i = IRB.CreatePointerCast(i, IntptrTy);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001293 }
David Blaikieff6409d2015-05-18 22:13:54 +00001294 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001295}
1296
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001297static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001298 Instruction *InsertBefore, Value *Addr,
1299 unsigned Alignment, unsigned Granularity,
1300 uint32_t TypeSize, bool IsWrite,
1301 Value *SizeArgument, bool UseCalls,
1302 uint32_t Exp) {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001303 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1304 // if the data is properly aligned.
1305 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1306 TypeSize == 128) &&
1307 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001308 return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1309 nullptr, UseCalls, Exp);
1310 Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1311 IsWrite, nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001312}
1313
1314static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1315 const DataLayout &DL, Type *IntptrTy,
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001316 Value *Mask, Instruction *I,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001317 Value *Addr, unsigned Alignment,
1318 unsigned Granularity, uint32_t TypeSize,
1319 bool IsWrite, Value *SizeArgument,
1320 bool UseCalls, uint32_t Exp) {
1321 auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1322 uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1323 unsigned Num = VTy->getVectorNumElements();
1324 auto Zero = ConstantInt::get(IntptrTy, 0);
1325 for (unsigned Idx = 0; Idx < Num; ++Idx) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001326 Value *InstrumentedAddress = nullptr;
1327 Instruction *InsertBefore = I;
1328 if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1329 // dyn_cast as we might get UndefValue
1330 if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
Craig Topper79ab6432017-07-06 18:39:47 +00001331 if (Masked->isZero())
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001332 // Mask is constant false, so no instrumentation needed.
1333 continue;
1334 // If we have a true or undef value, fall through to doInstrumentAddress
1335 // with InsertBefore == I
1336 }
1337 } else {
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001338 IRBuilder<> IRB(I);
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001339 Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1340 TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1341 InsertBefore = ThenTerm;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001342 }
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001343
1344 IRBuilder<> IRB(InsertBefore);
1345 InstrumentedAddress =
1346 IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1347 doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1348 Granularity, ElemTypeSize, IsWrite, SizeArgument,
1349 UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001350 }
1351}
1352
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001353void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001354 Instruction *I, bool UseCalls,
1355 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +00001356 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001357 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001358 uint64_t TypeSize = 0;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001359 Value *MaybeMask = nullptr;
1360 Value *Addr =
1361 isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
Kostya Serebryany90241602012-05-30 09:04:06 +00001362 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001363
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001364 // Optimization experiments.
1365 // The experiments can be used to evaluate potential optimizations that remove
1366 // instrumentation (assess false negatives). Instead of completely removing
1367 // some instrumentation, you set Exp to a non-zero value (mask of optimization
1368 // experiments that want to remove instrumentation of this instruction).
1369 // If Exp is non-zero, this pass will emit special calls into runtime
1370 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1371 // make runtime terminate the program in a special way (with a different
1372 // exit status). Then you run the new compiler on a buggy corpus, collect
1373 // the special terminations (ideally, you don't see them at all -- no false
1374 // negatives) and make the decision on the optimization.
1375 uint32_t Exp = ClForceExperiment;
1376
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001377 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001378 // If initialization order checking is disabled, a simple access to a
1379 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001380 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001381 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001382 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1383 NumOptimizedAccessesToGlobalVar++;
1384 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001385 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001386 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001387
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001388 if (ClOpt && ClOptStack) {
1389 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001390 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001391 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1392 NumOptimizedAccessesToStackVar++;
1393 return;
1394 }
1395 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001396
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001397 if (IsWrite)
1398 NumInstrumentedWrites++;
1399 else
1400 NumInstrumentedReads++;
1401
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001402 unsigned Granularity = 1 << Mapping.Scale;
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001403 if (MaybeMask) {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001404 instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1405 Alignment, Granularity, TypeSize, IsWrite,
1406 nullptr, UseCalls, Exp);
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001407 } else {
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001408 doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
Filipe Cabecinhasec350b72016-11-15 22:37:30 +00001409 IsWrite, nullptr, UseCalls, Exp);
1410 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001411}
1412
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001413Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1414 Value *Addr, bool IsWrite,
1415 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001416 Value *SizeArgument,
1417 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001418 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001419 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1420 CallInst *Call = nullptr;
1421 if (SizeArgument) {
1422 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001423 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1424 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001425 else
David Blaikieff6409d2015-05-18 22:13:54 +00001426 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1427 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001428 } else {
1429 if (Exp == 0)
1430 Call =
1431 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1432 else
David Blaikieff6409d2015-05-18 22:13:54 +00001433 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1434 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001435 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001436
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001437 // We don't do Call->setDoesNotReturn() because the BB already has
1438 // UnreachableInst at the end.
1439 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001440 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001441 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001442}
1443
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001444Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001445 Value *ShadowValue,
1446 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001447 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001448 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001449 Value *LastAccessedByte =
1450 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001451 // (Addr & (Granularity - 1)) + size - 1
1452 if (TypeSize / 8 > 1)
1453 LastAccessedByte = IRB.CreateAdd(
1454 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1455 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001456 LastAccessedByte =
1457 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001458 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1459 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1460}
1461
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001462void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001463 Instruction *InsertBefore, Value *Addr,
1464 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001465 Value *SizeArgument, bool UseCalls,
1466 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001467 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001468 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001469 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1470
1471 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001472 if (Exp == 0)
1473 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1474 AddrLong);
1475 else
David Blaikieff6409d2015-05-18 22:13:54 +00001476 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1477 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001478 return;
1479 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001480
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001481 Type *ShadowTy =
1482 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001483 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1484 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1485 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001486 Value *ShadowValue =
1487 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001488
1489 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001490 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001491 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001492
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001493 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001494 // We use branch weights for the slow path check, to indicate that the slow
1495 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001496 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1497 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001498 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001499 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001500 IRB.SetInsertPoint(CheckTerm);
1501 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001502 if (Recover) {
1503 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1504 } else {
1505 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001506 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001507 CrashTerm = new UnreachableInst(*C, CrashBlock);
1508 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1509 ReplaceInstWithInst(CheckTerm, NewTerm);
1510 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001511 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001512 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001513 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001514
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001515 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001516 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001517 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001518}
1519
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001520// Instrument unusual size or unusual alignment.
1521// We can not do it with a single check, so we do 1-byte check for the first
1522// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1523// to report the actual access size.
1524void AddressSanitizer::instrumentUnusualSizeOrAlignment(
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001525 Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1526 bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1527 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001528 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1529 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1530 if (UseCalls) {
1531 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001532 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1533 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001534 else
David Blaikieff6409d2015-05-18 22:13:54 +00001535 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1536 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001537 } else {
1538 Value *LastByte = IRB.CreateIntToPtr(
1539 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1540 Addr->getType());
Filipe Cabecinhas4647b742017-01-06 15:24:51 +00001541 instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1542 instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001543 }
1544}
1545
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001546void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1547 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001548 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001549 IRBuilder<> IRB(&GlobalInit.front(),
1550 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001551
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001552 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001553 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1554 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001555
1556 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001557 for (auto &BB : GlobalInit.getBasicBlockList())
1558 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001559 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001560}
1561
1562void AddressSanitizerModule::createInitializerPoisonCalls(
1563 Module &M, GlobalValue *ModuleName) {
1564 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001565 if (!GV)
1566 return;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001567
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001568 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1569 if (!CA)
1570 return;
1571
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001572 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001573 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001574 ConstantStruct *CS = cast<ConstantStruct>(OP);
1575
1576 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001577 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001578 if (F->getName() == kAsanModuleCtorName) continue;
1579 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1580 // Don't instrument CTORs that will run before asan.module_ctor.
1581 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1582 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001583 }
1584 }
1585}
1586
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001587bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001588 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001589 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001590
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001591 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001592 if (!Ty->isSized()) return false;
1593 if (!G->hasInitializer()) return false;
Vedant Kumarf5ac6d42016-06-22 17:30:58 +00001594 if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001595 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001596 // Don't handle ODR linkage types and COMDATs since other modules may be built
1597 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001598 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1599 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1600 G->getLinkage() != GlobalVariable::InternalLinkage)
1601 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001602 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001603 // Two problems with thread-locals:
1604 // - The address of the main thread's copy can't be computed at link-time.
1605 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001606 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001607 // For now, just ignore this Global if the alignment is large.
1608 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001609
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001610 if (G->hasSection()) {
Rafael Espindola83658d62016-05-11 18:21:59 +00001611 StringRef Section = G->getSection();
Kuba Brecka086e34b2014-12-05 21:32:46 +00001612
Anna Zaks11904602015-06-09 00:58:08 +00001613 // Globals from llvm.metadata aren't emitted, do not instrument them.
1614 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001615 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001616 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001617
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001618 // Do not instrument function pointers to initialization and termination
1619 // routines: dynamic linker will not properly handle redzones.
1620 if (Section.startswith(".preinit_array") ||
1621 Section.startswith(".init_array") ||
1622 Section.startswith(".fini_array")) {
1623 return false;
1624 }
1625
Anna Zaks11904602015-06-09 00:58:08 +00001626 // Callbacks put into the CRT initializer/terminator sections
1627 // should not be instrumented.
1628 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1629 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1630 if (Section.startswith(".CRT")) {
1631 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1632 return false;
1633 }
1634
Kuba Brecka1001bb52014-12-05 22:19:18 +00001635 if (TargetTriple.isOSBinFormatMachO()) {
1636 StringRef ParsedSegment, ParsedSection;
1637 unsigned TAA = 0, StubSize = 0;
1638 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001639 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1640 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001641 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001642
1643 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1644 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1645 // them.
1646 if (ParsedSegment == "__OBJC" ||
1647 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1648 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1649 return false;
1650 }
1651 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1652 // Constant CFString instances are compiled in the following way:
1653 // -- the string buffer is emitted into
1654 // __TEXT,__cstring,cstring_literals
1655 // -- the constant NSConstantString structure referencing that buffer
1656 // is placed into __DATA,__cfstring
1657 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1658 // Moreover, it causes the linker to crash on OS X 10.7
1659 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1660 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1661 return false;
1662 }
1663 // The linker merges the contents of cstring_literals and removes the
1664 // trailing zeroes.
1665 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1666 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1667 return false;
1668 }
1669 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001670 }
1671
1672 return true;
1673}
1674
Ryan Govostes653f9d02016-03-28 20:28:57 +00001675// On Mach-O platforms, we emit global metadata in a separate section of the
1676// binary in order to allow the linker to properly dead strip. This is only
1677// supported on recent versions of ld64.
1678bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1679 if (!TargetTriple.isOSBinFormatMachO())
1680 return false;
1681
1682 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1683 return true;
1684 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001685 return true;
Ryan Govostes653f9d02016-03-28 20:28:57 +00001686 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1687 return true;
1688
1689 return false;
1690}
1691
Reid Kleckner01660a32016-11-21 20:40:37 +00001692StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1693 switch (TargetTriple.getObjectFormat()) {
1694 case Triple::COFF: return ".ASAN$GL";
1695 case Triple::ELF: return "asan_globals";
1696 case Triple::MachO: return "__DATA,__asan_globals,regular";
1697 default: break;
1698 }
1699 llvm_unreachable("unsupported object format");
1700}
1701
Alexey Samsonov788381b2012-12-25 12:28:20 +00001702void AddressSanitizerModule::initializeCallbacks(Module &M) {
1703 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001704
Alexey Samsonov788381b2012-12-25 12:28:20 +00001705 // Declare our poisoning and unpoisoning functions.
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001706 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001707 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001708 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001709 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001710 kAsanUnpoisonGlobalsName, IRB.getVoidTy()));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001711 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001712
Alexey Samsonov788381b2012-12-25 12:28:20 +00001713 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001714 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001715 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001716 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00001717 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1718 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001719 IntptrTy, IntptrTy));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001720 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001721
1722 // Declare the functions that find globals in a shared object and then invoke
1723 // the (un)register function on them.
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001724 AsanRegisterImageGlobals =
1725 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001726 kAsanRegisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001727 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
Mike Aizatsky243b71f2016-04-21 22:00:13 +00001728
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001729 AsanUnregisterImageGlobals =
1730 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00001731 kAsanUnregisterImageGlobalsName, IRB.getVoidTy(), IntptrTy));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001732 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001733
1734 AsanRegisterElfGlobals = checkSanitizerInterfaceFunction(
1735 M.getOrInsertFunction(kAsanRegisterElfGlobalsName, IRB.getVoidTy(),
1736 IntptrTy, IntptrTy, IntptrTy));
1737 AsanRegisterElfGlobals->setLinkage(Function::ExternalLinkage);
1738
1739 AsanUnregisterElfGlobals = checkSanitizerInterfaceFunction(
1740 M.getOrInsertFunction(kAsanUnregisterElfGlobalsName, IRB.getVoidTy(),
1741 IntptrTy, IntptrTy, IntptrTy));
1742 AsanUnregisterElfGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001743}
1744
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001745// Put the metadata and the instrumented global in the same group. This ensures
1746// that the metadata is discarded if the instrumented global is discarded.
1747void AddressSanitizerModule::SetComdatForGlobalMetadata(
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001748 GlobalVariable *G, GlobalVariable *Metadata, StringRef InternalSuffix) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001749 Module &M = *G->getParent();
1750 Comdat *C = G->getComdat();
1751 if (!C) {
1752 if (!G->hasName()) {
1753 // If G is unnamed, it must be internal. Give it an artificial name
1754 // so we can put it in a comdat.
1755 assert(G->hasLocalLinkage());
1756 G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1757 }
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001758
1759 if (!InternalSuffix.empty() && G->hasLocalLinkage()) {
1760 std::string Name = G->getName();
1761 Name += InternalSuffix;
1762 C = M.getOrInsertComdat(Name);
1763 } else {
1764 C = M.getOrInsertComdat(G->getName());
1765 }
1766
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001767 // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1768 if (TargetTriple.isOSBinFormatCOFF())
1769 C->setSelectionKind(Comdat::NoDuplicates);
1770 G->setComdat(C);
1771 }
1772
1773 assert(G->hasComdat());
1774 Metadata->setComdat(G->getComdat());
1775}
1776
1777// Create a separate metadata global and put it in the appropriate ASan
1778// global registration section.
1779GlobalVariable *
1780AddressSanitizerModule::CreateMetadataGlobal(Module &M, Constant *Initializer,
1781 StringRef OriginalName) {
Evgeniy Stepanov90fd8732017-04-11 22:28:13 +00001782 auto Linkage = TargetTriple.isOSBinFormatMachO()
1783 ? GlobalVariable::InternalLinkage
1784 : GlobalVariable::PrivateLinkage;
1785 GlobalVariable *Metadata = new GlobalVariable(
1786 M, Initializer->getType(), false, Linkage, Initializer,
Peter Collingbourne6f0ecca2017-05-16 00:39:01 +00001787 Twine("__asan_global_") + GlobalValue::dropLLVMManglingEscape(OriginalName));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001788 Metadata->setSection(getGlobalMetadataSection());
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001789 return Metadata;
1790}
1791
1792IRBuilder<> AddressSanitizerModule::CreateAsanModuleDtor(Module &M) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001793 AsanDtorFunction =
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001794 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1795 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1796 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001797
1798 return IRBuilder<>(ReturnInst::Create(*C, AsanDtorBB));
1799}
1800
1801void AddressSanitizerModule::InstrumentGlobalsCOFF(
1802 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1803 ArrayRef<Constant *> MetadataInitializers) {
1804 assert(ExtendedGlobals.size() == MetadataInitializers.size());
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001805 auto &DL = M.getDataLayout();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001806
1807 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001808 Constant *Initializer = MetadataInitializers[i];
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001809 GlobalVariable *G = ExtendedGlobals[i];
1810 GlobalVariable *Metadata =
Evgeniy Stepanovf01c70f2017-01-12 23:26:20 +00001811 CreateMetadataGlobal(M, Initializer, G->getName());
1812
1813 // The MSVC linker always inserts padding when linking incrementally. We
1814 // cope with that by aligning each struct to its size, which must be a power
1815 // of two.
1816 unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(Initializer->getType());
1817 assert(isPowerOf2_32(SizeOfGlobalStruct) &&
1818 "global metadata will not be padded appropriately");
1819 Metadata->setAlignment(SizeOfGlobalStruct);
1820
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001821 SetComdatForGlobalMetadata(G, Metadata, "");
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001822 }
1823}
1824
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00001825void AddressSanitizerModule::InstrumentGlobalsELF(
1826 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1827 ArrayRef<Constant *> MetadataInitializers,
1828 const std::string &UniqueModuleId) {
1829 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1830
1831 SmallVector<GlobalValue *, 16> MetadataGlobals(ExtendedGlobals.size());
1832 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1833 GlobalVariable *G = ExtendedGlobals[i];
1834 GlobalVariable *Metadata =
1835 CreateMetadataGlobal(M, MetadataInitializers[i], G->getName());
1836 MDNode *MD = MDNode::get(M.getContext(), ValueAsMetadata::get(G));
1837 Metadata->setMetadata(LLVMContext::MD_associated, MD);
1838 MetadataGlobals[i] = Metadata;
1839
1840 SetComdatForGlobalMetadata(G, Metadata, UniqueModuleId);
1841 }
1842
1843 // Update llvm.compiler.used, adding the new metadata globals. This is
1844 // needed so that during LTO these variables stay alive.
1845 if (!MetadataGlobals.empty())
1846 appendToCompilerUsed(M, MetadataGlobals);
1847
1848 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1849 // to look up the loaded image that contains it. Second, we can store in it
1850 // whether registration has already occurred, to prevent duplicate
1851 // registration.
1852 //
1853 // Common linkage ensures that there is only one global per shared library.
1854 GlobalVariable *RegisteredFlag = new GlobalVariable(
1855 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1856 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1857 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1858
1859 // Create start and stop symbols.
1860 GlobalVariable *StartELFMetadata = new GlobalVariable(
1861 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1862 "__start_" + getGlobalMetadataSection());
1863 StartELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1864 GlobalVariable *StopELFMetadata = new GlobalVariable(
1865 M, IntptrTy, false, GlobalVariable::ExternalWeakLinkage, nullptr,
1866 "__stop_" + getGlobalMetadataSection());
1867 StopELFMetadata->setVisibility(GlobalVariable::HiddenVisibility);
1868
1869 // Create a call to register the globals with the runtime.
1870 IRB.CreateCall(AsanRegisterElfGlobals,
1871 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1872 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1873 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1874
1875 // We also need to unregister globals at the end, e.g., when a shared library
1876 // gets closed.
1877 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1878 IRB_Dtor.CreateCall(AsanUnregisterElfGlobals,
1879 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy),
1880 IRB.CreatePointerCast(StartELFMetadata, IntptrTy),
1881 IRB.CreatePointerCast(StopELFMetadata, IntptrTy)});
1882}
1883
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001884void AddressSanitizerModule::InstrumentGlobalsMachO(
1885 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1886 ArrayRef<Constant *> MetadataInitializers) {
1887 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1888
1889 // On recent Mach-O platforms, use a structure which binds the liveness of
1890 // the global variable to the metadata struct. Keep the list of "Liveness" GV
1891 // created to be added to llvm.compiler.used
Serge Gueltone38003f2017-05-09 19:31:13 +00001892 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001893 SmallVector<GlobalValue *, 16> LivenessGlobals(ExtendedGlobals.size());
1894
1895 for (size_t i = 0; i < ExtendedGlobals.size(); i++) {
1896 Constant *Initializer = MetadataInitializers[i];
1897 GlobalVariable *G = ExtendedGlobals[i];
1898 GlobalVariable *Metadata =
1899 CreateMetadataGlobal(M, Initializer, G->getName());
1900
1901 // On recent Mach-O platforms, we emit the global metadata in a way that
1902 // allows the linker to properly strip dead globals.
Serge Gueltone38003f2017-05-09 19:31:13 +00001903 auto LivenessBinder =
1904 ConstantStruct::get(LivenessTy, Initializer->getAggregateElement(0u),
1905 ConstantExpr::getPointerCast(Metadata, IntptrTy));
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00001906 GlobalVariable *Liveness = new GlobalVariable(
1907 M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1908 Twine("__asan_binder_") + G->getName());
1909 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1910 LivenessGlobals[i] = Liveness;
1911 }
1912
1913 // Update llvm.compiler.used, adding the new liveness globals. This is
1914 // needed so that during LTO these variables stay alive. The alternative
1915 // would be to have the linker handling the LTO symbols, but libLTO
1916 // current API does not expose access to the section for each symbol.
1917 if (!LivenessGlobals.empty())
1918 appendToCompilerUsed(M, LivenessGlobals);
1919
1920 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1921 // to look up the loaded image that contains it. Second, we can store in it
1922 // whether registration has already occurred, to prevent duplicate
1923 // registration.
1924 //
1925 // common linkage ensures that there is only one global per shared library.
1926 GlobalVariable *RegisteredFlag = new GlobalVariable(
1927 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1928 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1929 RegisteredFlag->setVisibility(GlobalVariable::HiddenVisibility);
1930
1931 IRB.CreateCall(AsanRegisterImageGlobals,
1932 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1933
1934 // We also need to unregister globals at the end, e.g., when a shared library
1935 // gets closed.
1936 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1937 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1938 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1939}
1940
1941void AddressSanitizerModule::InstrumentGlobalsWithMetadataArray(
1942 IRBuilder<> &IRB, Module &M, ArrayRef<GlobalVariable *> ExtendedGlobals,
1943 ArrayRef<Constant *> MetadataInitializers) {
1944 assert(ExtendedGlobals.size() == MetadataInitializers.size());
1945 unsigned N = ExtendedGlobals.size();
1946 assert(N > 0);
1947
1948 // On platforms that don't have a custom metadata section, we emit an array
1949 // of global metadata structures.
1950 ArrayType *ArrayOfGlobalStructTy =
1951 ArrayType::get(MetadataInitializers[0]->getType(), N);
1952 auto AllGlobals = new GlobalVariable(
1953 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1954 ConstantArray::get(ArrayOfGlobalStructTy, MetadataInitializers), "");
1955
1956 IRB.CreateCall(AsanRegisterGlobals,
1957 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1958 ConstantInt::get(IntptrTy, N)});
1959
1960 // We also need to unregister globals at the end, e.g., when a shared library
1961 // gets closed.
1962 IRBuilder<> IRB_Dtor = CreateAsanModuleDtor(M);
1963 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1964 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1965 ConstantInt::get(IntptrTy, N)});
1966}
1967
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001968// This function replaces all global variables with new variables that have
1969// trailing redzones. It also creates a function that poisons
1970// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001971// Sets *CtorComdat to true if the global registration code emitted into the
1972// asan constructor is comdat-compatible.
1973bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M, bool *CtorComdat) {
1974 *CtorComdat = false;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001975 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001976
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001977 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1978
Alexey Samsonova02e6642014-05-29 18:40:48 +00001979 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001980 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001981 }
1982
1983 size_t n = GlobalsToChange.size();
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00001984 if (n == 0) {
1985 *CtorComdat = true;
1986 return false;
1987 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001988
Reid Kleckner78565832016-11-29 01:32:21 +00001989 auto &DL = M.getDataLayout();
Reid Kleckner01660a32016-11-21 20:40:37 +00001990
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001991 // A global is described by a structure
1992 // size_t beg;
1993 // size_t size;
1994 // size_t size_with_redzone;
1995 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001996 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001997 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001998 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001999 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002000 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002001 StructType *GlobalStructTy =
2002 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Serge Gueltone38003f2017-05-09 19:31:13 +00002003 IntptrTy, IntptrTy, IntptrTy);
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002004 SmallVector<GlobalVariable *, 16> NewGlobals(n);
2005 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00002006
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002007 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002008
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00002009 // We shouldn't merge same module names, as this string serves as unique
2010 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002011 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002012 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002013
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002014 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00002015 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002016 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00002017
2018 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002019 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002020 // Create string holding the global name (use global name from metadata
2021 // if it's available, otherwise just write the name of global variable).
2022 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002023 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002024 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00002025
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002026 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002027 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002028 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00002029 // MinRZ <= RZ <= kMaxGlobalRedzone
2030 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002031 uint64_t RZ = std::max(
2032 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00002033 uint64_t RightRedzoneSize = RZ;
2034 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002035 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002036 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002037 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
2038
Serge Gueltone38003f2017-05-09 19:31:13 +00002039 StructType *NewTy = StructType::get(Ty, RightRedZoneTy);
2040 Constant *NewInitializer = ConstantStruct::get(
2041 NewTy, G->getInitializer(), Constant::getNullValue(RightRedZoneTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002042
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002043 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00002044 GlobalValue::LinkageTypes Linkage = G->getLinkage();
2045 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
2046 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002047 GlobalVariable *NewGlobal =
2048 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
2049 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002050 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00002051 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002052
Kuba Breckaa28c9e82016-10-31 18:51:58 +00002053 // Move null-terminated C strings to "__asan_cstring" section on Darwin.
2054 if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
2055 G->isConstant()) {
2056 auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
2057 if (Seq && Seq->isCString())
2058 NewGlobal->setSection("__TEXT,__asan_cstring,regular");
2059 }
2060
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002061 // Transfer the debug info. The payload starts at offset zero so we can
2062 // copy the debug info over as is.
Adrian Prantlbceaaa92016-12-20 02:09:43 +00002063 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Adrian Prantl12fa3b32016-09-20 18:28:42 +00002064 G->getDebugInfo(GVs);
2065 for (auto *GV : GVs)
2066 NewGlobal->addDebugInfo(GV);
2067
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002068 Value *Indices2[2];
2069 Indices2[0] = IRB.getInt32(0);
2070 Indices2[1] = IRB.getInt32(0);
2071
2072 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00002073 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002074 NewGlobal->takeName(G);
2075 G->eraseFromParent();
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002076 NewGlobals[i] = NewGlobal;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002077
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00002078 Constant *SourceLoc;
2079 if (!MD.SourceLoc.empty()) {
2080 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
2081 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
2082 } else {
2083 SourceLoc = ConstantInt::get(IntptrTy, 0);
2084 }
2085
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002086 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
2087 GlobalValue *InstrumentedGlobal = NewGlobal;
2088
Kuba Breckaa1ea64a2016-09-14 14:06:33 +00002089 bool CanUsePrivateAliases =
Dan Gohman1209c7a2017-01-17 20:34:09 +00002090 TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO() ||
2091 TargetTriple.isOSBinFormatWasm();
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002092 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
2093 // Create local alias for NewGlobal to avoid crash on ODR between
2094 // instrumented and non-instrumented libraries.
2095 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
2096 NameForGlobal + M.getName(), NewGlobal);
2097
2098 // With local aliases, we need to provide another externally visible
2099 // symbol __odr_asan_XXX to detect ODR violation.
2100 auto *ODRIndicatorSym =
2101 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
2102 Constant::getNullValue(IRB.getInt8Ty()),
2103 kODRGenPrefix + NameForGlobal, nullptr,
2104 NewGlobal->getThreadLocalMode());
2105
2106 // Set meaningful attributes for indicator symbol.
2107 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
2108 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
2109 ODRIndicatorSym->setAlignment(1);
2110 ODRIndicator = ODRIndicatorSym;
2111 InstrumentedGlobal = GA;
2112 }
2113
Reid Kleckner01660a32016-11-21 20:40:37 +00002114 Constant *Initializer = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002115 GlobalStructTy,
2116 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002117 ConstantInt::get(IntptrTy, SizeInBytes),
2118 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
2119 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00002120 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00002121 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
Serge Gueltone38003f2017-05-09 19:31:13 +00002122 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002123
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002124 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00002125
Kostya Serebryany20343352012-10-17 13:40:06 +00002126 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Reid Kleckner01660a32016-11-21 20:40:37 +00002127
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002128 Initializers[i] = Initializer;
2129 }
Reid Kleckner01660a32016-11-21 20:40:37 +00002130
Evgeniy Stepanov964f4662017-04-27 20:27:27 +00002131 std::string ELFUniqueModuleId =
2132 (UseGlobalsGC && TargetTriple.isOSBinFormatELF()) ? getUniqueModuleId(&M)
2133 : "";
2134
2135 if (!ELFUniqueModuleId.empty()) {
2136 InstrumentGlobalsELF(IRB, M, NewGlobals, Initializers, ELFUniqueModuleId);
2137 *CtorComdat = true;
2138 } else if (UseGlobalsGC && TargetTriple.isOSBinFormatCOFF()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002139 InstrumentGlobalsCOFF(IRB, M, NewGlobals, Initializers);
Evgeniy Stepanov9e536082017-04-24 19:34:13 +00002140 } else if (UseGlobalsGC && ShouldUseMachOGlobalsSection()) {
Evgeniy Stepanov5d31d082017-01-12 23:03:03 +00002141 InstrumentGlobalsMachO(IRB, M, NewGlobals, Initializers);
2142 } else {
2143 InstrumentGlobalsWithMetadataArray(IRB, M, NewGlobals, Initializers);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002144 }
2145
Reid Kleckner01660a32016-11-21 20:40:37 +00002146 // Create calls for poisoning before initializers run and unpoisoning after.
2147 if (HasDynamicallyInitializedGlobals)
2148 createInitializerPoisonCalls(M, ModuleName);
2149
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002150 DEBUG(dbgs() << M);
2151 return true;
2152}
2153
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002154bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002155 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002156 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002157 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002158 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002159 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002160 initializeCallbacks(M);
2161
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002162 if (CompileKernel)
2163 return false;
Alex Shlyapnikovbbd5cc62017-03-27 23:11:50 +00002164
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002165 // Create a module constructor. A destructor is created lazily because not all
2166 // platforms, and not all modules need it.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002167 std::tie(AsanCtorFunction, std::ignore) = createSanitizerCtorAndInitFunctions(
2168 M, kAsanModuleCtorName, kAsanInitName, /*InitArgTypes=*/{},
2169 /*InitArgs=*/{}, kAsanVersionCheckName);
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002170
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002171 bool CtorComdat = true;
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002172 bool Changed = false;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002173 // TODO(glider): temporarily disabled globals instrumentation for KASan.
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002174 if (ClGlobals) {
2175 IRBuilder<> IRB(AsanCtorFunction->getEntryBlock().getTerminator());
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002176 Changed |= InstrumentGlobals(IRB, M, &CtorComdat);
2177 }
2178
2179 // Put the constructor and destructor in comdat if both
2180 // (1) global instrumentation is not TU-specific
2181 // (2) target is ELF.
Evgeniy Stepanovb56012b2017-05-15 20:43:42 +00002182 if (UseCtorComdat && TargetTriple.isOSBinFormatELF() && CtorComdat) {
Evgeniy Stepanov716f0ff222017-04-27 20:27:23 +00002183 AsanCtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleCtorName));
2184 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority,
2185 AsanCtorFunction);
2186 if (AsanDtorFunction) {
2187 AsanDtorFunction->setComdat(M.getOrInsertComdat(kAsanModuleDtorName));
2188 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority,
2189 AsanDtorFunction);
2190 }
2191 } else {
2192 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
2193 if (AsanDtorFunction)
2194 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002195 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00002196
2197 return Changed;
2198}
2199
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002200void AddressSanitizer::initializeCallbacks(Module &M) {
2201 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002202 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002203 // IsWrite, TypeSize and Exp are encoded in the function name.
2204 for (int Exp = 0; Exp < 2; Exp++) {
2205 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
2206 const std::string TypeStr = AccessIsWrite ? "store" : "load";
2207 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002208 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00002209 const std::string EndingStr = Recover ? "_noabort" : "";
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002210
2211 SmallVector<Type *, 3> Args2 = {IntptrTy, IntptrTy};
2212 SmallVector<Type *, 2> Args1{1, IntptrTy};
2213 if (Exp) {
2214 Type *ExpType = Type::getInt32Ty(*C);
2215 Args2.push_back(ExpType);
2216 Args1.push_back(ExpType);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00002217 }
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002218 AsanErrorCallbackSized[AccessIsWrite][Exp] =
2219 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2220 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr +
2221 EndingStr,
2222 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002223
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002224 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
2225 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2226 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
2227 FunctionType::get(IRB.getVoidTy(), Args2, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002228
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002229 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
2230 AccessSizeIndex++) {
2231 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
2232 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2233 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2234 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
2235 FunctionType::get(IRB.getVoidTy(), Args1, false)));
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002236
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00002237 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
2238 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2239 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
2240 FunctionType::get(IRB.getVoidTy(), Args1, false)));
2241 }
2242 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00002243 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00002244
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002245 const std::string MemIntrinCallbackPrefix =
2246 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002247 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002248 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002249 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002250 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002251 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002252 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002253 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002254 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002255 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002256
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002257 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002258 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy()));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00002259
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002260 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002261 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002262 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002263 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00002264 // We insert an empty inline asm after __asan_report* to avoid callback merge.
2265 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
2266 StringRef(""), StringRef(""),
2267 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002268}
2269
2270// virtual
2271bool AddressSanitizer::doInitialization(Module &M) {
2272 // Initialize the private fields. No one has accessed them before.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00002273 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002274
2275 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002276 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002277 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00002278 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00002279
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002280 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002281 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002282}
2283
Keno Fischere03fae42015-12-05 14:42:34 +00002284bool AddressSanitizer::doFinalization(Module &M) {
2285 GlobalsMD.reset();
2286 return false;
2287}
2288
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002289bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
2290 // For each NSObject descendant having a +load method, this method is invoked
2291 // by the ObjC runtime before any of the static constructors is called.
2292 // Therefore we need to instrument such methods with a call to __asan_init
2293 // at the beginning in order to initialize our runtime before any access to
2294 // the shadow memory.
2295 // We cannot just ignore these methods, because they may call other
2296 // instrumented functions.
2297 if (F.getName().find(" load]") != std::string::npos) {
Evgeniy Stepanov039af602017-04-06 19:55:09 +00002298 Function *AsanInitFunction =
2299 declareSanitizerInitFunction(*F.getParent(), kAsanInitName, {});
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00002300 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00002301 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00002302 return true;
2303 }
2304 return false;
2305}
2306
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002307void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
2308 // Generate code only when dynamic addressing is needed.
2309 if (Mapping.Offset != kDynamicShadowSentinel)
2310 return;
2311
2312 IRBuilder<> IRB(&F.front().front());
2313 Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2314 kAsanShadowMemoryDynamicAddress, IntptrTy);
2315 LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2316}
2317
Reid Kleckner2f907552015-07-21 17:40:14 +00002318void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2319 // Find the one possible call to llvm.localescape and pre-mark allocas passed
2320 // to it as uninteresting. This assumes we haven't started processing allocas
2321 // yet. This check is done up front because iterating the use list in
2322 // isInterestingAlloca would be algorithmically slower.
2323 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2324
2325 // Try to get the declaration of llvm.localescape. If it's not in the module,
2326 // we can exit early.
2327 if (!F.getParent()->getFunction("llvm.localescape")) return;
2328
2329 // Look for a call to llvm.localescape call in the entry block. It can't be in
2330 // any other block.
2331 for (Instruction &I : F.getEntryBlock()) {
2332 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2333 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2334 // We found a call. Mark all the allocas passed in as uninteresting.
2335 for (Value *Arg : II->arg_operands()) {
2336 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2337 assert(AI && AI->isStaticAlloca() &&
2338 "non-static alloca arg to localescape");
2339 ProcessedAllocas[AI] = false;
2340 }
2341 break;
2342 }
2343 }
2344}
2345
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00002346bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00002347 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002348 if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
Etienne Bergeron52e47432016-09-15 15:35:59 +00002349 if (F.getName().startswith("__asan_")) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002350
Etienne Bergeron78582b22016-09-15 15:45:05 +00002351 bool FunctionModified = false;
2352
Kostya Serebryanycf880b92013-02-26 06:58:09 +00002353 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Etienne Bergeron752f8832016-09-14 17:18:37 +00002354 // This function needs to be called even if the function body is not
2355 // instrumented.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002356 if (maybeInsertAsanInitAtFunctionEntry(F))
2357 FunctionModified = true;
Etienne Bergeron752f8832016-09-14 17:18:37 +00002358
2359 // Leave if the function doesn't need instrumentation.
Etienne Bergeron78582b22016-09-15 15:45:05 +00002360 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002361
Etienne Bergeron752f8832016-09-14 17:18:37 +00002362 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2363
2364 initializeCallbacks(*F.getParent());
2365 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002366
Reid Kleckner2f907552015-07-21 17:40:14 +00002367 FunctionStateRAII CleanupObj(this);
2368
Etienne Bergeron0ca05682016-09-30 17:46:32 +00002369 maybeInsertDynamicShadowAtFunctionEntry(F);
2370
Reid Kleckner2f907552015-07-21 17:40:14 +00002371 // We can't instrument allocas used with llvm.localescape. Only static allocas
2372 // can be passed to that intrinsic.
2373 markEscapedLocalAllocas(F);
2374
Bill Wendlingc9b22d72012-10-09 07:45:08 +00002375 // We want to instrument every address only once per basic block (unless there
2376 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002377 SmallSet<Value *, 16> TempsToInstrument;
2378 SmallVector<Instruction *, 16> ToInstrument;
2379 SmallVector<Instruction *, 8> NoReturnCalls;
2380 SmallVector<BasicBlock *, 16> AllBlocks;
2381 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002382 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00002383 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00002384 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002385 uint64_t TypeSize;
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002386 const TargetLibraryInfo *TLI =
2387 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002388
2389 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002390 for (auto &BB : F) {
2391 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002392 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002393 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002394 for (auto &Inst : BB) {
2395 if (LooksLikeCodeInBug11395(&Inst)) return false;
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002396 Value *MaybeMask = nullptr;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002397 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002398 &Alignment, &MaybeMask)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002399 if (ClOpt && ClOptSameTemp) {
Filipe Cabecinhasdd968872016-12-14 21:57:04 +00002400 // If we have a mask, skip instrumentation if we've already
2401 // instrumented the full object. But don't add to TempsToInstrument
2402 // because we might get another load/store with a different mask.
2403 if (MaybeMask) {
2404 if (TempsToInstrument.count(Addr))
2405 continue; // We've seen this (whole) temp in the current BB.
2406 } else {
2407 if (!TempsToInstrument.insert(Addr).second)
2408 continue; // We've seen this temp in the current BB.
2409 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002410 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00002411 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00002412 isInterestingPointerComparisonOrSubtraction(&Inst)) {
2413 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002414 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002415 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002416 // ok, take it.
2417 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002418 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002419 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00002420 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002421 // A call inside BB.
2422 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002423 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002424 }
Marcin Koscielnicki3feda222016-06-18 10:10:37 +00002425 if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2426 maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002427 continue;
2428 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00002429 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00002430 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002431 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002432 }
2433 }
2434
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002435 bool UseCalls =
2436 CompileKernel ||
2437 (ClInstrumentationWithCallsThreshold >= 0 &&
2438 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002439 const DataLayout &DL = F.getParent()->getDataLayout();
George Burgess IV56c7e882017-03-21 20:08:59 +00002440 ObjectSizeOpts ObjSizeOpts;
2441 ObjSizeOpts.RoundToAlign = true;
2442 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(), ObjSizeOpts);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002443
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002444 // Instrument.
2445 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00002446 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002447 if (ClDebugMin < 0 || ClDebugMax < 0 ||
2448 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002449 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002450 instrumentMop(ObjSizeVis, Inst, UseCalls,
2451 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002452 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00002453 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002454 }
2455 NumInstrumented++;
2456 }
2457
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002458 FunctionStackPoisoner FSP(F, *this);
2459 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002460
2461 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2462 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00002463 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002464 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00002465 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00002466 }
2467
Alexey Samsonova02e6642014-05-29 18:40:48 +00002468 for (auto Inst : PointerComparisonsOrSubtracts) {
2469 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00002470 NumInstrumented++;
2471 }
2472
Etienne Bergeron78582b22016-09-15 15:45:05 +00002473 if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2474 FunctionModified = true;
Bob Wilsonda4147c2013-11-15 07:16:09 +00002475
Etienne Bergeron78582b22016-09-15 15:45:05 +00002476 DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2477 << F << "\n");
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00002478
Etienne Bergeron78582b22016-09-15 15:45:05 +00002479 return FunctionModified;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002480}
2481
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002482// Workaround for bug 11395: we don't want to instrument stack in functions
2483// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2484// FIXME: remove once the bug 11395 is fixed.
2485bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2486 if (LongSize != 32) return false;
2487 CallInst *CI = dyn_cast<CallInst>(I);
2488 if (!CI || !CI->isInlineAsm()) return false;
2489 if (CI->getNumArgOperands() <= 5) return false;
2490 // We have inline assembly with quite a few arguments.
2491 return true;
2492}
2493
2494void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2495 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00002496 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2497 std::string Suffix = itostr(i);
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002498 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2499 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002500 IntptrTy));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00002501 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002502 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002503 IRB.getVoidTy(), IntptrTy, IntptrTy));
Kostya Serebryany6805de52013-09-10 13:16:56 +00002504 }
Vitaly Buka79b75d32016-06-09 23:05:35 +00002505 if (ASan.UseAfterScope) {
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002506 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2507 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002508 IntptrTy, IntptrTy));
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002509 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2510 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002511 IntptrTy, IntptrTy));
Vitaly Buka79b75d32016-06-09 23:05:35 +00002512 }
2513
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002514 for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2515 std::ostringstream Name;
2516 Name << kAsanSetShadowPrefix;
2517 Name << std::setw(2) << std::setfill('0') << std::hex << Val;
Mehdi Aminidb11fdf2017-04-06 20:23:57 +00002518 AsanSetShadowFunc[Val] =
2519 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002520 Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy));
Vitaly Buka3455b9b2016-08-20 18:34:39 +00002521 }
2522
Yury Gribov98b18592015-05-28 07:51:49 +00002523 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002524 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Yury Gribov98b18592015-05-28 07:51:49 +00002525 AsanAllocasUnpoisonFunc =
2526 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Serge Guelton59a2d7b2017-04-11 15:01:18 +00002527 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002528}
2529
Vitaly Buka793913c2016-08-29 18:17:21 +00002530void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2531 ArrayRef<uint8_t> ShadowBytes,
2532 size_t Begin, size_t End,
2533 IRBuilder<> &IRB,
2534 Value *ShadowBase) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002535 if (Begin >= End)
2536 return;
Vitaly Buka186280d2016-08-20 18:34:36 +00002537
2538 const size_t LargestStoreSizeInBytes =
2539 std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2540
2541 const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2542
2543 // Poison given range in shadow using larges store size with out leading and
Vitaly Buka793913c2016-08-29 18:17:21 +00002544 // trailing zeros in ShadowMask. Zeros never change, so they need neither
2545 // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2546 // middle of a store.
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002547 for (size_t i = Begin; i < End;) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002548 if (!ShadowMask[i]) {
2549 assert(!ShadowBytes[i]);
Vitaly Buka186280d2016-08-20 18:34:36 +00002550 ++i;
2551 continue;
2552 }
2553
2554 size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2555 // Fit store size into the range.
2556 while (StoreSizeInBytes > End - i)
2557 StoreSizeInBytes /= 2;
2558
2559 // Minimize store size by trimming trailing zeros.
Vitaly Buka793913c2016-08-29 18:17:21 +00002560 for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
Vitaly Buka186280d2016-08-20 18:34:36 +00002561 while (j <= StoreSizeInBytes / 2)
2562 StoreSizeInBytes /= 2;
2563 }
2564
2565 uint64_t Val = 0;
Vitaly Buka793913c2016-08-29 18:17:21 +00002566 for (size_t j = 0; j < StoreSizeInBytes; j++) {
2567 if (IsLittleEndian)
2568 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2569 else
2570 Val = (Val << 8) | ShadowBytes[i + j];
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002571 }
Vitaly Buka186280d2016-08-20 18:34:36 +00002572
2573 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2574 Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
Vitaly Buka0672a272016-08-22 04:16:14 +00002575 IRB.CreateAlignedStore(
2576 Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
Vitaly Buka186280d2016-08-20 18:34:36 +00002577
2578 i += StoreSizeInBytes;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002579 }
2580}
2581
Vitaly Buka793913c2016-08-29 18:17:21 +00002582void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2583 ArrayRef<uint8_t> ShadowBytes,
2584 IRBuilder<> &IRB, Value *ShadowBase) {
2585 copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2586}
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002587
Vitaly Buka793913c2016-08-29 18:17:21 +00002588void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2589 ArrayRef<uint8_t> ShadowBytes,
2590 size_t Begin, size_t End,
2591 IRBuilder<> &IRB, Value *ShadowBase) {
2592 assert(ShadowMask.size() == ShadowBytes.size());
2593 size_t Done = Begin;
2594 for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2595 if (!ShadowMask[i]) {
2596 assert(!ShadowBytes[i]);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002597 continue;
Vitaly Buka793913c2016-08-29 18:17:21 +00002598 }
2599 uint8_t Val = ShadowBytes[i];
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002600 if (!AsanSetShadowFunc[Val])
2601 continue;
2602
2603 // Skip same values.
Vitaly Buka793913c2016-08-29 18:17:21 +00002604 for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002605 }
2606
2607 if (j - i >= ClMaxInlinePoisoningSize) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002608 copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002609 IRB.CreateCall(AsanSetShadowFunc[Val],
2610 {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2611 ConstantInt::get(IntptrTy, j - i)});
2612 Done = j;
2613 }
2614 }
2615
Vitaly Buka793913c2016-08-29 18:17:21 +00002616 copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
Vitaly Buka1f9e1352016-08-20 20:23:50 +00002617}
2618
Kostya Serebryany6805de52013-09-10 13:16:56 +00002619// Fake stack allocator (asan_fake_stack.h) has 11 size classes
2620// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2621static int StackMallocSizeClass(uint64_t LocalStackSize) {
2622 assert(LocalStackSize <= kMaxStackMallocSize);
2623 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002624 for (int i = 0;; i++, MaxSize *= 2)
2625 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00002626 llvm_unreachable("impossible LocalStackSize");
2627}
2628
Vitaly Buka74443f02017-07-18 22:28:03 +00002629void FunctionStackPoisoner::copyArgsPassedByValToAllocas() {
Matt Morehouse49e5aca2017-08-09 17:59:43 +00002630 Instruction *CopyInsertPoint = &F.front().front();
2631 if (CopyInsertPoint == ASan.LocalDynamicShadow) {
2632 // Insert after the dynamic shadow location is determined
2633 CopyInsertPoint = CopyInsertPoint->getNextNode();
2634 assert(CopyInsertPoint);
2635 }
2636 IRBuilder<> IRB(CopyInsertPoint);
Vitaly Buka74443f02017-07-18 22:28:03 +00002637 const DataLayout &DL = F.getParent()->getDataLayout();
2638 for (Argument &Arg : F.args()) {
2639 if (Arg.hasByValAttr()) {
2640 Type *Ty = Arg.getType()->getPointerElementType();
2641 unsigned Align = Arg.getParamAlignment();
2642 if (Align == 0) Align = DL.getABITypeAlignment(Ty);
2643
2644 const std::string &Name = Arg.hasName() ? Arg.getName().str() :
2645 "Arg" + llvm::to_string(Arg.getArgNo());
2646 AllocaInst *AI = IRB.CreateAlloca(Ty, nullptr, Twine(Name) + ".byval");
2647 AI->setAlignment(Align);
2648 Arg.replaceAllUsesWith(AI);
2649
2650 uint64_t AllocSize = DL.getTypeAllocSize(Ty);
2651 IRB.CreateMemCpy(AI, &Arg, AllocSize, Align);
2652 }
2653 }
2654}
2655
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002656PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2657 Value *ValueIfTrue,
2658 Instruction *ThenTerm,
2659 Value *ValueIfFalse) {
2660 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2661 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2662 PHI->addIncoming(ValueIfFalse, CondBlock);
2663 BasicBlock *ThenBlock = ThenTerm->getParent();
2664 PHI->addIncoming(ValueIfTrue, ThenBlock);
2665 return PHI;
2666}
2667
2668Value *FunctionStackPoisoner::createAllocaForLayout(
2669 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2670 AllocaInst *Alloca;
2671 if (Dynamic) {
2672 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2673 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2674 "MyAlloca");
2675 } else {
2676 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2677 nullptr, "MyAlloca");
2678 assert(Alloca->isStaticAlloca());
2679 }
2680 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2681 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2682 Alloca->setAlignment(FrameAlignment);
2683 return IRB.CreatePointerCast(Alloca, IntptrTy);
2684}
2685
Yury Gribov98b18592015-05-28 07:51:49 +00002686void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2687 BasicBlock &FirstBB = *F.begin();
2688 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2689 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2690 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2691 DynamicAllocaLayout->setAlignment(32);
2692}
2693
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002694void FunctionStackPoisoner::processDynamicAllocas() {
2695 if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2696 assert(DynamicAllocaPoisonCallVec.empty());
2697 return;
2698 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002699
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002700 // Insert poison calls for lifetime intrinsics for dynamic allocas.
2701 for (const auto &APC : DynamicAllocaPoisonCallVec) {
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002702 assert(APC.InsBefore);
2703 assert(APC.AI);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002704 assert(ASan.isInterestingAlloca(*APC.AI));
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002705 assert(!APC.AI->isStaticAlloca());
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002706
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002707 IRBuilder<> IRB(APC.InsBefore);
2708 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Vitaly Bukab451f1b2016-06-09 23:31:59 +00002709 // Dynamic allocas will be unpoisoned unconditionally below in
2710 // unpoisonDynamicAllocas.
2711 // Flag that we need unpoison static allocas.
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00002712 }
2713
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002714 // Handle dynamic allocas.
2715 createDynamicAllocasInitStorage();
2716 for (auto &AI : DynamicAllocaVec)
2717 handleDynamicAllocaCall(AI);
2718 unpoisonDynamicAllocas();
2719}
Yury Gribov98b18592015-05-28 07:51:49 +00002720
Vitaly Buka5b4f1212016-08-20 17:22:27 +00002721void FunctionStackPoisoner::processStaticAllocas() {
2722 if (AllocaVec.empty()) {
2723 assert(StaticAllocaPoisonCallVec.empty());
2724 return;
Kuba Breckaf5875d32015-02-24 09:47:05 +00002725 }
Yury Gribov55441bb2014-11-21 10:29:50 +00002726
Kostya Serebryany6805de52013-09-10 13:16:56 +00002727 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002728 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00002729 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00002730 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002731
2732 Instruction *InsBefore = AllocaVec[0];
2733 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002734 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002735
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002736 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2737 // debug info is broken, because only entry-block allocas are treated as
2738 // regular stack slots.
2739 auto InsBeforeB = InsBefore->getParent();
2740 assert(InsBeforeB == &F.getEntryBlock());
Kuba Breckaa49dcbb2016-11-08 21:30:41 +00002741 for (auto *AI : StaticAllocasToMoveUp)
2742 if (AI->getParent() == InsBeforeB)
2743 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002744
Reid Kleckner2f907552015-07-21 17:40:14 +00002745 // If we have a call to llvm.localescape, keep it in the entry block.
2746 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2747
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002748 SmallVector<ASanStackVariableDescription, 16> SVD;
2749 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002750 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002751 ASanStackVariableDescription D = {AI->getName().data(),
Vitaly Buka21a9e572016-07-28 22:50:50 +00002752 ASan.getAllocaSizeInBytes(*AI),
Vitaly Bukad88e5202016-10-18 23:29:41 +00002753 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002754 AI->getAlignment(),
2755 AI,
Vitaly Bukad88e5202016-10-18 23:29:41 +00002756 0,
Vitaly Bukaf9fd63a2016-08-20 16:48:24 +00002757 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002758 SVD.push_back(D);
2759 }
Vitaly Buka5910a922016-10-18 23:29:52 +00002760
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002761 // Minimal header size (left redzone) is 4 pointers,
2762 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2763 size_t MinHeaderSize = ASan.LongSize / 2;
Vitaly Bukadb331d82016-08-29 17:41:29 +00002764 const ASanStackFrameLayout &L =
2765 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
Vitaly Buka793913c2016-08-29 18:17:21 +00002766
Vitaly Buka5910a922016-10-18 23:29:52 +00002767 // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2768 DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2769 for (auto &Desc : SVD)
2770 AllocaToSVDMap[Desc.AI] = &Desc;
2771
2772 // Update SVD with information from lifetime intrinsics.
2773 for (const auto &APC : StaticAllocaPoisonCallVec) {
2774 assert(APC.InsBefore);
2775 assert(APC.AI);
2776 assert(ASan.isInterestingAlloca(*APC.AI));
2777 assert(APC.AI->isStaticAlloca());
2778
2779 ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2780 Desc.LifetimeSize = Desc.Size;
2781 if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2782 if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2783 if (LifetimeLoc->getFile() == FnLoc->getFile())
2784 if (unsigned Line = LifetimeLoc->getLine())
2785 Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2786 }
2787 }
2788 }
2789
2790 auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2791 DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002792 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002793 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2794 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002795 bool DoDynamicAlloca = ClDynamicAllocaStack;
2796 // Don't do dynamic alloca or stack malloc if:
2797 // 1) There is inline asm: too often it makes assumptions on which registers
2798 // are available.
2799 // 2) There is a returns_twice call (typically setjmp), which is
2800 // optimization-hostile, and doesn't play well with introduced indirect
2801 // register-relative calculation of local variable addresses.
2802 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2803 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002804
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002805 Value *StaticAlloca =
2806 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2807
2808 Value *FakeStack;
2809 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002810
2811 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002812 // void *FakeStack = __asan_option_detect_stack_use_after_return
2813 // ? __asan_stack_malloc_N(LocalStackSize)
2814 // : nullptr;
2815 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002816 Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2817 kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2818 Value *UseAfterReturnIsEnabled =
2819 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002820 Constant::getNullValue(IRB.getInt32Ty()));
2821 Instruction *Term =
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002822 SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002823 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002824 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002825 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2826 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2827 Value *FakeStackValue =
2828 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2829 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002830 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002831 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Vitaly Buka7b8ed4f2016-06-02 00:06:42 +00002832 FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002833 ConstantInt::get(IntptrTy, 0));
2834
2835 Value *NoFakeStack =
2836 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2837 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2838 IRBIf.SetInsertPoint(Term);
2839 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2840 Value *AllocaValue =
2841 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2842 IRB.SetInsertPoint(InsBefore);
2843 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2844 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2845 } else {
2846 // void *FakeStack = nullptr;
2847 // void *LocalStackBase = alloca(LocalStackSize);
2848 FakeStack = ConstantInt::get(IntptrTy, 0);
2849 LocalStackBase =
2850 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002851 }
2852
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002853 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002854 for (const auto &Desc : SVD) {
2855 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002856 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002857 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002858 AI->getType());
Adrian Prantl109b2362017-04-28 17:51:05 +00002859 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, DIExpression::NoDeref);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002860 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002861 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002862
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002863 // The left-most redzone has enough space for at least 4 pointers.
2864 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002865 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2866 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2867 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002868 // Write the frame description constant to redzone[1].
2869 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002870 IRB.CreateAdd(LocalStackBase,
2871 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2872 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002873 GlobalVariable *StackDescriptionGlobal =
Vitaly Buka5910a922016-10-18 23:29:52 +00002874 createPrivateGlobalForString(*F.getParent(), DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002875 /*AllowMerging*/ true);
2876 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002877 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002878 // Write the PC to redzone[2].
2879 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002880 IRB.CreateAdd(LocalStackBase,
2881 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2882 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002883 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002884
Vitaly Buka793913c2016-08-29 18:17:21 +00002885 const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2886
2887 // Poison the stack red zones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002888 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Vitaly Buka793913c2016-08-29 18:17:21 +00002889 // As mask we must use most poisoned case: red zones and after scope.
2890 // As bytes we can use either the same or just red zones only.
2891 copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2892
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002893 if (!StaticAllocaPoisonCallVec.empty()) {
Vitaly Buka793913c2016-08-29 18:17:21 +00002894 const auto &ShadowInScope = GetShadowBytes(SVD, L);
2895
2896 // Poison static allocas near lifetime intrinsics.
2897 for (const auto &APC : StaticAllocaPoisonCallVec) {
Vitaly Buka5910a922016-10-18 23:29:52 +00002898 const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
Vitaly Buka793913c2016-08-29 18:17:21 +00002899 assert(Desc.Offset % L.Granularity == 0);
2900 size_t Begin = Desc.Offset / L.Granularity;
2901 size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2902
2903 IRBuilder<> IRB(APC.InsBefore);
2904 copyToShadow(ShadowAfterScope,
2905 APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2906 IRB, ShadowBase);
2907 }
2908 }
2909
2910 SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
Vitaly Buka793913c2016-08-29 18:17:21 +00002911 SmallVector<uint8_t, 64> ShadowAfterReturn;
Vitaly Buka186280d2016-08-20 18:34:36 +00002912
Kostya Serebryany530e2072013-12-23 14:15:08 +00002913 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002914 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002915 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002916 // Mark the current frame as retired.
2917 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2918 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002919 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002920 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002921 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002922 // // In use-after-return mode, poison the whole stack frame.
2923 // if StackMallocIdx <= 4
2924 // // For small sizes inline the whole thing:
2925 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002926 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002927 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002928 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002929 // else
2930 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002931 Value *Cmp =
2932 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002933 TerminatorInst *ThenTerm, *ElseTerm;
2934 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2935
2936 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002937 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002938 int ClassSize = kMinStackMallocSize << StackMallocIdx;
Vitaly Buka793913c2016-08-29 18:17:21 +00002939 ShadowAfterReturn.resize(ClassSize / L.Granularity,
2940 kAsanStackUseAfterReturnMagic);
2941 copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2942 ShadowBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002943 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002944 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002945 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2946 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2947 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2948 IRBPoison.CreateStore(
2949 Constant::getNullValue(IRBPoison.getInt8Ty()),
2950 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2951 } else {
2952 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002953 IRBPoison.CreateCall(
2954 AsanStackFreeFunc[StackMallocIdx],
2955 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002956 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002957
2958 IRBuilder<> IRBElse(ElseTerm);
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002959 copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002960 } else {
Vitaly Buka8e1906e2016-10-18 18:04:59 +00002961 copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002962 }
2963 }
2964
Kostya Serebryany09959942012-10-19 06:20:53 +00002965 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002966 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002967}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002968
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002969void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002970 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002971 // For now just insert the call to ASan runtime.
2972 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2973 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002974 IRB.CreateCall(
2975 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2976 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002977}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002978
2979// Handling llvm.lifetime intrinsics for a given %alloca:
2980// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2981// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2982// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2983// could be poisoned by previous llvm.lifetime.end instruction, as the
2984// variable may go in and out of scope several times, e.g. in loops).
2985// (3) if we poisoned at least one %alloca in a function,
2986// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002987
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002988AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2989 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
Etienne Bergeron9bd42812016-09-14 15:59:32 +00002990 // We're interested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002991 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002992 // See if we've already calculated (or started to calculate) alloca for a
2993 // given value.
2994 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002995 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002996 // Store 0 while we're calculating alloca for value V to avoid
2997 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002998 AllocaForValue[V] = nullptr;
2999 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003000 if (CastInst *CI = dyn_cast<CastInst>(V))
3001 Res = findAllocaForValue(CI->getOperand(0));
3002 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003003 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003004 // Allow self-referencing phi-nodes.
3005 if (IncValue == PN) continue;
3006 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
3007 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00003008 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
3009 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00003010 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003011 }
Vitaly Buka53054a72016-07-22 00:56:17 +00003012 } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
3013 Res = findAllocaForValue(EP->getPointerOperand());
3014 } else {
3015 DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003016 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003017 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00003018 return Res;
3019}
Yury Gribov55441bb2014-11-21 10:29:50 +00003020
Yury Gribov98b18592015-05-28 07:51:49 +00003021void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00003022 IRBuilder<> IRB(AI);
3023
Yury Gribov55441bb2014-11-21 10:29:50 +00003024 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
3025 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
3026
3027 Value *Zero = Constant::getNullValue(IntptrTy);
3028 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
3029 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00003030
3031 // Since we need to extend alloca with additional memory to locate
3032 // redzones, and OldSize is number of allocated blocks with
3033 // ElementSize size, get allocated memory size in bytes by
3034 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00003035 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003036 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00003037 Value *OldSize =
3038 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
3039 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00003040
3041 // PartialSize = OldSize % 32
3042 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
3043
3044 // Misalign = kAllocaRzSize - PartialSize;
3045 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
3046
3047 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
3048 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
3049 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
3050
3051 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
3052 // Align is added to locate left redzone, PartialPadding for possible
3053 // partial redzone and kAllocaRzSize for right redzone respectively.
3054 Value *AdditionalChunkSize = IRB.CreateAdd(
3055 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
3056
3057 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
3058
3059 // Insert new alloca with new NewSize and Align params.
3060 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
3061 NewAlloca->setAlignment(Align);
3062
3063 // NewAddress = Address + Align
3064 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
3065 ConstantInt::get(IntptrTy, Align));
3066
Yury Gribov98b18592015-05-28 07:51:49 +00003067 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00003068 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00003069
3070 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
3071 // for unpoisoning stuff.
3072 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
3073
Yury Gribov55441bb2014-11-21 10:29:50 +00003074 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
3075
Yury Gribov98b18592015-05-28 07:51:49 +00003076 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00003077 AI->replaceAllUsesWith(NewAddressPtr);
3078
Yury Gribov98b18592015-05-28 07:51:49 +00003079 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00003080 AI->eraseFromParent();
3081}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003082
3083// isSafeAccess returns true if Addr is always inbounds with respect to its
3084// base object. For example, it is a field access or an array access with
3085// constant inbounds index.
3086bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
3087 Value *Addr, uint64_t TypeSize) const {
3088 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
3089 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00003090 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003091 int64_t Offset = SizeOffset.second.getSExtValue();
3092 // Three checks are required to ensure safety:
3093 // . Offset >= 0 (since the offset is given from the base ptr)
3094 // . Size >= Offset (unsigned)
3095 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00003096 return Offset >= 0 && Size >= uint64_t(Offset) &&
3097 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00003098}