blob: 39c1e41651f2d255569639ab58405f54312f87c4 [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.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000070static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000071static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000072static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000073static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000074static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
75static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000076static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000078static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000079static const size_t kMaxStackMallocSize = 1 << 16; // 64K
80static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
81static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
82
Craig Topperd3a34f82013-07-16 01:17:10 +000083static const char *const kAsanModuleCtorName = "asan.module_ctor";
84static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000085static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000088static const char *const kAsanUnregisterGlobalsName =
89 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
91static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000092static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000093static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
94static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000096static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000097static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
98static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000100static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000101static const char *const kAsanPoisonStackMemoryName =
102 "__asan_poison_stack_memory";
103static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000104 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000105
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000106static const char *const kAsanOptionDetectUAR =
107 "__asan_option_detect_stack_use_after_return";
108
Yury Gribov98b18592015-05-28 07:51:49 +0000109static const char *const kAsanAllocaPoison =
110 "__asan_alloca_poison";
111static const char *const kAsanAllocasUnpoison =
112 "__asan_allocas_unpoison";
113
Kostya Serebryany874dae62012-07-16 16:15:40 +0000114// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
115static const size_t kNumberOfAccessSizes = 5;
116
Yury Gribov55441bb2014-11-21 10:29:50 +0000117static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000118
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000119// Command-line flags.
120
121// This flag may need to be replaced with -f[no-]asan-reads.
122static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000123 cl::desc("instrument read instructions"),
124 cl::Hidden, cl::init(true));
125static cl::opt<bool> ClInstrumentWrites(
126 "asan-instrument-writes", cl::desc("instrument write instructions"),
127 cl::Hidden, cl::init(true));
128static cl::opt<bool> ClInstrumentAtomics(
129 "asan-instrument-atomics",
130 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
131 cl::init(true));
132static cl::opt<bool> ClAlwaysSlowPath(
133 "asan-always-slow-path",
134 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
135 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000136// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000137// in any given BB. Normally, this should be set to unlimited (INT_MAX),
138// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
139// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000140static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
141 "asan-max-ins-per-bb", cl::init(10000),
142 cl::desc("maximal number of instructions to instrument in any given BB"),
143 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000144// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000145static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
146 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000147static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000148 cl::desc("Check return-after-free"),
149 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000150// This flag may need to be replaced with -f[no]asan-globals.
151static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000152 cl::desc("Handle global objects"), cl::Hidden,
153 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000154static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000155 cl::desc("Handle C++ initializer order"),
156 cl::Hidden, cl::init(true));
157static cl::opt<bool> ClInvalidPointerPairs(
158 "asan-detect-invalid-pointer-pair",
159 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
160 cl::init(false));
161static cl::opt<unsigned> ClRealignStack(
162 "asan-realign-stack",
163 cl::desc("Realign stack to the value of this flag (power of two)"),
164 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000165static cl::opt<int> ClInstrumentationWithCallsThreshold(
166 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000167 cl::desc(
168 "If the function being instrumented contains more than "
169 "this number of memory accesses, use callbacks instead of "
170 "inline checks (-1 means never use callbacks)."),
171 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000172static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000173 "asan-memory-access-callback-prefix",
174 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
175 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000176static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000177 cl::desc("instrument dynamic allocas"),
178 cl::Hidden, cl::init(false));
179static cl::opt<bool> ClSkipPromotableAllocas(
180 "asan-skip-promotable-allocas",
181 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
182 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000183
184// These flags allow to change the shadow mapping.
185// The shadow mapping looks like
186// Shadow = (Mem >> scale) + (1 << offset_log)
187static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000188 cl::desc("scale of asan shadow mapping"),
189 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000190
191// Optimization flags. Not user visible, used mostly for testing
192// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000193static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
194 cl::Hidden, cl::init(true));
195static cl::opt<bool> ClOptSameTemp(
196 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
197 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000198static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000199 cl::desc("Don't instrument scalar globals"),
200 cl::Hidden, cl::init(true));
201static cl::opt<bool> ClOptStack(
202 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
203 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000204
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000205static cl::opt<bool> ClCheckLifetime(
206 "asan-check-lifetime",
207 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
208 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000209
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000210static cl::opt<bool> ClDynamicAllocaStack(
211 "asan-stack-dynamic-alloca",
212 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000213 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000214
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000215static cl::opt<uint32_t> ClForceExperiment(
216 "asan-force-experiment",
217 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
218 cl::init(0));
219
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000220// Debug flags.
221static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
222 cl::init(0));
223static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
224 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000225static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
226 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000227static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
228 cl::Hidden, cl::init(-1));
229static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
230 cl::Hidden, cl::init(-1));
231
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000232STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
233STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000234STATISTIC(NumOptimizedAccessesToGlobalVar,
235 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000236STATISTIC(NumOptimizedAccessesToStackVar,
237 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000238
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000240/// Frontend-provided metadata for source location.
241struct LocationMetadata {
242 StringRef Filename;
243 int LineNo;
244 int ColumnNo;
245
246 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
247
248 bool empty() const { return Filename.empty(); }
249
250 void parse(MDNode *MDN) {
251 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000252 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
253 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000254 LineNo =
255 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
256 ColumnNo =
257 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000258 }
259};
260
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000261/// Frontend-provided metadata for global variables.
262class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000263 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000264 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000265 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000266 LocationMetadata SourceLoc;
267 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000268 bool IsDynInit;
269 bool IsBlacklisted;
270 };
271
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000272 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000273
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000274 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000275 assert(!inited_);
276 inited_ = true;
277 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000278 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000279 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000280 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000281 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000282 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000283 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000285 // We can already have an entry for GV if it was merged with another
286 // global.
287 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000288 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
289 E.SourceLoc.parse(Loc);
290 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
291 E.Name = Name->getString();
292 ConstantInt *IsDynInit =
293 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000294 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000295 ConstantInt *IsBlacklisted =
296 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000297 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000298 }
299 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000300
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000301 /// Returns metadata entry for a given global.
302 Entry get(GlobalVariable *G) const {
303 auto Pos = Entries.find(G);
304 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000305 }
306
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000307 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000308 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000309 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000310};
311
Alexey Samsonov1345d352013-01-16 13:23:28 +0000312/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000313/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000314struct ShadowMapping {
315 int Scale;
316 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000317 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000318};
319
Kuba Brecka1001bb52014-12-05 22:19:18 +0000320static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000321 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000322 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000323 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
324 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000325 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
326 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000327 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000328 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
329 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000330 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
331 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000332 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000333 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000334
335 ShadowMapping Mapping;
336
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000337 if (LongSize == 32) {
338 if (IsAndroid)
339 Mapping.Offset = 0;
340 else if (IsMIPS32)
341 Mapping.Offset = kMIPS32_ShadowOffset32;
342 else if (IsFreeBSD)
343 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000344 else if (IsIOS)
345 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000346 else if (IsWindows)
347 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000348 else
349 Mapping.Offset = kDefaultShadowOffset32;
350 } else { // LongSize == 64
351 if (IsPPC64)
352 Mapping.Offset = kPPC64_ShadowOffset64;
353 else if (IsFreeBSD)
354 Mapping.Offset = kFreeBSD_ShadowOffset64;
355 else if (IsLinux && IsX86_64)
356 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000357 else if (IsMIPS64)
358 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000359 else if (IsAArch64)
360 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000361 else
362 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000363 }
364
365 Mapping.Scale = kDefaultShadowScale;
366 if (ClMappingScale) {
367 Mapping.Scale = ClMappingScale;
368 }
369
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000370 // OR-ing shadow offset if more efficient (at least on x86) if the offset
371 // is a power of two, but on ppc64 we have to use add since the shadow
372 // offset is not necessary 1/8-th of the address space.
373 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
374
Alexey Samsonov1345d352013-01-16 13:23:28 +0000375 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000376}
377
Alexey Samsonov1345d352013-01-16 13:23:28 +0000378static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000379 // Redzone used for stack and globals is at least 32 bytes.
380 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000381 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000382}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000383
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000384/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000385struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000386 AddressSanitizer() : FunctionPass(ID) {
387 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
388 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000389 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000390 return "AddressSanitizerFunctionPass";
391 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000392 void getAnalysisUsage(AnalysisUsage &AU) const override {
393 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000394 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000395 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000396 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
397 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000398 uint64_t SizeInBytes =
399 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000400 return SizeInBytes;
401 }
402 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000403 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000404
405 // Check if we have dynamic alloca.
406 bool isDynamicAlloca(AllocaInst &AI) const {
407 return AI.isArrayAllocation() || !AI.isStaticAlloca();
408 }
409
Anna Zaks8ed1d812015-02-27 03:12:36 +0000410 /// If it is an interesting memory access, return the PointerOperand
411 /// and set IsWrite/Alignment. Otherwise return nullptr.
412 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000413 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000414 unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000415 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000416 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000417 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000418 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
419 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000420 Value *SizeArgument, bool UseCalls, uint32_t Exp);
421 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
422 uint32_t TypeSize, bool IsWrite,
423 Value *SizeArgument, bool UseCalls,
424 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000425 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
426 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000427 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000428 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000429 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000430 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000431 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000432 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000433 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000434 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000435 static char ID; // Pass identification, replacement for typeid
436
Yury Gribov3ae427d2014-12-01 08:47:58 +0000437 DominatorTree &getDominatorTree() const { return *DT; }
438
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000439 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000440 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000441
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000442 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000443 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000444 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
445 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000446
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000447 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000448 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000449 int LongSize;
450 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000451 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000452 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000453 Function *AsanCtorFunction;
454 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000455 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000456 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000457 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
458 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
459 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
460 // This array is indexed by AccessIsWrite and Experiment.
461 Function *AsanErrorCallbackSized[2][2];
462 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000463 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000464 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000465 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000466 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000467
468 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000469};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000470
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000471class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000472 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000473 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000474 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000475 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000476 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000477
Kostya Serebryany20a79972012-11-22 03:18:50 +0000478 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000479 void initializeCallbacks(Module &M);
480
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000481 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000482 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000483 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000484 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000485 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000486 return RedzoneSizeForScale(Mapping.Scale);
487 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000488
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000489 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000490 Type *IntptrTy;
491 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000492 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000493 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000494 Function *AsanPoisonGlobals;
495 Function *AsanUnpoisonGlobals;
496 Function *AsanRegisterGlobals;
497 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000498};
499
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000500// Stack poisoning does not play well with exception handling.
501// When an exception is thrown, we essentially bypass the code
502// that unpoisones the stack. This is why the run-time library has
503// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
504// stack in the interceptor. This however does not work inside the
505// actual function which catches the exception. Most likely because the
506// compiler hoists the load of the shadow value somewhere too high.
507// This causes asan to report a non-existing bug on 453.povray.
508// It sounds like an LLVM bug.
509struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
510 Function &F;
511 AddressSanitizer &ASan;
512 DIBuilder DIB;
513 LLVMContext *C;
514 Type *IntptrTy;
515 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000516 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000517
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000518 SmallVector<AllocaInst *, 16> AllocaVec;
519 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000520 unsigned StackAlignment;
521
Kostya Serebryany6805de52013-09-10 13:16:56 +0000522 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000523 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000524 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000525 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000527 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
528 struct AllocaPoisonCall {
529 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000530 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000531 uint64_t Size;
532 bool DoPoison;
533 };
534 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
535
Yury Gribov98b18592015-05-28 07:51:49 +0000536 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
537 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
538 AllocaInst *DynamicAllocaLayout = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000539
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000540 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000541 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000542 AllocaForValueMapTy AllocaForValue;
543
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000544 bool HasNonEmptyInlineAsm;
545 std::unique_ptr<CallInst> EmptyInlineAsm;
546
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000547 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000548 : F(F),
549 ASan(ASan),
550 DIB(*F.getParent(), /*AllowUnresolved*/ false),
551 C(ASan.C),
552 IntptrTy(ASan.IntptrTy),
553 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
554 Mapping(ASan.Mapping),
555 StackAlignment(1 << Mapping.Scale),
556 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000557 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000558
559 bool runOnFunction() {
560 if (!ClStack) return false;
561 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000562 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000563
Yury Gribov55441bb2014-11-21 10:29:50 +0000564 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000565
566 initializeCallbacks(*F.getParent());
567
568 poisonStack();
569
570 if (ClDebugStack) {
571 DEBUG(dbgs() << F);
572 }
573 return true;
574 }
575
Yury Gribov55441bb2014-11-21 10:29:50 +0000576 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000577 // poisoned red zones around all of them.
578 // Then unpoison everything back before the function returns.
579 void poisonStack();
580
Yury Gribov98b18592015-05-28 07:51:49 +0000581 void createDynamicAllocasInitStorage();
582
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000583 // ----------------------- Visitors.
584 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000585 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000586
Yury Gribov98b18592015-05-28 07:51:49 +0000587 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
588 Value *SavedStack) {
589 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000590 IRB.CreateCall(AsanAllocasUnpoisonFunc,
591 {IRB.CreateLoad(DynamicAllocaLayout),
592 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000593 }
594
Yury Gribov55441bb2014-11-21 10:29:50 +0000595 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000596 void unpoisonDynamicAllocas() {
597 for (auto &Ret : RetVec)
598 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000599
Yury Gribov98b18592015-05-28 07:51:49 +0000600 for (auto &StackRestoreInst : StackRestoreVec)
601 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
602 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000603 }
604
Yury Gribov55441bb2014-11-21 10:29:50 +0000605 // Deploy and poison redzones around dynamic alloca call. To do this, we
606 // should replace this call with another one with changed parameters and
607 // replace all its uses with new address, so
608 // addr = alloca type, old_size, align
609 // is replaced by
610 // new_size = (old_size + additional_size) * sizeof(type)
611 // tmp = alloca i8, new_size, max(align, 32)
612 // addr = tmp + 32 (first 32 bytes are for the left redzone).
613 // Additional_size is added to make new memory allocation contain not only
614 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000615 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000616
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000617 /// \brief Collect Alloca instructions we want (and can) handle.
618 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000619 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000620
621 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000622 if (ASan.isDynamicAlloca(AI))
623 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000624 else
625 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000626 }
627
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000628 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
629 /// errors.
630 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000631 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000632 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
633 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000634 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000635 return;
636 // Found lifetime intrinsic, add ASan instrumentation if necessary.
637 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
638 // If size argument is undefined, don't do anything.
639 if (Size->isMinusOne()) return;
640 // Check that size doesn't saturate uint64_t and can
641 // be stored in IntptrTy.
642 const uint64_t SizeValue = Size->getValue().getLimitedValue();
643 if (SizeValue == ~0ULL ||
644 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
645 return;
646 // Find alloca instruction that corresponds to llvm.lifetime argument.
647 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
648 if (!AI) return;
649 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000650 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000651 AllocaPoisonCallVec.push_back(APC);
652 }
653
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000654 void visitCallInst(CallInst &CI) {
655 HasNonEmptyInlineAsm |=
656 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
657 }
658
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000659 // ---------------------- Helpers.
660 void initializeCallbacks(Module &M);
661
Yury Gribov3ae427d2014-12-01 08:47:58 +0000662 bool doesDominateAllExits(const Instruction *I) const {
663 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000664 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000665 }
666 return true;
667 }
668
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000669 /// Finds alloca where the value comes from.
670 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000671 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000672 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000673 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000674
675 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
676 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000677 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
678 bool Dynamic);
679 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
680 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000681};
682
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000683} // namespace
684
685char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000686INITIALIZE_PASS_BEGIN(
687 AddressSanitizer, "asan",
688 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
689 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000690INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000691INITIALIZE_PASS_END(
692 AddressSanitizer, "asan",
693 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
694 false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000695FunctionPass *llvm::createAddressSanitizerFunctionPass() {
696 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000697}
698
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000699char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000700INITIALIZE_PASS(
701 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000702 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000703 "ModulePass",
704 false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000705ModulePass *llvm::createAddressSanitizerModulePass() {
706 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000707}
708
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000709static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000710 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000711 assert(Res < kNumberOfAccessSizes);
712 return Res;
713}
714
Bill Wendling58f8cef2013-08-06 22:52:42 +0000715// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000716static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
717 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000718 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000719 // We use private linkage for module-local strings. If they can be merged
720 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000721 GlobalVariable *GV =
722 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000723 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000724 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000725 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
726 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000727}
728
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000729/// \brief Create a global describing a source location.
730static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
731 LocationMetadata MD) {
732 Constant *LocData[] = {
733 createPrivateGlobalForString(M, MD.Filename, true),
734 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
735 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
736 };
737 auto LocStruct = ConstantStruct::getAnon(LocData);
738 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
739 GlobalValue::PrivateLinkage, LocStruct,
740 kAsanGenPrefix);
741 GV->setUnnamedAddr(true);
742 return GV;
743}
744
Kostya Serebryany139a9372012-11-20 14:16:08 +0000745static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000746 return G->getName().find(kAsanGenPrefix) == 0 ||
747 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000748}
749
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000750Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
751 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000752 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000753 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000754 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000755 if (Mapping.OrShadowOffset)
756 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
757 else
758 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759}
760
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000761// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000762void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
763 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000764 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000765 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000766 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000767 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
768 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
769 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000770 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000771 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000772 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000773 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
774 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
775 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000776 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000777 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000778}
779
Anna Zaks8ed1d812015-02-27 03:12:36 +0000780/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000781bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
782 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
783
784 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
785 return PreviouslySeenAllocaInfo->getSecond();
786
Yury Gribov98b18592015-05-28 07:51:49 +0000787 bool IsInteresting =
788 (AI.getAllocatedType()->isSized() &&
789 // alloca() may be called with 0 size, ignore it.
790 getAllocaSizeInBytes(&AI) > 0 &&
791 // We are only interested in allocas not promotable to registers.
792 // Promotable allocas are common under -O0.
793 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
794 isDynamicAlloca(AI)));
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000795
796 ProcessedAllocas[&AI] = IsInteresting;
797 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000798}
799
800/// If I is an interesting memory access, return the PointerOperand
801/// and set IsWrite/Alignment. Otherwise return nullptr.
802Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
803 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000804 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000805 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000806 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000807 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000808
809 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000810 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000811 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000812 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000813 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000814 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000815 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000816 PtrOperand = LI->getPointerOperand();
817 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000818 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000819 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000820 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000821 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000822 PtrOperand = SI->getPointerOperand();
823 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000824 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000825 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000826 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000827 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000828 PtrOperand = RMW->getPointerOperand();
829 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000830 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000831 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000832 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000833 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000834 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000835 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000836
837 // Treat memory accesses to promotable allocas as non-interesting since they
838 // will not cause memory violations. This greatly speeds up the instrumented
839 // executable at -O0.
840 if (ClSkipPromotableAllocas)
841 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
842 return isInterestingAlloca(*AI) ? AI : nullptr;
843
844 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000845}
846
Kostya Serebryany796f6552014-02-27 12:45:36 +0000847static bool isPointerOperand(Value *V) {
848 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
849}
850
851// This is a rough heuristic; it may cause both false positives and
852// false negatives. The proper implementation requires cooperation with
853// the frontend.
854static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
855 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000856 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000857 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000858 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000859 } else {
860 return false;
861 }
862 if (!isPointerOperand(I->getOperand(0)) ||
863 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000864 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000865 return true;
866}
867
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000868bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
869 // If a global variable does not have dynamic initialization we don't
870 // have to instrument it. However, if a global does not have initializer
871 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000872 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000873}
874
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000875void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
876 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000877 IRBuilder<> IRB(I);
878 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
879 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
880 for (int i = 0; i < 2; i++) {
881 if (Param[i]->getType()->isPointerTy())
882 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
883 }
David Blaikieff6409d2015-05-18 22:13:54 +0000884 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000885}
886
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000887void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000888 Instruction *I, bool UseCalls,
889 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000890 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000891 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000892 uint64_t TypeSize = 0;
893 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000894 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000895
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000896 // Optimization experiments.
897 // The experiments can be used to evaluate potential optimizations that remove
898 // instrumentation (assess false negatives). Instead of completely removing
899 // some instrumentation, you set Exp to a non-zero value (mask of optimization
900 // experiments that want to remove instrumentation of this instruction).
901 // If Exp is non-zero, this pass will emit special calls into runtime
902 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
903 // make runtime terminate the program in a special way (with a different
904 // exit status). Then you run the new compiler on a buggy corpus, collect
905 // the special terminations (ideally, you don't see them at all -- no false
906 // negatives) and make the decision on the optimization.
907 uint32_t Exp = ClForceExperiment;
908
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000909 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000910 // If initialization order checking is disabled, a simple access to a
911 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000912 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000913 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
914 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
915 NumOptimizedAccessesToGlobalVar++;
916 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000917 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000918 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000919
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000920 if (ClOpt && ClOptStack) {
921 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000922 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000923 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
924 NumOptimizedAccessesToStackVar++;
925 return;
926 }
927 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000928
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000929 if (IsWrite)
930 NumInstrumentedWrites++;
931 else
932 NumInstrumentedReads++;
933
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000934 unsigned Granularity = 1 << Mapping.Scale;
935 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
936 // if the data is properly aligned.
937 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
938 TypeSize == 128) &&
939 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000940 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
941 Exp);
942 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
943 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000944}
945
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000946Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
947 Value *Addr, bool IsWrite,
948 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000949 Value *SizeArgument,
950 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000951 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000952 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
953 CallInst *Call = nullptr;
954 if (SizeArgument) {
955 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +0000956 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
957 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000958 else
David Blaikieff6409d2015-05-18 22:13:54 +0000959 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
960 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000961 } else {
962 if (Exp == 0)
963 Call =
964 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
965 else
David Blaikieff6409d2015-05-18 22:13:54 +0000966 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
967 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000968 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000969
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000970 // We don't do Call->setDoesNotReturn() because the BB already has
971 // UnreachableInst at the end.
972 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +0000973 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000974 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000975}
976
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000977Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000978 Value *ShadowValue,
979 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000980 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000981 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000982 Value *LastAccessedByte =
983 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000984 // (Addr & (Granularity - 1)) + size - 1
985 if (TypeSize / 8 > 1)
986 LastAccessedByte = IRB.CreateAdd(
987 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
988 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000989 LastAccessedByte =
990 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000991 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
992 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
993}
994
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000995void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000996 Instruction *InsertBefore, Value *Addr,
997 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000998 Value *SizeArgument, bool UseCalls,
999 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001000 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001001 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001002 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1003
1004 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001005 if (Exp == 0)
1006 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1007 AddrLong);
1008 else
David Blaikieff6409d2015-05-18 22:13:54 +00001009 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1010 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001011 return;
1012 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001013
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001014 Type *ShadowTy =
1015 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001016 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1017 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1018 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001019 Value *ShadowValue =
1020 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001021
1022 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001023 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001024 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001025
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001026 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001027 // We use branch weights for the slow path check, to indicate that the slow
1028 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001029 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1030 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001031 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001032 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001033 IRB.SetInsertPoint(CheckTerm);
1034 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001035 BasicBlock *CrashBlock =
1036 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001037 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001038 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1039 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001040 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001041 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001042 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001043
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001044 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001045 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001046 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001047}
1048
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001049// Instrument unusual size or unusual alignment.
1050// We can not do it with a single check, so we do 1-byte check for the first
1051// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1052// to report the actual access size.
1053void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1054 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1055 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1056 IRBuilder<> IRB(I);
1057 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1058 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1059 if (UseCalls) {
1060 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001061 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1062 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001063 else
David Blaikieff6409d2015-05-18 22:13:54 +00001064 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1065 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001066 } else {
1067 Value *LastByte = IRB.CreateIntToPtr(
1068 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1069 Addr->getType());
1070 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1071 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1072 }
1073}
1074
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001075void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1076 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001077 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001078 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001079
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001080 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001081 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1082 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001083
1084 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001085 for (auto &BB : GlobalInit.getBasicBlockList())
1086 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001087 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001088}
1089
1090void AddressSanitizerModule::createInitializerPoisonCalls(
1091 Module &M, GlobalValue *ModuleName) {
1092 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1093
1094 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1095 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001096 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001097 ConstantStruct *CS = cast<ConstantStruct>(OP);
1098
1099 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001100 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001101 if (F->getName() == kAsanModuleCtorName) continue;
1102 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1103 // Don't instrument CTORs that will run before asan.module_ctor.
1104 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1105 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001106 }
1107 }
1108}
1109
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001110bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001111 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001112 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001113
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001114 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001115 if (!Ty->isSized()) return false;
1116 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001117 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001118 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001119 // Don't handle ODR linkage types and COMDATs since other modules may be built
1120 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001121 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1122 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1123 G->getLinkage() != GlobalVariable::InternalLinkage)
1124 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001125 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001126 // Two problems with thread-locals:
1127 // - The address of the main thread's copy can't be computed at link-time.
1128 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001129 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001130 // For now, just ignore this Global if the alignment is large.
1131 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001132
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001133 if (G->hasSection()) {
1134 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001135
Kuba Brecka1001bb52014-12-05 22:19:18 +00001136 if (TargetTriple.isOSBinFormatMachO()) {
1137 StringRef ParsedSegment, ParsedSection;
1138 unsigned TAA = 0, StubSize = 0;
1139 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001140 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1141 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001142 if (!ErrorCode.empty()) {
1143 report_fatal_error("Invalid section specifier '" + ParsedSection +
1144 "': " + ErrorCode + ".");
1145 }
1146
1147 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1148 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1149 // them.
1150 if (ParsedSegment == "__OBJC" ||
1151 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1152 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1153 return false;
1154 }
1155 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1156 // Constant CFString instances are compiled in the following way:
1157 // -- the string buffer is emitted into
1158 // __TEXT,__cstring,cstring_literals
1159 // -- the constant NSConstantString structure referencing that buffer
1160 // is placed into __DATA,__cfstring
1161 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1162 // Moreover, it causes the linker to crash on OS X 10.7
1163 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1164 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1165 return false;
1166 }
1167 // The linker merges the contents of cstring_literals and removes the
1168 // trailing zeroes.
1169 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1170 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1171 return false;
1172 }
1173 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001174
1175 // Callbacks put into the CRT initializer/terminator sections
1176 // should not be instrumented.
1177 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1178 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1179 if (Section.startswith(".CRT")) {
1180 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1181 return false;
1182 }
1183
Alexander Potapenko04969e82014-03-20 10:48:34 +00001184 // Globals from llvm.metadata aren't emitted, do not instrument them.
1185 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001186 }
1187
1188 return true;
1189}
1190
Alexey Samsonov788381b2012-12-25 12:28:20 +00001191void AddressSanitizerModule::initializeCallbacks(Module &M) {
1192 IRBuilder<> IRB(*C);
1193 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001194 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001195 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001196 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001197 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001198 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001199 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1200 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001201 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001202 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001203 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001204 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001205 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1206 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001207 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1208}
1209
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001210// This function replaces all global variables with new variables that have
1211// trailing redzones. It also creates a function that poisons
1212// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001213bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001214 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001215
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001216 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1217
Alexey Samsonova02e6642014-05-29 18:40:48 +00001218 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001219 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220 }
1221
1222 size_t n = GlobalsToChange.size();
1223 if (n == 0) return false;
1224
1225 // A global is described by a structure
1226 // size_t beg;
1227 // size_t size;
1228 // size_t size_with_redzone;
1229 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001230 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001231 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001232 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001233 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001234 StructType *GlobalStructTy =
1235 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001236 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001237 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001238
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001239 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001240
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001241 // We shouldn't merge same module names, as this string serves as unique
1242 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001243 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001244 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001245
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001247 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001248 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001249 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001250
1251 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001252 // Create string holding the global name (use global name from metadata
1253 // if it's available, otherwise just write the name of global variable).
1254 GlobalVariable *Name = createPrivateGlobalForString(
1255 M, MD.Name.empty() ? G->getName() : MD.Name,
1256 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001257
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001258 PointerType *PtrTy = cast<PointerType>(G->getType());
1259 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001260 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001261 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001262 // MinRZ <= RZ <= kMaxGlobalRedzone
1263 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001264 uint64_t RZ = std::max(
1265 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001266 uint64_t RightRedzoneSize = RZ;
1267 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001268 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001269 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001270 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1271
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001272 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001273 Constant *NewInitializer =
1274 ConstantStruct::get(NewTy, G->getInitializer(),
1275 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001276
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001277 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001278 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1279 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1280 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001281 GlobalVariable *NewGlobal =
1282 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1283 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001284 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001285 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001286
1287 Value *Indices2[2];
1288 Indices2[0] = IRB.getInt32(0);
1289 Indices2[1] = IRB.getInt32(0);
1290
1291 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001292 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001293 NewGlobal->takeName(G);
1294 G->eraseFromParent();
1295
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001296 Constant *SourceLoc;
1297 if (!MD.SourceLoc.empty()) {
1298 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1299 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1300 } else {
1301 SourceLoc = ConstantInt::get(IntptrTy, 0);
1302 }
1303
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001304 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001305 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001306 ConstantInt::get(IntptrTy, SizeInBytes),
1307 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1308 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001309 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001310 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001311
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001312 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001313
Kostya Serebryany20343352012-10-17 13:40:06 +00001314 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001315 }
1316
1317 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1318 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001319 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001320 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1321
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001322 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001323 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001324 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001325 IRB.CreateCall(AsanRegisterGlobals,
1326 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1327 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001328
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001329 // We also need to unregister globals at the end, e.g. when a shared library
1330 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001331 Function *AsanDtorFunction =
1332 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1333 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001334 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1335 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001336 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1337 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1338 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001339 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001340
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001341 DEBUG(dbgs() << M);
1342 return true;
1343}
1344
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001345bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001346 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001347 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001348 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001349 TargetTriple = Triple(M.getTargetTriple());
1350 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001351 initializeCallbacks(M);
1352
1353 bool Changed = false;
1354
1355 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1356 assert(CtorFunc);
1357 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1358
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001359 if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001360
1361 return Changed;
1362}
1363
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001364void AddressSanitizer::initializeCallbacks(Module &M) {
1365 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001366 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001367 // IsWrite, TypeSize and Exp are encoded in the function name.
1368 for (int Exp = 0; Exp < 2; Exp++) {
1369 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1370 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1371 const std::string ExpStr = Exp ? "exp_" : "";
1372 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1373 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001374 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001375 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n",
1376 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1377 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001378 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001379 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N",
1380 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1381 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1382 AccessSizeIndex++) {
1383 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1384 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001385 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001386 kAsanReportErrorTemplate + ExpStr + Suffix, IRB.getVoidTy(),
1387 IntptrTy, ExpType, nullptr));
1388 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001389 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001390 ClMemoryAccessCallbackPrefix + ExpStr + Suffix, IRB.getVoidTy(),
1391 IntptrTy, ExpType, nullptr));
1392 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001393 }
1394 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001395
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001396 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001397 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001398 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001399 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001400 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001401 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001402 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001403 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001404 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001405
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001406 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001407 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001408
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001409 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001410 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001411 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001412 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001413 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1414 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1415 StringRef(""), StringRef(""),
1416 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001417}
1418
1419// virtual
1420bool AddressSanitizer::doInitialization(Module &M) {
1421 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001422
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001423 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001424
1425 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001426 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001427 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001428 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001429
Ismail Pazarbasi09c37092015-05-07 21:40:46 +00001430 std::tie(AsanCtorFunction, AsanInitFunction) =
1431 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1432 /*InitArgTypes=*/{},
1433 /*InitArgs=*/{});
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001434
Kuba Brecka1001bb52014-12-05 22:19:18 +00001435 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001436
Alexey Samsonov1f647502014-05-29 01:10:14 +00001437 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001438 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001439}
1440
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001441bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1442 // For each NSObject descendant having a +load method, this method is invoked
1443 // by the ObjC runtime before any of the static constructors is called.
1444 // Therefore we need to instrument such methods with a call to __asan_init
1445 // at the beginning in order to initialize our runtime before any access to
1446 // the shadow memory.
1447 // We cannot just ignore these methods, because they may call other
1448 // instrumented functions.
1449 if (F.getName().find(" load]") != std::string::npos) {
1450 IRBuilder<> IRB(F.begin()->begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001451 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001452 return true;
1453 }
1454 return false;
1455}
1456
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001457bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001458 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001459 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001460 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001461 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001462
Yury Gribov3ae427d2014-12-01 08:47:58 +00001463 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1464
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001465 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001466 maybeInsertAsanInitAtFunctionEntry(F);
1467
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001468 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001470 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001471
1472 // We want to instrument every address only once per basic block (unless there
1473 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001474 SmallSet<Value *, 16> TempsToInstrument;
1475 SmallVector<Instruction *, 16> ToInstrument;
1476 SmallVector<Instruction *, 8> NoReturnCalls;
1477 SmallVector<BasicBlock *, 16> AllBlocks;
1478 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001479 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001480 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001481 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001482 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001483
1484 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001485 for (auto &BB : F) {
1486 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001487 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001488 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001489 for (auto &Inst : BB) {
1490 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001491 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1492 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001493 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001494 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001495 continue; // We've seen this temp in the current BB.
1496 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001497 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001498 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1499 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001500 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001501 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001502 // ok, take it.
1503 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001504 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001505 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001506 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001507 // A call inside BB.
1508 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001509 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001510 }
1511 continue;
1512 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001513 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001514 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001515 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001516 }
1517 }
1518
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001519 bool UseCalls = false;
1520 if (ClInstrumentationWithCallsThreshold >= 0 &&
1521 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1522 UseCalls = true;
1523
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001524 const TargetLibraryInfo *TLI =
1525 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001526 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001527 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1528 /*RoundToAlign=*/true);
1529
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001530 // Instrument.
1531 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001532 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001533 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1534 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001535 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001536 instrumentMop(ObjSizeVis, Inst, UseCalls,
1537 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001538 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001539 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001540 }
1541 NumInstrumented++;
1542 }
1543
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001544 FunctionStackPoisoner FSP(F, *this);
1545 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001546
1547 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1548 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001549 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001550 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001551 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001552 }
1553
Alexey Samsonova02e6642014-05-29 18:40:48 +00001554 for (auto Inst : PointerComparisonsOrSubtracts) {
1555 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001556 NumInstrumented++;
1557 }
1558
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001559 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001560
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001561 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1562
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001563 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001564}
1565
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001566// Workaround for bug 11395: we don't want to instrument stack in functions
1567// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1568// FIXME: remove once the bug 11395 is fixed.
1569bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1570 if (LongSize != 32) return false;
1571 CallInst *CI = dyn_cast<CallInst>(I);
1572 if (!CI || !CI->isInlineAsm()) return false;
1573 if (CI->getNumArgOperands() <= 5) return false;
1574 // We have inline assembly with quite a few arguments.
1575 return true;
1576}
1577
1578void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1579 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001580 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1581 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001582 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1583 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1584 IntptrTy, nullptr));
1585 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001586 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1587 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001588 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001589 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001590 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1591 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001592 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001593 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1594 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001595 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1596 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1597 AsanAllocasUnpoisonFunc =
1598 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1599 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001600}
1601
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001602void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1603 IRBuilder<> &IRB, Value *ShadowBase,
1604 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001605 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001606 size_t i = 0;
1607 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1608 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1609 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1610 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1611 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1612 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1613 uint64_t Val = 0;
1614 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001615 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001616 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1617 else
1618 Val = (Val << 8) | ShadowBytes[i + j];
1619 }
1620 if (!Val) continue;
1621 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1622 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1623 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1624 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001625 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001626 }
1627}
1628
Kostya Serebryany6805de52013-09-10 13:16:56 +00001629// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1630// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1631static int StackMallocSizeClass(uint64_t LocalStackSize) {
1632 assert(LocalStackSize <= kMaxStackMallocSize);
1633 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001634 for (int i = 0;; i++, MaxSize *= 2)
1635 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001636 llvm_unreachable("impossible LocalStackSize");
1637}
1638
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001639// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1640// We can not use MemSet intrinsic because it may end up calling the actual
1641// memset. Size is a multiple of 8.
1642// Currently this generates 8-byte stores on x86_64; it may be better to
1643// generate wider stores.
1644void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1645 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1646 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001647
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001648 // kAsanStackAfterReturnMagic is 0xf5.
1649 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001650
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001651 for (int i = 0; i < Size; i += 8) {
1652 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001653 IRB.CreateStore(
1654 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1655 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001656 }
1657}
1658
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001659static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001660 for (const auto &Inst : F.getEntryBlock())
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001661 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001662 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001663}
1664
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001665PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1666 Value *ValueIfTrue,
1667 Instruction *ThenTerm,
1668 Value *ValueIfFalse) {
1669 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1670 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1671 PHI->addIncoming(ValueIfFalse, CondBlock);
1672 BasicBlock *ThenBlock = ThenTerm->getParent();
1673 PHI->addIncoming(ValueIfTrue, ThenBlock);
1674 return PHI;
1675}
1676
1677Value *FunctionStackPoisoner::createAllocaForLayout(
1678 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1679 AllocaInst *Alloca;
1680 if (Dynamic) {
1681 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1682 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1683 "MyAlloca");
1684 } else {
1685 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1686 nullptr, "MyAlloca");
1687 assert(Alloca->isStaticAlloca());
1688 }
1689 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1690 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1691 Alloca->setAlignment(FrameAlignment);
1692 return IRB.CreatePointerCast(Alloca, IntptrTy);
1693}
1694
Yury Gribov98b18592015-05-28 07:51:49 +00001695void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1696 BasicBlock &FirstBB = *F.begin();
1697 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1698 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1699 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1700 DynamicAllocaLayout->setAlignment(32);
1701}
1702
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001703void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001704 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1705
Yury Gribov98b18592015-05-28 07:51:49 +00001706 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001707 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001708 createDynamicAllocasInitStorage();
1709 for (auto &AI : DynamicAllocaVec)
1710 handleDynamicAllocaCall(AI);
1711
1712 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001713 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001714
1715 if (AllocaVec.size() == 0) return;
1716
Kostya Serebryany6805de52013-09-10 13:16:56 +00001717 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001718 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001719
1720 Instruction *InsBefore = AllocaVec[0];
1721 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001722 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001723
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001724 SmallVector<ASanStackVariableDescription, 16> SVD;
1725 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001726 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001727 ASanStackVariableDescription D = {AI->getName().data(),
1728 ASan.getAllocaSizeInBytes(AI),
1729 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001730 SVD.push_back(D);
1731 }
1732 // Minimal header size (left redzone) is 4 pointers,
1733 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1734 size_t MinHeaderSize = ASan.LongSize / 2;
1735 ASanStackFrameLayout L;
1736 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1737 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1738 uint64_t LocalStackSize = L.FrameSize;
1739 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001740 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001741 // Don't do dynamic alloca in presence of inline asm: too often it makes
1742 // assumptions on which registers are available. Don't do stack malloc in the
1743 // presence of inline asm on 32-bit platforms for the same reason.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001744 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001745 DoStackMalloc &= !HasNonEmptyInlineAsm || ASan.LongSize != 32;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001746
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001747 Value *StaticAlloca =
1748 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1749
1750 Value *FakeStack;
1751 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001752
1753 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001754 // void *FakeStack = __asan_option_detect_stack_use_after_return
1755 // ? __asan_stack_malloc_N(LocalStackSize)
1756 // : nullptr;
1757 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001758 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1759 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001760 Value *UARIsEnabled =
1761 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1762 Constant::getNullValue(IRB.getInt32Ty()));
1763 Instruction *Term =
1764 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001765 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001766 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001767 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1768 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1769 Value *FakeStackValue =
1770 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1771 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001772 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001773 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001774 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1775 ConstantInt::get(IntptrTy, 0));
1776
1777 Value *NoFakeStack =
1778 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1779 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1780 IRBIf.SetInsertPoint(Term);
1781 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1782 Value *AllocaValue =
1783 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1784 IRB.SetInsertPoint(InsBefore);
1785 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1786 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1787 } else {
1788 // void *FakeStack = nullptr;
1789 // void *LocalStackBase = alloca(LocalStackSize);
1790 FakeStack = ConstantInt::get(IntptrTy, 0);
1791 LocalStackBase =
1792 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001793 }
1794
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001795 // Insert poison calls for lifetime intrinsics for alloca.
1796 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001797 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001798 assert(APC.InsBefore);
1799 assert(APC.AI);
1800 IRBuilder<> IRB(APC.InsBefore);
1801 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001802 HavePoisonedAllocas |= APC.DoPoison;
1803 }
1804
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001806 for (const auto &Desc : SVD) {
1807 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001808 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001809 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001810 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001811 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001812 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001813 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001814
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001815 // The left-most redzone has enough space for at least 4 pointers.
1816 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001817 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1818 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1819 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001820 // Write the frame description constant to redzone[1].
1821 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001822 IRB.CreateAdd(LocalStackBase,
1823 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1824 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001825 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001826 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001827 /*AllowMerging*/ true);
1828 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001829 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001830 // Write the PC to redzone[2].
1831 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001832 IRB.CreateAdd(LocalStackBase,
1833 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1834 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001835 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001836
1837 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001838 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001839 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001840
Kostya Serebryany530e2072013-12-23 14:15:08 +00001841 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001842 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001843 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001844 // Mark the current frame as retired.
1845 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1846 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001847 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001848 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001849 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001850 // // In use-after-return mode, poison the whole stack frame.
1851 // if StackMallocIdx <= 4
1852 // // For small sizes inline the whole thing:
1853 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001854 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001855 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001856 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001857 // else
1858 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001859 Value *Cmp =
1860 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001861 TerminatorInst *ThenTerm, *ElseTerm;
1862 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1863
1864 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001865 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001866 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1867 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1868 ClassSize >> Mapping.Scale);
1869 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001870 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001871 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1872 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1873 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1874 IRBPoison.CreateStore(
1875 Constant::getNullValue(IRBPoison.getInt8Ty()),
1876 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1877 } else {
1878 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001879 IRBPoison.CreateCall(
1880 AsanStackFreeFunc[StackMallocIdx],
1881 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001882 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001883
1884 IRBuilder<> IRBElse(ElseTerm);
1885 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001886 } else if (HavePoisonedAllocas) {
1887 // If we poisoned some allocas in llvm.lifetime analysis,
1888 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001889 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001890 } else {
1891 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001892 }
1893 }
1894
Kostya Serebryany09959942012-10-19 06:20:53 +00001895 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001896 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001897}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001898
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001899void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001900 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001901 // For now just insert the call to ASan runtime.
1902 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1903 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
David Blaikieff6409d2015-05-18 22:13:54 +00001904 IRB.CreateCall(DoPoison ? AsanPoisonStackMemoryFunc
1905 : AsanUnpoisonStackMemoryFunc,
1906 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00001907}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001908
1909// Handling llvm.lifetime intrinsics for a given %alloca:
1910// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1911// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1912// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1913// could be poisoned by previous llvm.lifetime.end instruction, as the
1914// variable may go in and out of scope several times, e.g. in loops).
1915// (3) if we poisoned at least one %alloca in a function,
1916// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001917
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001918AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1919 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1920 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001921 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001922 // See if we've already calculated (or started to calculate) alloca for a
1923 // given value.
1924 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001925 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001926 // Store 0 while we're calculating alloca for value V to avoid
1927 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001928 AllocaForValue[V] = nullptr;
1929 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001930 if (CastInst *CI = dyn_cast<CastInst>(V))
1931 Res = findAllocaForValue(CI->getOperand(0));
1932 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00001933 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001934 // Allow self-referencing phi-nodes.
1935 if (IncValue == PN) continue;
1936 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1937 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001938 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1939 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001940 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001941 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001942 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001943 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001944 return Res;
1945}
Yury Gribov55441bb2014-11-21 10:29:50 +00001946
Yury Gribov98b18592015-05-28 07:51:49 +00001947void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001948 IRBuilder<> IRB(AI);
1949
Yury Gribov55441bb2014-11-21 10:29:50 +00001950 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1951 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1952
1953 Value *Zero = Constant::getNullValue(IntptrTy);
1954 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1955 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00001956
1957 // Since we need to extend alloca with additional memory to locate
1958 // redzones, and OldSize is number of allocated blocks with
1959 // ElementSize size, get allocated memory size in bytes by
1960 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00001961 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001962 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00001963 Value *OldSize =
1964 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1965 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00001966
1967 // PartialSize = OldSize % 32
1968 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1969
1970 // Misalign = kAllocaRzSize - PartialSize;
1971 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1972
1973 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1974 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1975 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1976
1977 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1978 // Align is added to locate left redzone, PartialPadding for possible
1979 // partial redzone and kAllocaRzSize for right redzone respectively.
1980 Value *AdditionalChunkSize = IRB.CreateAdd(
1981 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1982
1983 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1984
1985 // Insert new alloca with new NewSize and Align params.
1986 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1987 NewAlloca->setAlignment(Align);
1988
1989 // NewAddress = Address + Align
1990 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
1991 ConstantInt::get(IntptrTy, Align));
1992
Yury Gribov98b18592015-05-28 07:51:49 +00001993 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00001994 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00001995
1996 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
1997 // for unpoisoning stuff.
1998 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
1999
Yury Gribov55441bb2014-11-21 10:29:50 +00002000 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2001
Yury Gribov98b18592015-05-28 07:51:49 +00002002 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002003 AI->replaceAllUsesWith(NewAddressPtr);
2004
Yury Gribov98b18592015-05-28 07:51:49 +00002005 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002006 AI->eraseFromParent();
2007}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002008
2009// isSafeAccess returns true if Addr is always inbounds with respect to its
2010// base object. For example, it is a field access or an array access with
2011// constant inbounds index.
2012bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2013 Value *Addr, uint64_t TypeSize) const {
2014 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2015 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002016 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002017 int64_t Offset = SizeOffset.second.getSExtValue();
2018 // Three checks are required to ensure safety:
2019 // . Offset >= 0 (since the offset is given from the base ptr)
2020 // . Size >= Offset (unsigned)
2021 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002022 return Offset >= 0 && Size >= uint64_t(Offset) &&
2023 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002024}