blob: a67a9a217a4ec9deddaa04639c954e10ba9e2672 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
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
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000027#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000037#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000043#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/DataTypes.h"
46#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000047#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000048#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000050#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000051#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000053#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000054#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000055#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000056#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000059#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060
61using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "asan"
64
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065static const uint64_t kDefaultShadowScale = 3;
66static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000069static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000070static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000071static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000072static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000073static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000074static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000075static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
76static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000077static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000078
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000079static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000080static const size_t kMaxStackMallocSize = 1 << 16; // 64K
81static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
82static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
83
Craig Topperd3a34f82013-07-16 01:17:10 +000084static const char *const kAsanModuleCtorName = "asan.module_ctor";
85static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000086static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000089static const char *const kAsanUnregisterGlobalsName =
90 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
92static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000093static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000094static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
95static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000097static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000098static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
99static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000101static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanPoisonStackMemoryName =
103 "__asan_poison_stack_memory";
104static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000105 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000106
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000107static const char *const kAsanOptionDetectUAR =
108 "__asan_option_detect_stack_use_after_return";
109
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000110static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
111static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000112
Kostya Serebryany874dae62012-07-16 16:15:40 +0000113// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
114static const size_t kNumberOfAccessSizes = 5;
115
Yury Gribov55441bb2014-11-21 10:29:50 +0000116static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000117
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000118// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000119static cl::opt<bool> ClEnableKasan(
120 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
121 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000122
123// This flag may need to be replaced with -f[no-]asan-reads.
124static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000125 cl::desc("instrument read instructions"),
126 cl::Hidden, cl::init(true));
127static cl::opt<bool> ClInstrumentWrites(
128 "asan-instrument-writes", cl::desc("instrument write instructions"),
129 cl::Hidden, cl::init(true));
130static cl::opt<bool> ClInstrumentAtomics(
131 "asan-instrument-atomics",
132 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
133 cl::init(true));
134static cl::opt<bool> ClAlwaysSlowPath(
135 "asan-always-slow-path",
136 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
137 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000138// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000139// in any given BB. Normally, this should be set to unlimited (INT_MAX),
140// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
141// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000142static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
143 "asan-max-ins-per-bb", cl::init(10000),
144 cl::desc("maximal number of instructions to instrument in any given BB"),
145 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000146// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000147static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
148 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000149static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150 cl::desc("Check return-after-free"),
151 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000152// This flag may need to be replaced with -f[no]asan-globals.
153static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000154 cl::desc("Handle global objects"), cl::Hidden,
155 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000156static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157 cl::desc("Handle C++ initializer order"),
158 cl::Hidden, cl::init(true));
159static cl::opt<bool> ClInvalidPointerPairs(
160 "asan-detect-invalid-pointer-pair",
161 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
162 cl::init(false));
163static cl::opt<unsigned> ClRealignStack(
164 "asan-realign-stack",
165 cl::desc("Realign stack to the value of this flag (power of two)"),
166 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000167static cl::opt<int> ClInstrumentationWithCallsThreshold(
168 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169 cl::desc(
170 "If the function being instrumented contains more than "
171 "this number of memory accesses, use callbacks instead of "
172 "inline checks (-1 means never use callbacks)."),
173 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000174static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000175 "asan-memory-access-callback-prefix",
176 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
177 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000178static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000179 cl::desc("instrument dynamic allocas"),
180 cl::Hidden, cl::init(false));
181static cl::opt<bool> ClSkipPromotableAllocas(
182 "asan-skip-promotable-allocas",
183 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
184 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185
186// These flags allow to change the shadow mapping.
187// The shadow mapping looks like
188// Shadow = (Mem >> scale) + (1 << offset_log)
189static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc("scale of asan shadow mapping"),
191 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000192
193// Optimization flags. Not user visible, used mostly for testing
194// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000195static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
196 cl::Hidden, cl::init(true));
197static cl::opt<bool> ClOptSameTemp(
198 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
199 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000200static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000201 cl::desc("Don't instrument scalar globals"),
202 cl::Hidden, cl::init(true));
203static cl::opt<bool> ClOptStack(
204 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
205 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000206
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000207static cl::opt<bool> ClCheckLifetime(
208 "asan-check-lifetime",
209 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
210 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000211
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000212static cl::opt<bool> ClDynamicAllocaStack(
213 "asan-stack-dynamic-alloca",
214 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000215 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000216
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000217static cl::opt<uint32_t> ClForceExperiment(
218 "asan-force-experiment",
219 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
220 cl::init(0));
221
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000222// Debug flags.
223static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
224 cl::init(0));
225static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
226 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000227static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
228 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
230 cl::Hidden, cl::init(-1));
231static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
232 cl::Hidden, cl::init(-1));
233
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000234STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
235STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000236STATISTIC(NumOptimizedAccessesToGlobalVar,
237 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000238STATISTIC(NumOptimizedAccessesToStackVar,
239 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000242/// Frontend-provided metadata for source location.
243struct LocationMetadata {
244 StringRef Filename;
245 int LineNo;
246 int ColumnNo;
247
248 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
249
250 bool empty() const { return Filename.empty(); }
251
252 void parse(MDNode *MDN) {
253 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000254 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
255 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000256 LineNo =
257 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
258 ColumnNo =
259 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000260 }
261};
262
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000263/// Frontend-provided metadata for global variables.
264class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000265 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000266 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000267 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000268 LocationMetadata SourceLoc;
269 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000270 bool IsDynInit;
271 bool IsBlacklisted;
272 };
273
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000274 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000275
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000276 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000277 assert(!inited_);
278 inited_ = true;
279 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000280 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000281 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000282 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000283 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000284 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000285 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000286 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 // We can already have an entry for GV if it was merged with another
288 // global.
289 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000290 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
291 E.SourceLoc.parse(Loc);
292 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
293 E.Name = Name->getString();
294 ConstantInt *IsDynInit =
295 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000296 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000297 ConstantInt *IsBlacklisted =
298 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000300 }
301 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000302
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000303 /// Returns metadata entry for a given global.
304 Entry get(GlobalVariable *G) const {
305 auto Pos = Entries.find(G);
306 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000307 }
308
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000309 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000310 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000312};
313
Alexey Samsonov1345d352013-01-16 13:23:28 +0000314/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000315/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000316struct ShadowMapping {
317 int Scale;
318 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000319 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000320};
321
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000322static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
323 bool IsKasan) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000324 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000325 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000326 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
327 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000328 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
329 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000330 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000331 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
332 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000333 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
334 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000335 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000336 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000337
338 ShadowMapping Mapping;
339
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000340 if (LongSize == 32) {
341 if (IsAndroid)
342 Mapping.Offset = 0;
343 else if (IsMIPS32)
344 Mapping.Offset = kMIPS32_ShadowOffset32;
345 else if (IsFreeBSD)
346 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000347 else if (IsIOS)
348 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000349 else if (IsWindows)
350 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000351 else
352 Mapping.Offset = kDefaultShadowOffset32;
353 } else { // LongSize == 64
354 if (IsPPC64)
355 Mapping.Offset = kPPC64_ShadowOffset64;
356 else if (IsFreeBSD)
357 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000358 else if (IsLinux && IsX86_64) {
359 if (IsKasan)
360 Mapping.Offset = kLinuxKasan_ShadowOffset64;
361 else
362 Mapping.Offset = kSmallX86_64ShadowOffset;
363 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000364 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000365 else if (IsAArch64)
366 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000367 else
368 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000369 }
370
371 Mapping.Scale = kDefaultShadowScale;
372 if (ClMappingScale) {
373 Mapping.Scale = ClMappingScale;
374 }
375
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000376 // OR-ing shadow offset if more efficient (at least on x86) if the offset
377 // is a power of two, but on ppc64 we have to use add since the shadow
378 // offset is not necessary 1/8-th of the address space.
379 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
380
Alexey Samsonov1345d352013-01-16 13:23:28 +0000381 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000382}
383
Alexey Samsonov1345d352013-01-16 13:23:28 +0000384static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000385 // Redzone used for stack and globals is at least 32 bytes.
386 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000387 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000388}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000389
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000391struct AddressSanitizer : public FunctionPass {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000392 explicit AddressSanitizer(bool CompileKernel = false)
393 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000394 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
395 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000396 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000397 return "AddressSanitizerFunctionPass";
398 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000399 void getAnalysisUsage(AnalysisUsage &AU) const override {
400 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000401 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000402 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000403 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
404 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 uint64_t SizeInBytes =
406 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000407 return SizeInBytes;
408 }
409 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000410 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000411
412 // Check if we have dynamic alloca.
413 bool isDynamicAlloca(AllocaInst &AI) const {
414 return AI.isArrayAllocation() || !AI.isStaticAlloca();
415 }
416
Anna Zaks8ed1d812015-02-27 03:12:36 +0000417 /// If it is an interesting memory access, return the PointerOperand
418 /// and set IsWrite/Alignment. Otherwise return nullptr.
419 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000420 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000421 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000423 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000424 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
425 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000426 Value *SizeArgument, bool UseCalls, uint32_t Exp);
427 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
428 uint32_t TypeSize, bool IsWrite,
429 Value *SizeArgument, bool UseCalls,
430 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000431 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
432 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000433 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000434 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000435 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000436 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000437 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000438 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000439 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000440 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000441 static char ID; // Pass identification, replacement for typeid
442
Yury Gribov3ae427d2014-12-01 08:47:58 +0000443 DominatorTree &getDominatorTree() const { return *DT; }
444
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000445 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000446 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000447
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000448 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000449 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000450 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
451 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000452
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000453 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000454 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000455 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000456 bool CompileKernel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000457 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000458 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000459 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000460 Function *AsanCtorFunction = nullptr;
461 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000462 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000463 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000464 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
465 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
466 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
467 // This array is indexed by AccessIsWrite and Experiment.
468 Function *AsanErrorCallbackSized[2][2];
469 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000470 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000471 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000472 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000473 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000474
475 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000476};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000477
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000478class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000479 public:
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000480 explicit AddressSanitizerModule(bool CompileKernel = false)
481 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000482 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000483 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000484 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000485
Kostya Serebryany20a79972012-11-22 03:18:50 +0000486 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000487 void initializeCallbacks(Module &M);
488
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000489 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000490 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000491 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000492 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000493 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000494 return RedzoneSizeForScale(Mapping.Scale);
495 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000496
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000497 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000498 bool CompileKernel;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000499 Type *IntptrTy;
500 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000501 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000502 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000503 Function *AsanPoisonGlobals;
504 Function *AsanUnpoisonGlobals;
505 Function *AsanRegisterGlobals;
506 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000507};
508
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000509// Stack poisoning does not play well with exception handling.
510// When an exception is thrown, we essentially bypass the code
511// that unpoisones the stack. This is why the run-time library has
512// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
513// stack in the interceptor. This however does not work inside the
514// actual function which catches the exception. Most likely because the
515// compiler hoists the load of the shadow value somewhere too high.
516// This causes asan to report a non-existing bug on 453.povray.
517// It sounds like an LLVM bug.
518struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
519 Function &F;
520 AddressSanitizer &ASan;
521 DIBuilder DIB;
522 LLVMContext *C;
523 Type *IntptrTy;
524 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000525 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000527 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000528 SmallVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000529 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000530 unsigned StackAlignment;
531
Kostya Serebryany6805de52013-09-10 13:16:56 +0000532 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000533 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000534 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000535 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000536
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000537 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
538 struct AllocaPoisonCall {
539 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000540 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000541 uint64_t Size;
542 bool DoPoison;
543 };
544 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
545
Yury Gribov98b18592015-05-28 07:51:49 +0000546 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
547 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
548 AllocaInst *DynamicAllocaLayout = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000549
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000550 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000551 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000552 AllocaForValueMapTy AllocaForValue;
553
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000554 bool HasNonEmptyInlineAsm;
555 std::unique_ptr<CallInst> EmptyInlineAsm;
556
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000557 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000558 : F(F),
559 ASan(ASan),
560 DIB(*F.getParent(), /*AllowUnresolved*/ false),
561 C(ASan.C),
562 IntptrTy(ASan.IntptrTy),
563 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
564 Mapping(ASan.Mapping),
565 StackAlignment(1 << Mapping.Scale),
566 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000567 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000568
569 bool runOnFunction() {
570 if (!ClStack) return false;
571 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000572 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000573
Yury Gribov55441bb2014-11-21 10:29:50 +0000574 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000575
576 initializeCallbacks(*F.getParent());
577
578 poisonStack();
579
580 if (ClDebugStack) {
581 DEBUG(dbgs() << F);
582 }
583 return true;
584 }
585
Yury Gribov55441bb2014-11-21 10:29:50 +0000586 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000587 // poisoned red zones around all of them.
588 // Then unpoison everything back before the function returns.
589 void poisonStack();
590
Yury Gribov98b18592015-05-28 07:51:49 +0000591 void createDynamicAllocasInitStorage();
592
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000593 // ----------------------- Visitors.
594 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000595 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000596
Yury Gribov98b18592015-05-28 07:51:49 +0000597 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
598 Value *SavedStack) {
599 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000600 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000601 {IRB.CreateLoad(DynamicAllocaLayout),
Yury Gribov781bce22015-05-28 08:03:28 +0000602 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000603 }
604
Yury Gribov55441bb2014-11-21 10:29:50 +0000605 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000606 void unpoisonDynamicAllocas() {
607 for (auto &Ret : RetVec)
608 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000609
Yury Gribov98b18592015-05-28 07:51:49 +0000610 for (auto &StackRestoreInst : StackRestoreVec)
611 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
612 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000613 }
614
Yury Gribov55441bb2014-11-21 10:29:50 +0000615 // Deploy and poison redzones around dynamic alloca call. To do this, we
616 // should replace this call with another one with changed parameters and
617 // replace all its uses with new address, so
618 // addr = alloca type, old_size, align
619 // is replaced by
620 // new_size = (old_size + additional_size) * sizeof(type)
621 // tmp = alloca i8, new_size, max(align, 32)
622 // addr = tmp + 32 (first 32 bytes are for the left redzone).
623 // Additional_size is added to make new memory allocation contain not only
624 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000625 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000626
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000627 /// \brief Collect Alloca instructions we want (and can) handle.
628 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000629 if (!ASan.isInterestingAlloca(AI)) {
630 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.push_back(&AI);
631 return;
632 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000633
634 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000635 if (ASan.isDynamicAlloca(AI))
636 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000637 else
638 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000639 }
640
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000641 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
642 /// errors.
643 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000644 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000645 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
646 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000647 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000648 return;
649 // Found lifetime intrinsic, add ASan instrumentation if necessary.
650 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
651 // If size argument is undefined, don't do anything.
652 if (Size->isMinusOne()) return;
653 // Check that size doesn't saturate uint64_t and can
654 // be stored in IntptrTy.
655 const uint64_t SizeValue = Size->getValue().getLimitedValue();
656 if (SizeValue == ~0ULL ||
657 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
658 return;
659 // Find alloca instruction that corresponds to llvm.lifetime argument.
660 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
661 if (!AI) return;
662 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000663 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000664 AllocaPoisonCallVec.push_back(APC);
665 }
666
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000667 void visitCallInst(CallInst &CI) {
668 HasNonEmptyInlineAsm |=
669 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
670 }
671
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000672 // ---------------------- Helpers.
673 void initializeCallbacks(Module &M);
674
Yury Gribov3ae427d2014-12-01 08:47:58 +0000675 bool doesDominateAllExits(const Instruction *I) const {
676 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000677 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000678 }
679 return true;
680 }
681
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000682 /// Finds alloca where the value comes from.
683 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000684 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000685 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000686 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000687
688 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
689 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000690 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
691 bool Dynamic);
692 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
693 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000694};
695
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000696} // namespace
697
698char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000699INITIALIZE_PASS_BEGIN(
700 AddressSanitizer, "asan",
701 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
702 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000703INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000704INITIALIZE_PASS_END(
705 AddressSanitizer, "asan",
706 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
707 false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000708FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
709 return new AddressSanitizer(CompileKernel);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000710}
711
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000712char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000713INITIALIZE_PASS(
714 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000715 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000716 "ModulePass",
717 false, false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000718ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
719 return new AddressSanitizerModule(CompileKernel);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000720}
721
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000722static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000723 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000724 assert(Res < kNumberOfAccessSizes);
725 return Res;
726}
727
Bill Wendling58f8cef2013-08-06 22:52:42 +0000728// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000729static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
730 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000731 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000732 // We use private linkage for module-local strings. If they can be merged
733 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000734 GlobalVariable *GV =
735 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000736 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000737 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000738 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
739 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000740}
741
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000742/// \brief Create a global describing a source location.
743static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
744 LocationMetadata MD) {
745 Constant *LocData[] = {
746 createPrivateGlobalForString(M, MD.Filename, true),
747 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
748 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
749 };
750 auto LocStruct = ConstantStruct::getAnon(LocData);
751 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
752 GlobalValue::PrivateLinkage, LocStruct,
753 kAsanGenPrefix);
754 GV->setUnnamedAddr(true);
755 return GV;
756}
757
Kostya Serebryany139a9372012-11-20 14:16:08 +0000758static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000759 return G->getName().find(kAsanGenPrefix) == 0 ||
760 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000761}
762
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000763Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
764 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000765 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000766 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000767 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000768 if (Mapping.OrShadowOffset)
769 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
770 else
771 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000772}
773
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000774// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000775void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
776 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000777 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000778 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000779 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000780 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
781 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
782 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000783 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000784 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000785 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000786 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
787 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
788 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000789 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000790 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000791}
792
Anna Zaks8ed1d812015-02-27 03:12:36 +0000793/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000794bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
795 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
796
797 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
798 return PreviouslySeenAllocaInfo->getSecond();
799
Yury Gribov98b18592015-05-28 07:51:49 +0000800 bool IsInteresting =
801 (AI.getAllocatedType()->isSized() &&
802 // alloca() may be called with 0 size, ignore it.
803 getAllocaSizeInBytes(&AI) > 0 &&
804 // We are only interested in allocas not promotable to registers.
805 // Promotable allocas are common under -O0.
806 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
807 isDynamicAlloca(AI)));
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000808
809 ProcessedAllocas[&AI] = IsInteresting;
810 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000811}
812
813/// If I is an interesting memory access, return the PointerOperand
814/// and set IsWrite/Alignment. Otherwise return nullptr.
815Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
816 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000817 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000818 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000819 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000820 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000821
822 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000823 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000824 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000825 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000826 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000827 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000828 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000829 PtrOperand = LI->getPointerOperand();
830 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000831 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000832 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000833 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000834 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000835 PtrOperand = SI->getPointerOperand();
836 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000837 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000838 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000839 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000840 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000841 PtrOperand = RMW->getPointerOperand();
842 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000844 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000845 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000846 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000847 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000848 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000849
850 // Treat memory accesses to promotable allocas as non-interesting since they
851 // will not cause memory violations. This greatly speeds up the instrumented
852 // executable at -O0.
853 if (ClSkipPromotableAllocas)
854 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
855 return isInterestingAlloca(*AI) ? AI : nullptr;
856
857 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000858}
859
Kostya Serebryany796f6552014-02-27 12:45:36 +0000860static bool isPointerOperand(Value *V) {
861 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
862}
863
864// This is a rough heuristic; it may cause both false positives and
865// false negatives. The proper implementation requires cooperation with
866// the frontend.
867static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
868 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000869 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000870 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000871 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000872 } else {
873 return false;
874 }
875 if (!isPointerOperand(I->getOperand(0)) ||
876 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000877 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000878 return true;
879}
880
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000881bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
882 // If a global variable does not have dynamic initialization we don't
883 // have to instrument it. However, if a global does not have initializer
884 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000885 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000886}
887
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000888void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
889 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000890 IRBuilder<> IRB(I);
891 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
892 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
893 for (int i = 0; i < 2; i++) {
894 if (Param[i]->getType()->isPointerTy())
895 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
896 }
David Blaikieff6409d2015-05-18 22:13:54 +0000897 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000898}
899
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000900void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000901 Instruction *I, bool UseCalls,
902 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000903 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000904 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000905 uint64_t TypeSize = 0;
906 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000907 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000908
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000909 // Optimization experiments.
910 // The experiments can be used to evaluate potential optimizations that remove
911 // instrumentation (assess false negatives). Instead of completely removing
912 // some instrumentation, you set Exp to a non-zero value (mask of optimization
913 // experiments that want to remove instrumentation of this instruction).
914 // If Exp is non-zero, this pass will emit special calls into runtime
915 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
916 // make runtime terminate the program in a special way (with a different
917 // exit status). Then you run the new compiler on a buggy corpus, collect
918 // the special terminations (ideally, you don't see them at all -- no false
919 // negatives) and make the decision on the optimization.
920 uint32_t Exp = ClForceExperiment;
921
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000922 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000923 // If initialization order checking is disabled, a simple access to a
924 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000925 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000926 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
927 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
928 NumOptimizedAccessesToGlobalVar++;
929 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000930 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000931 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000932
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000933 if (ClOpt && ClOptStack) {
934 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000935 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000936 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
937 NumOptimizedAccessesToStackVar++;
938 return;
939 }
940 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000941
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000942 if (IsWrite)
943 NumInstrumentedWrites++;
944 else
945 NumInstrumentedReads++;
946
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000947 unsigned Granularity = 1 << Mapping.Scale;
948 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
949 // if the data is properly aligned.
950 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
951 TypeSize == 128) &&
952 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000953 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
954 Exp);
955 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
956 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000957}
958
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000959Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
960 Value *Addr, bool IsWrite,
961 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000962 Value *SizeArgument,
963 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000964 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000965 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
966 CallInst *Call = nullptr;
967 if (SizeArgument) {
968 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +0000969 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
970 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000971 else
David Blaikieff6409d2015-05-18 22:13:54 +0000972 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
973 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000974 } else {
975 if (Exp == 0)
976 Call =
977 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
978 else
David Blaikieff6409d2015-05-18 22:13:54 +0000979 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
980 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000981 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000982
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000983 // We don't do Call->setDoesNotReturn() because the BB already has
984 // UnreachableInst at the end.
985 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +0000986 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000987 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000988}
989
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000990Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000991 Value *ShadowValue,
992 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000993 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000994 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000995 Value *LastAccessedByte =
996 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000997 // (Addr & (Granularity - 1)) + size - 1
998 if (TypeSize / 8 > 1)
999 LastAccessedByte = IRB.CreateAdd(
1000 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1001 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001002 LastAccessedByte =
1003 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001004 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1005 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1006}
1007
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001008void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001009 Instruction *InsertBefore, Value *Addr,
1010 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001011 Value *SizeArgument, bool UseCalls,
1012 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001013 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001014 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001015 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1016
1017 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001018 if (Exp == 0)
1019 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1020 AddrLong);
1021 else
David Blaikieff6409d2015-05-18 22:13:54 +00001022 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1023 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001024 return;
1025 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001026
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001027 Type *ShadowTy =
1028 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1030 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1031 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001032 Value *ShadowValue =
1033 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001034
1035 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001036 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001037 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001038
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001039 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001040 // We use branch weights for the slow path check, to indicate that the slow
1041 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001042 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1043 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001044 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001045 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001046 IRB.SetInsertPoint(CheckTerm);
1047 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001048 BasicBlock *CrashBlock =
1049 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001050 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001051 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1052 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001053 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001054 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001055 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001056
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001057 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001058 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001059 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001060}
1061
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001062// Instrument unusual size or unusual alignment.
1063// We can not do it with a single check, so we do 1-byte check for the first
1064// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1065// to report the actual access size.
1066void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1067 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1068 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1069 IRBuilder<> IRB(I);
1070 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1071 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1072 if (UseCalls) {
1073 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001074 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1075 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001076 else
David Blaikieff6409d2015-05-18 22:13:54 +00001077 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1078 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001079 } else {
1080 Value *LastByte = IRB.CreateIntToPtr(
1081 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1082 Addr->getType());
1083 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1084 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1085 }
1086}
1087
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001088void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1089 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001090 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001091 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001092
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001093 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001094 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1095 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001096
1097 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001098 for (auto &BB : GlobalInit.getBasicBlockList())
1099 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001100 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001101}
1102
1103void AddressSanitizerModule::createInitializerPoisonCalls(
1104 Module &M, GlobalValue *ModuleName) {
1105 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1106
1107 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1108 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001109 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001110 ConstantStruct *CS = cast<ConstantStruct>(OP);
1111
1112 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001113 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001114 if (F->getName() == kAsanModuleCtorName) continue;
1115 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1116 // Don't instrument CTORs that will run before asan.module_ctor.
1117 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1118 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001119 }
1120 }
1121}
1122
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001123bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001125 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001126
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001127 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001128 if (!Ty->isSized()) return false;
1129 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001130 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001131 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001132 // Don't handle ODR linkage types and COMDATs since other modules may be built
1133 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001134 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1135 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1136 G->getLinkage() != GlobalVariable::InternalLinkage)
1137 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001138 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001139 // Two problems with thread-locals:
1140 // - The address of the main thread's copy can't be computed at link-time.
1141 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001142 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001143 // For now, just ignore this Global if the alignment is large.
1144 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001145
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001146 if (G->hasSection()) {
1147 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001148
Anna Zaks11904602015-06-09 00:58:08 +00001149 // Globals from llvm.metadata aren't emitted, do not instrument them.
1150 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001151 // Do not instrument globals from special LLVM sections.
1152 if (Section.find("__llvm") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001153
1154 // Callbacks put into the CRT initializer/terminator sections
1155 // should not be instrumented.
1156 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1157 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1158 if (Section.startswith(".CRT")) {
1159 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1160 return false;
1161 }
1162
Kuba Brecka1001bb52014-12-05 22:19:18 +00001163 if (TargetTriple.isOSBinFormatMachO()) {
1164 StringRef ParsedSegment, ParsedSection;
1165 unsigned TAA = 0, StubSize = 0;
1166 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001167 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1168 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001169 if (!ErrorCode.empty()) {
Anna Zaks11904602015-06-09 00:58:08 +00001170 assert(false && "Invalid section specifier.");
1171 return false;
Kuba Brecka1001bb52014-12-05 22:19:18 +00001172 }
1173
1174 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1175 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1176 // them.
1177 if (ParsedSegment == "__OBJC" ||
1178 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1179 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1180 return false;
1181 }
1182 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1183 // Constant CFString instances are compiled in the following way:
1184 // -- the string buffer is emitted into
1185 // __TEXT,__cstring,cstring_literals
1186 // -- the constant NSConstantString structure referencing that buffer
1187 // is placed into __DATA,__cfstring
1188 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1189 // Moreover, it causes the linker to crash on OS X 10.7
1190 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1191 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1192 return false;
1193 }
1194 // The linker merges the contents of cstring_literals and removes the
1195 // trailing zeroes.
1196 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1197 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1198 return false;
1199 }
1200 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001201 }
1202
1203 return true;
1204}
1205
Alexey Samsonov788381b2012-12-25 12:28:20 +00001206void AddressSanitizerModule::initializeCallbacks(Module &M) {
1207 IRBuilder<> IRB(*C);
1208 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001209 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001210 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001211 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001212 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001213 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001214 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1215 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001216 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001217 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001218 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001219 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001220 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1221 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001222 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1223}
1224
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001225// This function replaces all global variables with new variables that have
1226// trailing redzones. It also creates a function that poisons
1227// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001228bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001229 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001230
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001231 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1232
Alexey Samsonova02e6642014-05-29 18:40:48 +00001233 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001234 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001235 }
1236
1237 size_t n = GlobalsToChange.size();
1238 if (n == 0) return false;
1239
1240 // A global is described by a structure
1241 // size_t beg;
1242 // size_t size;
1243 // size_t size_with_redzone;
1244 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001245 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001246 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001247 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001248 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001249 StructType *GlobalStructTy =
1250 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001251 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001252 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001253
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001254 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001255
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001256 // We shouldn't merge same module names, as this string serves as unique
1257 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001258 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001259 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001260
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001261 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001262 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001263 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001264 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001265
1266 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001267 // Create string holding the global name (use global name from metadata
1268 // if it's available, otherwise just write the name of global variable).
1269 GlobalVariable *Name = createPrivateGlobalForString(
1270 M, MD.Name.empty() ? G->getName() : MD.Name,
1271 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001272
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001273 PointerType *PtrTy = cast<PointerType>(G->getType());
1274 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001275 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001276 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001277 // MinRZ <= RZ <= kMaxGlobalRedzone
1278 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001279 uint64_t RZ = std::max(
1280 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001281 uint64_t RightRedzoneSize = RZ;
1282 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001283 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001284 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001285 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1286
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001287 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001288 Constant *NewInitializer =
1289 ConstantStruct::get(NewTy, G->getInitializer(),
1290 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001291
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001292 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001293 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1294 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1295 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001296 GlobalVariable *NewGlobal =
1297 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1298 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001299 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001300 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001301
1302 Value *Indices2[2];
1303 Indices2[0] = IRB.getInt32(0);
1304 Indices2[1] = IRB.getInt32(0);
1305
1306 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001307 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001308 NewGlobal->takeName(G);
1309 G->eraseFromParent();
1310
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001311 Constant *SourceLoc;
1312 if (!MD.SourceLoc.empty()) {
1313 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1314 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1315 } else {
1316 SourceLoc = ConstantInt::get(IntptrTy, 0);
1317 }
1318
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001319 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001320 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001321 ConstantInt::get(IntptrTy, SizeInBytes),
1322 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1323 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001324 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001325 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001326
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001327 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001328
Kostya Serebryany20343352012-10-17 13:40:06 +00001329 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001330 }
1331
1332 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1333 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001334 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001335 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1336
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001337 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001338 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001339 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001340 IRB.CreateCall(AsanRegisterGlobals,
1341 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1342 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001343
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001344 // We also need to unregister globals at the end, e.g. when a shared library
1345 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001346 Function *AsanDtorFunction =
1347 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1348 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001349 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1350 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001351 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1352 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1353 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001354 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001355
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001356 DEBUG(dbgs() << M);
1357 return true;
1358}
1359
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001360bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001361 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001362 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001363 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001364 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001365 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001366 initializeCallbacks(M);
1367
1368 bool Changed = false;
1369
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001370 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1371 if (ClGlobals && !CompileKernel) {
1372 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1373 assert(CtorFunc);
1374 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1375 Changed |= InstrumentGlobals(IRB, M);
1376 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001377
1378 return Changed;
1379}
1380
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001381void AddressSanitizer::initializeCallbacks(Module &M) {
1382 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001383 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001384 // IsWrite, TypeSize and Exp are encoded in the function name.
1385 for (int Exp = 0; Exp < 2; Exp++) {
1386 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1387 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1388 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001389 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1390 const std::string EndingStr = CompileKernel ? "_noabort" : "";
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001391 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001392 // TODO(glider): for KASan builds add _noabort to error reporting
1393 // functions and make them actually noabort (remove the UnreachableInst).
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001394 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001395 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001396 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001397 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1398 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001399 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001400 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001401 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1402 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1403 AccessSizeIndex++) {
1404 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1405 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001406 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001407 kAsanReportErrorTemplate + ExpStr + Suffix,
1408 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001409 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001410 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001411 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1412 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001413 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001414 }
1415 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001416
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001417 const std::string MemIntrinCallbackPrefix =
1418 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001419 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001420 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001421 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001422 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001423 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001424 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001425 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001426 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001427 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001428
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001429 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001430 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001431
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001432 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001433 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001434 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001435 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001436 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1437 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1438 StringRef(""), StringRef(""),
1439 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001440}
1441
1442// virtual
1443bool AddressSanitizer::doInitialization(Module &M) {
1444 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001445
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001446 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001447
1448 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001449 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001450 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001451 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001452
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001453 if (!CompileKernel) {
1454 std::tie(AsanCtorFunction, AsanInitFunction) =
1455 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1456 /*InitArgTypes=*/{},
1457 /*InitArgs=*/{});
1458 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1459 }
1460 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001461 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001462}
1463
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001464bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1465 // For each NSObject descendant having a +load method, this method is invoked
1466 // by the ObjC runtime before any of the static constructors is called.
1467 // Therefore we need to instrument such methods with a call to __asan_init
1468 // at the beginning in order to initialize our runtime before any access to
1469 // the shadow memory.
1470 // We cannot just ignore these methods, because they may call other
1471 // instrumented functions.
1472 if (F.getName().find(" load]") != std::string::npos) {
1473 IRBuilder<> IRB(F.begin()->begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001474 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001475 return true;
1476 }
1477 return false;
1478}
1479
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001480bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001481 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001482 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001483 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001484 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001485
Yury Gribov3ae427d2014-12-01 08:47:58 +00001486 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1487
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001488 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001489 maybeInsertAsanInitAtFunctionEntry(F);
1490
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001491 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001492
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001493 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001494
1495 // We want to instrument every address only once per basic block (unless there
1496 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001497 SmallSet<Value *, 16> TempsToInstrument;
1498 SmallVector<Instruction *, 16> ToInstrument;
1499 SmallVector<Instruction *, 8> NoReturnCalls;
1500 SmallVector<BasicBlock *, 16> AllBlocks;
1501 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001502 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001503 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001504 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001505 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001506
1507 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001508 for (auto &BB : F) {
1509 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001511 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001512 for (auto &Inst : BB) {
1513 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001514 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1515 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001516 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001517 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001518 continue; // We've seen this temp in the current BB.
1519 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001520 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001521 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1522 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001523 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001524 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001525 // ok, take it.
1526 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001527 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001528 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001529 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530 // A call inside BB.
1531 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001532 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001533 }
1534 continue;
1535 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001536 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001537 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001538 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001539 }
1540 }
1541
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001542 bool UseCalls =
1543 CompileKernel ||
1544 (ClInstrumentationWithCallsThreshold >= 0 &&
1545 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001546 const TargetLibraryInfo *TLI =
1547 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001548 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001549 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1550 /*RoundToAlign=*/true);
1551
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001552 // Instrument.
1553 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001554 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001555 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1556 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001557 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001558 instrumentMop(ObjSizeVis, Inst, UseCalls,
1559 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001560 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001561 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001562 }
1563 NumInstrumented++;
1564 }
1565
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001566 FunctionStackPoisoner FSP(F, *this);
1567 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001568
1569 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1570 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001571 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001572 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001573 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001574 }
1575
Alexey Samsonova02e6642014-05-29 18:40:48 +00001576 for (auto Inst : PointerComparisonsOrSubtracts) {
1577 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001578 NumInstrumented++;
1579 }
1580
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001581 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001582
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001583 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1584
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001585 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001586}
1587
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001588// Workaround for bug 11395: we don't want to instrument stack in functions
1589// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1590// FIXME: remove once the bug 11395 is fixed.
1591bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1592 if (LongSize != 32) return false;
1593 CallInst *CI = dyn_cast<CallInst>(I);
1594 if (!CI || !CI->isInlineAsm()) return false;
1595 if (CI->getNumArgOperands() <= 5) return false;
1596 // We have inline assembly with quite a few arguments.
1597 return true;
1598}
1599
1600void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1601 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001602 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1603 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001604 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1605 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1606 IntptrTy, nullptr));
1607 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001608 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1609 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001610 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001611 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001612 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1613 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001614 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001615 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1616 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001617 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1618 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1619 AsanAllocasUnpoisonFunc =
1620 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1621 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001622}
1623
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001624void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1625 IRBuilder<> &IRB, Value *ShadowBase,
1626 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001627 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001628 size_t i = 0;
1629 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1630 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1631 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1632 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1633 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1634 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1635 uint64_t Val = 0;
1636 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001637 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001638 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1639 else
1640 Val = (Val << 8) | ShadowBytes[i + j];
1641 }
1642 if (!Val) continue;
1643 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1644 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1645 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1646 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001647 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001648 }
1649}
1650
Kostya Serebryany6805de52013-09-10 13:16:56 +00001651// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1652// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1653static int StackMallocSizeClass(uint64_t LocalStackSize) {
1654 assert(LocalStackSize <= kMaxStackMallocSize);
1655 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001656 for (int i = 0;; i++, MaxSize *= 2)
1657 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001658 llvm_unreachable("impossible LocalStackSize");
1659}
1660
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001661// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1662// We can not use MemSet intrinsic because it may end up calling the actual
1663// memset. Size is a multiple of 8.
1664// Currently this generates 8-byte stores on x86_64; it may be better to
1665// generate wider stores.
1666void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1667 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1668 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001669
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001670 // kAsanStackAfterReturnMagic is 0xf5.
1671 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001672
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001673 for (int i = 0; i < Size; i += 8) {
1674 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001675 IRB.CreateStore(
1676 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1677 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001678 }
1679}
1680
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001681PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1682 Value *ValueIfTrue,
1683 Instruction *ThenTerm,
1684 Value *ValueIfFalse) {
1685 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1686 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1687 PHI->addIncoming(ValueIfFalse, CondBlock);
1688 BasicBlock *ThenBlock = ThenTerm->getParent();
1689 PHI->addIncoming(ValueIfTrue, ThenBlock);
1690 return PHI;
1691}
1692
1693Value *FunctionStackPoisoner::createAllocaForLayout(
1694 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1695 AllocaInst *Alloca;
1696 if (Dynamic) {
1697 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1698 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1699 "MyAlloca");
1700 } else {
1701 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1702 nullptr, "MyAlloca");
1703 assert(Alloca->isStaticAlloca());
1704 }
1705 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1706 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1707 Alloca->setAlignment(FrameAlignment);
1708 return IRB.CreatePointerCast(Alloca, IntptrTy);
1709}
1710
Yury Gribov98b18592015-05-28 07:51:49 +00001711void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1712 BasicBlock &FirstBB = *F.begin();
1713 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1714 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1715 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1716 DynamicAllocaLayout->setAlignment(32);
1717}
1718
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001719void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001720 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1721
Yury Gribov98b18592015-05-28 07:51:49 +00001722 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001723 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001724 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001725 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001726
1727 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001728 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001729
1730 if (AllocaVec.size() == 0) return;
1731
Kostya Serebryany6805de52013-09-10 13:16:56 +00001732 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001733 DebugLoc EntryDebugLocation;
1734 if (auto SP = getDISubprogram(&F))
1735 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001736
1737 Instruction *InsBefore = AllocaVec[0];
1738 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001739 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001740
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001741 for (auto *AI : NonInstrumentedStaticAllocaVec) AI->moveBefore(InsBefore);
1742
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001743 SmallVector<ASanStackVariableDescription, 16> SVD;
1744 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001745 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001746 ASanStackVariableDescription D = {AI->getName().data(),
1747 ASan.getAllocaSizeInBytes(AI),
1748 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001749 SVD.push_back(D);
1750 }
1751 // Minimal header size (left redzone) is 4 pointers,
1752 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1753 size_t MinHeaderSize = ASan.LongSize / 2;
1754 ASanStackFrameLayout L;
1755 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1756 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1757 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001758 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1759 LocalStackSize <= kMaxStackMallocSize;
Anna Zaks4f652b62015-06-25 23:35:45 +00001760 // Don't do dynamic alloca or stack malloc in presence of inline asm:
1761 // too often it makes assumptions on which registers are available.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001762 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Anna Zaks4f652b62015-06-25 23:35:45 +00001763 DoStackMalloc &= !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001764
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001765 Value *StaticAlloca =
1766 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1767
1768 Value *FakeStack;
1769 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001770
1771 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001772 // void *FakeStack = __asan_option_detect_stack_use_after_return
1773 // ? __asan_stack_malloc_N(LocalStackSize)
1774 // : nullptr;
1775 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001776 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1777 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001778 Value *UARIsEnabled =
1779 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1780 Constant::getNullValue(IRB.getInt32Ty()));
1781 Instruction *Term =
1782 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001783 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001784 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001785 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1786 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1787 Value *FakeStackValue =
1788 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1789 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001790 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001791 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001792 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1793 ConstantInt::get(IntptrTy, 0));
1794
1795 Value *NoFakeStack =
1796 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1797 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1798 IRBIf.SetInsertPoint(Term);
1799 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1800 Value *AllocaValue =
1801 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1802 IRB.SetInsertPoint(InsBefore);
1803 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1804 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1805 } else {
1806 // void *FakeStack = nullptr;
1807 // void *LocalStackBase = alloca(LocalStackSize);
1808 FakeStack = ConstantInt::get(IntptrTy, 0);
1809 LocalStackBase =
1810 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001811 }
1812
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001813 // Insert poison calls for lifetime intrinsics for alloca.
1814 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001815 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001816 assert(APC.InsBefore);
1817 assert(APC.AI);
1818 IRBuilder<> IRB(APC.InsBefore);
1819 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001820 HavePoisonedAllocas |= APC.DoPoison;
1821 }
1822
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001823 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001824 for (const auto &Desc : SVD) {
1825 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001826 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001827 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001828 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001829 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001830 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001831 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001832
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001833 // The left-most redzone has enough space for at least 4 pointers.
1834 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001835 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1836 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1837 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001838 // Write the frame description constant to redzone[1].
1839 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001840 IRB.CreateAdd(LocalStackBase,
1841 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1842 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001843 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001844 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001845 /*AllowMerging*/ true);
1846 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001847 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001848 // Write the PC to redzone[2].
1849 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001850 IRB.CreateAdd(LocalStackBase,
1851 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1852 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001853 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001854
1855 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001856 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001857 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001858
Kostya Serebryany530e2072013-12-23 14:15:08 +00001859 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001860 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001861 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001862 // Mark the current frame as retired.
1863 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1864 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001865 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001866 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001867 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001868 // // In use-after-return mode, poison the whole stack frame.
1869 // if StackMallocIdx <= 4
1870 // // For small sizes inline the whole thing:
1871 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001872 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001873 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001874 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001875 // else
1876 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001877 Value *Cmp =
1878 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001879 TerminatorInst *ThenTerm, *ElseTerm;
1880 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1881
1882 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001883 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001884 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1885 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1886 ClassSize >> Mapping.Scale);
1887 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001888 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001889 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1890 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1891 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1892 IRBPoison.CreateStore(
1893 Constant::getNullValue(IRBPoison.getInt8Ty()),
1894 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1895 } else {
1896 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001897 IRBPoison.CreateCall(
1898 AsanStackFreeFunc[StackMallocIdx],
1899 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001900 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001901
1902 IRBuilder<> IRBElse(ElseTerm);
1903 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001904 } else if (HavePoisonedAllocas) {
1905 // If we poisoned some allocas in llvm.lifetime analysis,
1906 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001907 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001908 } else {
1909 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001910 }
1911 }
1912
Kostya Serebryany09959942012-10-19 06:20:53 +00001913 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001914 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001915}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001916
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001917void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001918 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001919 // For now just insert the call to ASan runtime.
1920 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1921 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001922 IRB.CreateCall(
1923 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1924 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00001925}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001926
1927// Handling llvm.lifetime intrinsics for a given %alloca:
1928// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1929// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1930// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1931// could be poisoned by previous llvm.lifetime.end instruction, as the
1932// variable may go in and out of scope several times, e.g. in loops).
1933// (3) if we poisoned at least one %alloca in a function,
1934// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001935
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001936AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1937 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1938 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001939 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001940 // See if we've already calculated (or started to calculate) alloca for a
1941 // given value.
1942 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001943 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001944 // Store 0 while we're calculating alloca for value V to avoid
1945 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001946 AllocaForValue[V] = nullptr;
1947 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001948 if (CastInst *CI = dyn_cast<CastInst>(V))
1949 Res = findAllocaForValue(CI->getOperand(0));
1950 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00001951 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001952 // Allow self-referencing phi-nodes.
1953 if (IncValue == PN) continue;
1954 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1955 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001956 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1957 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001958 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001959 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001960 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001961 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001962 return Res;
1963}
Yury Gribov55441bb2014-11-21 10:29:50 +00001964
Yury Gribov98b18592015-05-28 07:51:49 +00001965void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001966 IRBuilder<> IRB(AI);
1967
Yury Gribov55441bb2014-11-21 10:29:50 +00001968 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1969 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1970
1971 Value *Zero = Constant::getNullValue(IntptrTy);
1972 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1973 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00001974
1975 // Since we need to extend alloca with additional memory to locate
1976 // redzones, and OldSize is number of allocated blocks with
1977 // ElementSize size, get allocated memory size in bytes by
1978 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00001979 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001980 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00001981 Value *OldSize =
1982 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1983 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00001984
1985 // PartialSize = OldSize % 32
1986 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1987
1988 // Misalign = kAllocaRzSize - PartialSize;
1989 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1990
1991 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1992 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1993 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1994
1995 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1996 // Align is added to locate left redzone, PartialPadding for possible
1997 // partial redzone and kAllocaRzSize for right redzone respectively.
1998 Value *AdditionalChunkSize = IRB.CreateAdd(
1999 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2000
2001 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2002
2003 // Insert new alloca with new NewSize and Align params.
2004 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2005 NewAlloca->setAlignment(Align);
2006
2007 // NewAddress = Address + Align
2008 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2009 ConstantInt::get(IntptrTy, Align));
2010
Yury Gribov98b18592015-05-28 07:51:49 +00002011 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002012 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002013
2014 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2015 // for unpoisoning stuff.
2016 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2017
Yury Gribov55441bb2014-11-21 10:29:50 +00002018 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2019
Yury Gribov98b18592015-05-28 07:51:49 +00002020 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002021 AI->replaceAllUsesWith(NewAddressPtr);
2022
Yury Gribov98b18592015-05-28 07:51:49 +00002023 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002024 AI->eraseFromParent();
2025}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002026
2027// isSafeAccess returns true if Addr is always inbounds with respect to its
2028// base object. For example, it is a field access or an array access with
2029// constant inbounds index.
2030bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2031 Value *Addr, uint64_t TypeSize) const {
2032 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2033 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002034 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002035 int64_t Offset = SizeOffset.second.getSExtValue();
2036 // Three checks are required to ensure safety:
2037 // . Offset >= 0 (since the offset is given from the base ptr)
2038 // . Size >= Offset (unsigned)
2039 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002040 return Offset >= 0 && Size >= uint64_t(Offset) &&
2041 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002042}