blob: e2d7a6de4e15020205a1c3349c6dbf1257a2bf8a [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"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000058#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059
60using namespace llvm;
61
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "asan"
63
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000064static const uint64_t kDefaultShadowScale = 3;
65static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000066static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000068static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000069static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000070static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000071static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000072static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000073static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
74static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000075static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000076
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000077static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000078static const size_t kMaxStackMallocSize = 1 << 16; // 64K
79static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
80static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
81
Craig Topperd3a34f82013-07-16 01:17:10 +000082static const char *const kAsanModuleCtorName = "asan.module_ctor";
83static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000084static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000085static const char *const kAsanReportErrorTemplate = "__asan_report_";
86static const char *const kAsanReportLoadN = "__asan_report_load_n";
87static const char *const kAsanReportStoreN = "__asan_report_store_n";
88static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000089static const char *const kAsanUnregisterGlobalsName =
90 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
92static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000093static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000094static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
95static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000097static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000098static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
99static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000101static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanPoisonStackMemoryName =
103 "__asan_poison_stack_memory";
104static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000105 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000106
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000107static const char *const kAsanOptionDetectUAR =
108 "__asan_option_detect_stack_use_after_return";
109
David Blaikieeacc2872013-09-18 00:11:27 +0000110#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000111static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +0000112#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000113
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;
118static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
119static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
120static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
121static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
122
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000123// Command-line flags.
124
125// This flag may need to be replaced with -f[no-]asan-reads.
126static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000127 cl::desc("instrument read instructions"),
128 cl::Hidden, cl::init(true));
129static cl::opt<bool> ClInstrumentWrites(
130 "asan-instrument-writes", cl::desc("instrument write instructions"),
131 cl::Hidden, cl::init(true));
132static cl::opt<bool> ClInstrumentAtomics(
133 "asan-instrument-atomics",
134 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
135 cl::init(true));
136static cl::opt<bool> ClAlwaysSlowPath(
137 "asan-always-slow-path",
138 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
139 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000140// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000141// in any given BB. Normally, this should be set to unlimited (INT_MAX),
142// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
143// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000144static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
145 "asan-max-ins-per-bb", cl::init(10000),
146 cl::desc("maximal number of instructions to instrument in any given BB"),
147 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000148// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000149static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
150 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000151static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000152 cl::desc("Check return-after-free"),
153 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000154// This flag may need to be replaced with -f[no]asan-globals.
155static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000156 cl::desc("Handle global objects"), cl::Hidden,
157 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000158static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000159 cl::desc("Handle C++ initializer order"),
160 cl::Hidden, cl::init(true));
161static cl::opt<bool> ClInvalidPointerPairs(
162 "asan-detect-invalid-pointer-pair",
163 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
164 cl::init(false));
165static cl::opt<unsigned> ClRealignStack(
166 "asan-realign-stack",
167 cl::desc("Realign stack to the value of this flag (power of two)"),
168 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000169static cl::opt<int> ClInstrumentationWithCallsThreshold(
170 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000171 cl::desc(
172 "If the function being instrumented contains more than "
173 "this number of memory accesses, use callbacks instead of "
174 "inline checks (-1 means never use callbacks)."),
175 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000176static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000177 "asan-memory-access-callback-prefix",
178 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
179 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000180static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000181 cl::desc("instrument dynamic allocas"),
182 cl::Hidden, cl::init(false));
183static cl::opt<bool> ClSkipPromotableAllocas(
184 "asan-skip-promotable-allocas",
185 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
186 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000187
188// These flags allow to change the shadow mapping.
189// The shadow mapping looks like
190// Shadow = (Mem >> scale) + (1 << offset_log)
191static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192 cl::desc("scale of asan shadow mapping"),
193 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000194
195// Optimization flags. Not user visible, used mostly for testing
196// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
198 cl::Hidden, cl::init(true));
199static cl::opt<bool> ClOptSameTemp(
200 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
201 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000202static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000203 cl::desc("Don't instrument scalar globals"),
204 cl::Hidden, cl::init(true));
205static cl::opt<bool> ClOptStack(
206 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
207 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000208
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000209static cl::opt<bool> ClCheckLifetime(
210 "asan-check-lifetime",
211 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
212 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000213
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000214static cl::opt<bool> ClDynamicAllocaStack(
215 "asan-stack-dynamic-alloca",
216 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000217 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000218
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000219// Debug flags.
220static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
221 cl::init(0));
222static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
223 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000224static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
225 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000226static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
227 cl::Hidden, cl::init(-1));
228static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
229 cl::Hidden, cl::init(-1));
230
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000231STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
232STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +0000233STATISTIC(NumInstrumentedDynamicAllocas,
234 "Number of instrumented dynamic allocas");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000235STATISTIC(NumOptimizedAccessesToGlobalVar,
236 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000237STATISTIC(NumOptimizedAccessesToStackVar,
238 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000239
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000240namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000241/// Frontend-provided metadata for source location.
242struct LocationMetadata {
243 StringRef Filename;
244 int LineNo;
245 int ColumnNo;
246
247 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
248
249 bool empty() const { return Filename.empty(); }
250
251 void parse(MDNode *MDN) {
252 assert(MDN->getNumOperands() == 3);
253 MDString *MDFilename = cast<MDString>(MDN->getOperand(0));
254 Filename = MDFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000255 LineNo =
256 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
257 ColumnNo =
258 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000259 }
260};
261
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000262/// Frontend-provided metadata for global variables.
263class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000264 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000265 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000266 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000267 LocationMetadata SourceLoc;
268 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000269 bool IsDynInit;
270 bool IsBlacklisted;
271 };
272
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000273 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000274
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000275 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000276 assert(!inited_);
277 inited_ = true;
278 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000279 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000280 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000281 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000282 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000283 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000284 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000285 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000286 // We can already have an entry for GV if it was merged with another
287 // global.
288 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000289 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
290 E.SourceLoc.parse(Loc);
291 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
292 E.Name = Name->getString();
293 ConstantInt *IsDynInit =
294 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000295 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000296 ConstantInt *IsBlacklisted =
297 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000298 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000299 }
300 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000301
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000302 /// Returns metadata entry for a given global.
303 Entry get(GlobalVariable *G) const {
304 auto Pos = Entries.find(G);
305 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000306 }
307
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000308 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000309 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000310 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000311};
312
Alexey Samsonov1345d352013-01-16 13:23:28 +0000313/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000314/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000315struct ShadowMapping {
316 int Scale;
317 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000318 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000319};
320
Kuba Brecka1001bb52014-12-05 22:19:18 +0000321static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000322 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000323 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000324 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
325 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000326 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
327 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000328 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000329 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
330 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000331 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
332 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000333 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000334 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000335
336 ShadowMapping Mapping;
337
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000338 if (LongSize == 32) {
339 if (IsAndroid)
340 Mapping.Offset = 0;
341 else if (IsMIPS32)
342 Mapping.Offset = kMIPS32_ShadowOffset32;
343 else if (IsFreeBSD)
344 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000345 else if (IsIOS)
346 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000347 else if (IsWindows)
348 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000349 else
350 Mapping.Offset = kDefaultShadowOffset32;
351 } else { // LongSize == 64
352 if (IsPPC64)
353 Mapping.Offset = kPPC64_ShadowOffset64;
354 else if (IsFreeBSD)
355 Mapping.Offset = kFreeBSD_ShadowOffset64;
356 else if (IsLinux && IsX86_64)
357 Mapping.Offset = kSmallX86_64ShadowOffset;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000358 else if (IsMIPS64)
359 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000360 else if (IsAArch64)
361 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000362 else
363 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000364 }
365
366 Mapping.Scale = kDefaultShadowScale;
367 if (ClMappingScale) {
368 Mapping.Scale = ClMappingScale;
369 }
370
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000371 // OR-ing shadow offset if more efficient (at least on x86) if the offset
372 // is a power of two, but on ppc64 we have to use add since the shadow
373 // offset is not necessary 1/8-th of the address space.
374 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
375
Alexey Samsonov1345d352013-01-16 13:23:28 +0000376 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000377}
378
Alexey Samsonov1345d352013-01-16 13:23:28 +0000379static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000380 // Redzone used for stack and globals is at least 32 bytes.
381 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000382 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000383}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000384
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000385/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000386struct AddressSanitizer : public FunctionPass {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000387 AddressSanitizer() : FunctionPass(ID) {
388 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
389 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000390 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000391 return "AddressSanitizerFunctionPass";
392 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000393 void getAnalysisUsage(AnalysisUsage &AU) const override {
394 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000395 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000396 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000397 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
398 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000399 uint64_t SizeInBytes =
400 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000401 return SizeInBytes;
402 }
403 /// Check if we want (and can) handle this alloca.
404 bool isInterestingAlloca(AllocaInst &AI) const;
405 /// If it is an interesting memory access, return the PointerOperand
406 /// and set IsWrite/Alignment. Otherwise return nullptr.
407 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000408 uint64_t *TypeSize,
Anna Zaks8ed1d812015-02-27 03:12:36 +0000409 unsigned *Alignment) const;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000410 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000411 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000412 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000413 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
414 Value *Addr, uint32_t TypeSize, bool IsWrite,
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000415 Value *SizeArgument, bool UseCalls);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000416 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
417 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000418 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000419 bool IsWrite, size_t AccessSizeIndex,
420 Value *SizeArgument);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000421 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000422 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000423 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000424 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000425 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000426 static char ID; // Pass identification, replacement for typeid
427
Yury Gribov3ae427d2014-12-01 08:47:58 +0000428 DominatorTree &getDominatorTree() const { return *DT; }
429
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000430 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000431 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000432
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000433 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000434 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000435 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
436 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000437
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000438 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000439 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000440 int LongSize;
441 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000442 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000443 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000444 Function *AsanCtorFunction;
445 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000446 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000447 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000448 // This array is indexed by AccessIsWrite and log2(AccessSize).
449 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000450 Function *AsanMemoryAccessCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000451 // This array is indexed by AccessIsWrite.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000452 Function *AsanErrorCallbackSized[2], *AsanMemoryAccessCallbackSized[2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000453 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000454 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000455 GlobalsMetadata GlobalsMD;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000456
457 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000458};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000459
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000460class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000461 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000462 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000463 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000464 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000465 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000466
Kostya Serebryany20a79972012-11-22 03:18:50 +0000467 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000468 void initializeCallbacks(Module &M);
469
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000470 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000471 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000472 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000473 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000474 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000475 return RedzoneSizeForScale(Mapping.Scale);
476 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000477
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000478 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000479 Type *IntptrTy;
480 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000481 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000482 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000483 Function *AsanPoisonGlobals;
484 Function *AsanUnpoisonGlobals;
485 Function *AsanRegisterGlobals;
486 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000487};
488
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000489// Stack poisoning does not play well with exception handling.
490// When an exception is thrown, we essentially bypass the code
491// that unpoisones the stack. This is why the run-time library has
492// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
493// stack in the interceptor. This however does not work inside the
494// actual function which catches the exception. Most likely because the
495// compiler hoists the load of the shadow value somewhere too high.
496// This causes asan to report a non-existing bug on 453.povray.
497// It sounds like an LLVM bug.
498struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
499 Function &F;
500 AddressSanitizer &ASan;
501 DIBuilder DIB;
502 LLVMContext *C;
503 Type *IntptrTy;
504 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000505 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000506
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000507 SmallVector<AllocaInst *, 16> AllocaVec;
508 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000509 unsigned StackAlignment;
510
Kostya Serebryany6805de52013-09-10 13:16:56 +0000511 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000512 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000513 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
514
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000515 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
516 struct AllocaPoisonCall {
517 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000518 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000519 uint64_t Size;
520 bool DoPoison;
521 };
522 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
523
Yury Gribov55441bb2014-11-21 10:29:50 +0000524 // Stores left and right redzone shadow addresses for dynamic alloca
525 // and pointer to alloca instruction itself.
526 // LeftRzAddr is a shadow address for alloca left redzone.
527 // RightRzAddr is a shadow address for alloca right redzone.
528 struct DynamicAllocaCall {
529 AllocaInst *AI;
530 Value *LeftRzAddr;
531 Value *RightRzAddr;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000532 bool Poison;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000533 explicit DynamicAllocaCall(AllocaInst *AI, Value *LeftRzAddr = nullptr,
534 Value *RightRzAddr = nullptr)
535 : AI(AI),
536 LeftRzAddr(LeftRzAddr),
537 RightRzAddr(RightRzAddr),
538 Poison(true) {}
Yury Gribov55441bb2014-11-21 10:29:50 +0000539 };
540 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
541
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000542 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000543 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000544 AllocaForValueMapTy AllocaForValue;
545
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000546 bool HasNonEmptyInlineAsm;
547 std::unique_ptr<CallInst> EmptyInlineAsm;
548
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000549 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000550 : F(F),
551 ASan(ASan),
552 DIB(*F.getParent(), /*AllowUnresolved*/ false),
553 C(ASan.C),
554 IntptrTy(ASan.IntptrTy),
555 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
556 Mapping(ASan.Mapping),
557 StackAlignment(1 << Mapping.Scale),
558 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000559 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000560
561 bool runOnFunction() {
562 if (!ClStack) return false;
563 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000564 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000565
Yury Gribov55441bb2014-11-21 10:29:50 +0000566 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000567
568 initializeCallbacks(*F.getParent());
569
570 poisonStack();
571
572 if (ClDebugStack) {
573 DEBUG(dbgs() << F);
574 }
575 return true;
576 }
577
Yury Gribov55441bb2014-11-21 10:29:50 +0000578 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000579 // poisoned red zones around all of them.
580 // Then unpoison everything back before the function returns.
581 void poisonStack();
582
583 // ----------------------- 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 Gribov55441bb2014-11-21 10:29:50 +0000587 // Unpoison dynamic allocas redzones.
588 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000589 if (!AllocaCall.Poison) return;
Yury Gribov55441bb2014-11-21 10:29:50 +0000590 for (auto Ret : RetVec) {
591 IRBuilder<> IRBRet(Ret);
592 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
593 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
594 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
595 ConstantInt::get(IntptrTy, 4));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000596 IRBRet.CreateStore(
597 Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
598 IRBRet.CreateStore(Zero,
599 IRBRet.CreateIntToPtr(PartialRzAddr, Int32PtrTy));
600 IRBRet.CreateStore(
601 Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
Yury Gribov55441bb2014-11-21 10:29:50 +0000602 }
603 }
604
605 // Right shift for BigEndian and left shift for LittleEndian.
606 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000607 auto &DL = F.getParent()->getDataLayout();
608 return DL.isLittleEndian() ? IRB.CreateShl(Val, Shift)
609 : IRB.CreateLShr(Val, Shift);
Yury Gribov55441bb2014-11-21 10:29:50 +0000610 }
611
612 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
613 // size of requested memory until runtime, we should compute it dynamically.
614 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
615 // otherwise it would contain the value that we will use to poison the
616 // partial redzone for alloca call.
617 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
618
619 // Deploy and poison redzones around dynamic alloca call. To do this, we
620 // should replace this call with another one with changed parameters and
621 // replace all its uses with new address, so
622 // addr = alloca type, old_size, align
623 // is replaced by
624 // new_size = (old_size + additional_size) * sizeof(type)
625 // tmp = alloca i8, new_size, max(align, 32)
626 // addr = tmp + 32 (first 32 bytes are for the left redzone).
627 // Additional_size is added to make new memory allocation contain not only
628 // requested memory, but also left, partial and right redzones.
629 // After that, we should poison redzones:
630 // (1) Left redzone with kAsanAllocaLeftMagic.
631 // (2) Partial redzone with the value, computed in runtime by
632 // computePartialRzMagic function.
633 // (3) Right redzone with kAsanAllocaRightMagic.
634 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
635
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000636 /// \brief Collect Alloca instructions we want (and can) handle.
637 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000638 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000639
640 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000641 if (isDynamicAlloca(AI))
642 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
643 else
644 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000645 }
646
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000647 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
648 /// errors.
649 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000650 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000651 Intrinsic::ID ID = II.getIntrinsicID();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000652 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000653 return;
654 // Found lifetime intrinsic, add ASan instrumentation if necessary.
655 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
656 // If size argument is undefined, don't do anything.
657 if (Size->isMinusOne()) return;
658 // Check that size doesn't saturate uint64_t and can
659 // be stored in IntptrTy.
660 const uint64_t SizeValue = Size->getValue().getLimitedValue();
661 if (SizeValue == ~0ULL ||
662 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
663 return;
664 // Find alloca instruction that corresponds to llvm.lifetime argument.
665 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
666 if (!AI) return;
667 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000668 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000669 AllocaPoisonCallVec.push_back(APC);
670 }
671
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000672 void visitCallInst(CallInst &CI) {
673 HasNonEmptyInlineAsm |=
674 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
675 }
676
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000677 // ---------------------- Helpers.
678 void initializeCallbacks(Module &M);
679
Yury Gribov3ae427d2014-12-01 08:47:58 +0000680 bool doesDominateAllExits(const Instruction *I) const {
681 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000682 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000683 }
684 return true;
685 }
686
Yury Gribov55441bb2014-11-21 10:29:50 +0000687 bool isDynamicAlloca(AllocaInst &AI) const {
688 return AI.isArrayAllocation() || !AI.isStaticAlloca();
689 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000690 /// Finds alloca where the value comes from.
691 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000692 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000693 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000694 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000695
696 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
697 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000698 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
699 bool Dynamic);
700 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
701 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000702};
703
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000704} // namespace
705
706char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000707INITIALIZE_PASS_BEGIN(
708 AddressSanitizer, "asan",
709 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
710 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000711INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000712INITIALIZE_PASS_END(
713 AddressSanitizer, "asan",
714 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
715 false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000716FunctionPass *llvm::createAddressSanitizerFunctionPass() {
717 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000718}
719
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000720char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000721INITIALIZE_PASS(
722 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000723 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000724 "ModulePass",
725 false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000726ModulePass *llvm::createAddressSanitizerModulePass() {
727 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000728}
729
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000730static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000731 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000732 assert(Res < kNumberOfAccessSizes);
733 return Res;
734}
735
Bill Wendling58f8cef2013-08-06 22:52:42 +0000736// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000737static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
738 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000739 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000740 // We use private linkage for module-local strings. If they can be merged
741 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000742 GlobalVariable *GV =
743 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000744 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000745 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000746 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
747 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000748}
749
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000750/// \brief Create a global describing a source location.
751static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
752 LocationMetadata MD) {
753 Constant *LocData[] = {
754 createPrivateGlobalForString(M, MD.Filename, true),
755 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
756 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
757 };
758 auto LocStruct = ConstantStruct::getAnon(LocData);
759 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
760 GlobalValue::PrivateLinkage, LocStruct,
761 kAsanGenPrefix);
762 GV->setUnnamedAddr(true);
763 return GV;
764}
765
Kostya Serebryany139a9372012-11-20 14:16:08 +0000766static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000767 return G->getName().find(kAsanGenPrefix) == 0 ||
768 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000769}
770
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000771Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
772 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000773 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000774 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000775 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000776 if (Mapping.OrShadowOffset)
777 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
778 else
779 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000780}
781
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000782// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000783void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
784 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000785 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000786 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000787 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
788 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
789 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
790 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
791 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000792 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000793 AsanMemset,
794 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
795 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
796 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000797 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000798 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000799}
800
Anna Zaks8ed1d812015-02-27 03:12:36 +0000801/// Check if we want (and can) handle this alloca.
802bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) const {
803 return (AI.getAllocatedType()->isSized() &&
804 // alloca() may be called with 0 size, ignore it.
805 getAllocaSizeInBytes(&AI) > 0 &&
806 // We are only interested in allocas not promotable to registers.
807 // Promotable allocas are common under -O0.
808 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)));
809}
810
811/// If I is an interesting memory access, return the PointerOperand
812/// and set IsWrite/Alignment. Otherwise return nullptr.
813Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
814 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000815 uint64_t *TypeSize,
Anna Zaks8ed1d812015-02-27 03:12:36 +0000816 unsigned *Alignment) const {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000817 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000818 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000819
820 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000821 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000822 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000823 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000824 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000825 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000826 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000827 PtrOperand = LI->getPointerOperand();
828 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000829 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000830 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000831 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000832 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000833 PtrOperand = SI->getPointerOperand();
834 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000835 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000836 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000838 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000839 PtrOperand = RMW->getPointerOperand();
840 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000841 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000842 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000843 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000844 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000845 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000846 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000847
848 // Treat memory accesses to promotable allocas as non-interesting since they
849 // will not cause memory violations. This greatly speeds up the instrumented
850 // executable at -O0.
851 if (ClSkipPromotableAllocas)
852 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
853 return isInterestingAlloca(*AI) ? AI : nullptr;
854
855 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000856}
857
Kostya Serebryany796f6552014-02-27 12:45:36 +0000858static bool isPointerOperand(Value *V) {
859 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
860}
861
862// This is a rough heuristic; it may cause both false positives and
863// false negatives. The proper implementation requires cooperation with
864// the frontend.
865static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
866 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000867 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000868 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000869 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000870 } else {
871 return false;
872 }
873 if (!isPointerOperand(I->getOperand(0)) ||
874 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000875 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000876 return true;
877}
878
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000879bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
880 // If a global variable does not have dynamic initialization we don't
881 // have to instrument it. However, if a global does not have initializer
882 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000883 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000884}
885
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000886void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
887 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000888 IRBuilder<> IRB(I);
889 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
890 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
891 for (int i = 0; i < 2; i++) {
892 if (Param[i]->getType()->isPointerTy())
893 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
894 }
895 IRB.CreateCall2(F, Param[0], Param[1]);
896}
897
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000898void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 Instruction *I, bool UseCalls,
900 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000901 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000902 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000903 uint64_t TypeSize = 0;
904 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000905 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000906
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000907 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000908 // If initialization order checking is disabled, a simple access to a
909 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000910 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000911 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
912 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
913 NumOptimizedAccessesToGlobalVar++;
914 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000915 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000916 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000917
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000918 if (ClOpt && ClOptStack) {
919 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000920 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000921 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
922 NumOptimizedAccessesToStackVar++;
923 return;
924 }
925 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000926
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000927 if (IsWrite)
928 NumInstrumentedWrites++;
929 else
930 NumInstrumentedReads++;
931
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000932 unsigned Granularity = 1 << Mapping.Scale;
933 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
934 // if the data is properly aligned.
935 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
936 TypeSize == 128) &&
937 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Craig Topperf40110f2014-04-25 05:29:35 +0000938 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls);
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000939 // Instrument unusual size or unusual alignment.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000940 // We can not do it with a single check, so we do 1-byte check for the first
941 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
942 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000943 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000944 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000945 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
946 if (UseCalls) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000947 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite], AddrLong, Size);
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000948 } else {
949 Value *LastByte = IRB.CreateIntToPtr(
950 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000951 Addr->getType());
Kostya Serebryanyc9a2c172014-04-22 11:19:45 +0000952 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false);
953 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false);
954 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000955}
956
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000957// Validate the result of Module::getOrInsertFunction called for an interface
958// function of AddressSanitizer. If the instrumented module defines a function
959// with the same name, their prototypes must match, otherwise
960// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000961static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000962 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
963 FuncOrBitcast->dump();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000964 report_fatal_error(
965 "trying to redefine an AddressSanitizer "
966 "interface function");
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000967}
968
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000969Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
970 Value *Addr, bool IsWrite,
971 size_t AccessSizeIndex,
972 Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000973 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000974 CallInst *Call =
975 SizeArgument
976 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
977 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000978
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000979 // We don't do Call->setDoesNotReturn() because the BB already has
980 // UnreachableInst at the end.
981 // This EmptyAsm is required to avoid callback merge.
982 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000983 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000984}
985
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000986Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000987 Value *ShadowValue,
988 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000989 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000990 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000991 Value *LastAccessedByte =
992 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000993 // (Addr & (Granularity - 1)) + size - 1
994 if (TypeSize / 8 > 1)
995 LastAccessedByte = IRB.CreateAdd(
996 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
997 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000998 LastAccessedByte =
999 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001000 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1001 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1002}
1003
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001004void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001005 Instruction *InsertBefore, Value *Addr,
1006 uint32_t TypeSize, bool IsWrite,
1007 Value *SizeArgument, bool UseCalls) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001008 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001009 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001010 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1011
1012 if (UseCalls) {
Kostya Serebryany94f57d192014-04-21 10:28:13 +00001013 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][AccessSizeIndex],
1014 AddrLong);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001015 return;
1016 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001017
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001018 Type *ShadowTy =
1019 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001020 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1021 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1022 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001023 Value *ShadowValue =
1024 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001025
1026 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001027 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001028 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001029
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001030 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001031 // We use branch weights for the slow path check, to indicate that the slow
1032 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001033 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1034 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001035 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001036 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001037 IRB.SetInsertPoint(CheckTerm);
1038 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001039 BasicBlock *CrashBlock =
1040 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001041 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001042 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1043 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001044 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001045 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001046 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001047
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001048 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1049 AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001050 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001051}
1052
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001053void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1054 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001055 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001056 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001057
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001058 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001059 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1060 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001061
1062 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001063 for (auto &BB : GlobalInit.getBasicBlockList())
1064 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001065 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001066}
1067
1068void AddressSanitizerModule::createInitializerPoisonCalls(
1069 Module &M, GlobalValue *ModuleName) {
1070 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1071
1072 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1073 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001074 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001075 ConstantStruct *CS = cast<ConstantStruct>(OP);
1076
1077 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001078 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001079 if (F->getName() == kAsanModuleCtorName) continue;
1080 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1081 // Don't instrument CTORs that will run before asan.module_ctor.
1082 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1083 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001084 }
1085 }
1086}
1087
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001088bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001089 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001090 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001091
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001092 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001093 if (!Ty->isSized()) return false;
1094 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001095 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001096 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001097 // Don't handle ODR linkage types and COMDATs since other modules may be built
1098 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001099 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1100 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1101 G->getLinkage() != GlobalVariable::InternalLinkage)
1102 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001103 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001104 // Two problems with thread-locals:
1105 // - The address of the main thread's copy can't be computed at link-time.
1106 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001107 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001108 // For now, just ignore this Global if the alignment is large.
1109 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001110
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001111 if (G->hasSection()) {
1112 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001113
Kuba Brecka1001bb52014-12-05 22:19:18 +00001114 if (TargetTriple.isOSBinFormatMachO()) {
1115 StringRef ParsedSegment, ParsedSection;
1116 unsigned TAA = 0, StubSize = 0;
1117 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001118 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1119 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001120 if (!ErrorCode.empty()) {
1121 report_fatal_error("Invalid section specifier '" + ParsedSection +
1122 "': " + ErrorCode + ".");
1123 }
1124
1125 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1126 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1127 // them.
1128 if (ParsedSegment == "__OBJC" ||
1129 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1130 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1131 return false;
1132 }
1133 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1134 // Constant CFString instances are compiled in the following way:
1135 // -- the string buffer is emitted into
1136 // __TEXT,__cstring,cstring_literals
1137 // -- the constant NSConstantString structure referencing that buffer
1138 // is placed into __DATA,__cfstring
1139 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1140 // Moreover, it causes the linker to crash on OS X 10.7
1141 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1142 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1143 return false;
1144 }
1145 // The linker merges the contents of cstring_literals and removes the
1146 // trailing zeroes.
1147 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1148 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1149 return false;
1150 }
1151 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001152
1153 // Callbacks put into the CRT initializer/terminator sections
1154 // should not be instrumented.
1155 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1156 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1157 if (Section.startswith(".CRT")) {
1158 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1159 return false;
1160 }
1161
Alexander Potapenko04969e82014-03-20 10:48:34 +00001162 // Globals from llvm.metadata aren't emitted, do not instrument them.
1163 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001164 }
1165
1166 return true;
1167}
1168
Alexey Samsonov788381b2012-12-25 12:28:20 +00001169void AddressSanitizerModule::initializeCallbacks(Module &M) {
1170 IRBuilder<> IRB(*C);
1171 // Declare our poisoning and unpoisoning functions.
1172 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001173 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001174 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1175 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001176 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001177 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1178 // Declare functions that register/unregister globals.
1179 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001180 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001181 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001182 AsanUnregisterGlobals = checkInterfaceFunction(
1183 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1184 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001185 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1186}
1187
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001188// This function replaces all global variables with new variables that have
1189// trailing redzones. It also creates a function that poisons
1190// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001191bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001192 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001193
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001194 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1195
Alexey Samsonova02e6642014-05-29 18:40:48 +00001196 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001197 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001198 }
1199
1200 size_t n = GlobalsToChange.size();
1201 if (n == 0) return false;
1202
1203 // A global is described by a structure
1204 // size_t beg;
1205 // size_t size;
1206 // size_t size_with_redzone;
1207 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001208 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001209 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001210 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001211 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001212 StructType *GlobalStructTy =
1213 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001214 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001215 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001216
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001217 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001218
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001219 // We shouldn't merge same module names, as this string serves as unique
1220 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001221 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001222 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001223
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001224 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001225 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001226 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001227 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001228
1229 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001230 // Create string holding the global name (use global name from metadata
1231 // if it's available, otherwise just write the name of global variable).
1232 GlobalVariable *Name = createPrivateGlobalForString(
1233 M, MD.Name.empty() ? G->getName() : MD.Name,
1234 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001235
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001236 PointerType *PtrTy = cast<PointerType>(G->getType());
1237 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001238 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001239 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001240 // MinRZ <= RZ <= kMaxGlobalRedzone
1241 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001242 uint64_t RZ = std::max(
1243 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001244 uint64_t RightRedzoneSize = RZ;
1245 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001246 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001247 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001248 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1249
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001250 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001251 Constant *NewInitializer =
1252 ConstantStruct::get(NewTy, G->getInitializer(),
1253 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001254
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001255 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001256 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1257 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1258 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001259 GlobalVariable *NewGlobal =
1260 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1261 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001262 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001263 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001264
1265 Value *Indices2[2];
1266 Indices2[0] = IRB.getInt32(0);
1267 Indices2[1] = IRB.getInt32(0);
1268
1269 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001270 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001271 NewGlobal->takeName(G);
1272 G->eraseFromParent();
1273
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001274 Constant *SourceLoc;
1275 if (!MD.SourceLoc.empty()) {
1276 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1277 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1278 } else {
1279 SourceLoc = ConstantInt::get(IntptrTy, 0);
1280 }
1281
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001282 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001283 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001284 ConstantInt::get(IntptrTy, SizeInBytes),
1285 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1286 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001287 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001288 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001289
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001290 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001291
Kostya Serebryany20343352012-10-17 13:40:06 +00001292 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001293 }
1294
1295 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1296 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001297 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001298 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1299
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001300 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001301 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001302 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001303 IRB.CreateCall2(AsanRegisterGlobals,
1304 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1305 ConstantInt::get(IntptrTy, n));
1306
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001307 // We also need to unregister globals at the end, e.g. when a shared library
1308 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001309 Function *AsanDtorFunction =
1310 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1311 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001312 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1313 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001314 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1315 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1316 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001317 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001318
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001319 DEBUG(dbgs() << M);
1320 return true;
1321}
1322
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001323bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001324 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001325 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001326 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001327 TargetTriple = Triple(M.getTargetTriple());
1328 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001329 initializeCallbacks(M);
1330
1331 bool Changed = false;
1332
1333 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1334 assert(CtorFunc);
1335 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1336
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001337 if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001338
1339 return Changed;
1340}
1341
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001342void AddressSanitizer::initializeCallbacks(Module &M) {
1343 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001344 // Create __asan_report* callbacks.
1345 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1346 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1347 AccessSizeIndex++) {
1348 // IsWrite and TypeSize are encoded in the function name.
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001349 std::string Suffix =
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001350 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany157a5152012-11-07 12:42:18 +00001351 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001352 checkInterfaceFunction(
1353 M.getOrInsertFunction(kAsanReportErrorTemplate + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001354 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001355 AsanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
1356 checkInterfaceFunction(
1357 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + Suffix,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001358 IRB.getVoidTy(), IntptrTy, nullptr));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001359 }
1360 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001361 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001362 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001363 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001364 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001365
Kostya Serebryany86332c02014-04-21 07:10:43 +00001366 AsanMemoryAccessCallbackSized[0] = checkInterfaceFunction(
1367 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "loadN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001368 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001369 AsanMemoryAccessCallbackSized[1] = checkInterfaceFunction(
1370 M.getOrInsertFunction(ClMemoryAccessCallbackPrefix + "storeN",
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001371 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany86332c02014-04-21 07:10:43 +00001372
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001373 AsanMemmove = checkInterfaceFunction(M.getOrInsertFunction(
1374 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001375 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001376 AsanMemcpy = checkInterfaceFunction(M.getOrInsertFunction(
1377 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001378 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001379 AsanMemset = checkInterfaceFunction(M.getOrInsertFunction(
1380 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001381 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001382
1383 AsanHandleNoReturnFunc = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001384 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001385
Kostya Serebryany796f6552014-02-27 12:45:36 +00001386 AsanPtrCmpFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001387 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany796f6552014-02-27 12:45:36 +00001388 AsanPtrSubFunction = checkInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001389 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001390 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1391 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1392 StringRef(""), StringRef(""),
1393 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001394}
1395
1396// virtual
1397bool AddressSanitizer::doInitialization(Module &M) {
1398 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001399
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001400 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001401
1402 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001403 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001404 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001405 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001406
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001407 AsanCtorFunction =
1408 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1409 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001410 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1411 // call __asan_init in the module ctor.
1412 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1413 AsanInitFunction = checkInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001414 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001415 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1416 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001417
Kuba Brecka1001bb52014-12-05 22:19:18 +00001418 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001419
Alexey Samsonov1f647502014-05-29 01:10:14 +00001420 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001421 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001422}
1423
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001424bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1425 // For each NSObject descendant having a +load method, this method is invoked
1426 // by the ObjC runtime before any of the static constructors is called.
1427 // Therefore we need to instrument such methods with a call to __asan_init
1428 // at the beginning in order to initialize our runtime before any access to
1429 // the shadow memory.
1430 // We cannot just ignore these methods, because they may call other
1431 // instrumented functions.
1432 if (F.getName().find(" load]") != std::string::npos) {
1433 IRBuilder<> IRB(F.begin()->begin());
1434 IRB.CreateCall(AsanInitFunction);
1435 return true;
1436 }
1437 return false;
1438}
1439
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001440bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001441 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001442 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001443 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001444 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001445
Yury Gribov3ae427d2014-12-01 08:47:58 +00001446 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1447
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001448 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001449 maybeInsertAsanInitAtFunctionEntry(F);
1450
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001451 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001452
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001453 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001454
1455 // We want to instrument every address only once per basic block (unless there
1456 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001457 SmallSet<Value *, 16> TempsToInstrument;
1458 SmallVector<Instruction *, 16> ToInstrument;
1459 SmallVector<Instruction *, 8> NoReturnCalls;
1460 SmallVector<BasicBlock *, 16> AllBlocks;
1461 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001462 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001463 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001464 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001465 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001466
1467 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001468 for (auto &BB : F) {
1469 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001471 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001472 for (auto &Inst : BB) {
1473 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001474 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1475 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001476 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001477 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001478 continue; // We've seen this temp in the current BB.
1479 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001480 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001481 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1482 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001483 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001484 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001485 // ok, take it.
1486 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001487 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001488 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001489 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001490 // A call inside BB.
1491 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001492 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001493 }
1494 continue;
1495 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001496 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001497 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001498 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001499 }
1500 }
1501
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001502 bool UseCalls = false;
1503 if (ClInstrumentationWithCallsThreshold >= 0 &&
1504 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1505 UseCalls = true;
1506
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001507 const TargetLibraryInfo *TLI =
1508 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001509 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001510 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1511 /*RoundToAlign=*/true);
1512
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001513 // Instrument.
1514 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001515 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001516 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1517 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001518 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001519 instrumentMop(ObjSizeVis, Inst, UseCalls,
1520 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001521 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001522 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001523 }
1524 NumInstrumented++;
1525 }
1526
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001527 FunctionStackPoisoner FSP(F, *this);
1528 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001529
1530 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1531 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001532 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001533 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001534 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001535 }
1536
Alexey Samsonova02e6642014-05-29 18:40:48 +00001537 for (auto Inst : PointerComparisonsOrSubtracts) {
1538 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001539 NumInstrumented++;
1540 }
1541
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001542 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001543
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001544 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1545
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001546 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001547}
1548
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001549// Workaround for bug 11395: we don't want to instrument stack in functions
1550// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1551// FIXME: remove once the bug 11395 is fixed.
1552bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1553 if (LongSize != 32) return false;
1554 CallInst *CI = dyn_cast<CallInst>(I);
1555 if (!CI || !CI->isInlineAsm()) return false;
1556 if (CI->getNumArgOperands() <= 5) return false;
1557 // We have inline assembly with quite a few arguments.
1558 return true;
1559}
1560
1561void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1562 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001563 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1564 std::string Suffix = itostr(i);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001565 AsanStackMallocFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1566 kAsanStackMallocNameTemplate + Suffix, IntptrTy, IntptrTy, nullptr));
1567 AsanStackFreeFunc[i] = checkInterfaceFunction(
1568 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1569 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001570 }
David Blaikiea92765c2014-11-14 00:41:42 +00001571 AsanPoisonStackMemoryFunc = checkInterfaceFunction(
1572 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1573 IntptrTy, IntptrTy, nullptr));
1574 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(
1575 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1576 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001577}
1578
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001579void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1580 IRBuilder<> &IRB, Value *ShadowBase,
1581 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001582 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001583 size_t i = 0;
1584 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1585 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1586 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1587 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1588 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1589 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1590 uint64_t Val = 0;
1591 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001592 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001593 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1594 else
1595 Val = (Val << 8) | ShadowBytes[i + j];
1596 }
1597 if (!Val) continue;
1598 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1599 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1600 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1601 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001602 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001603 }
1604}
1605
Kostya Serebryany6805de52013-09-10 13:16:56 +00001606// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1607// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1608static int StackMallocSizeClass(uint64_t LocalStackSize) {
1609 assert(LocalStackSize <= kMaxStackMallocSize);
1610 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001611 for (int i = 0;; i++, MaxSize *= 2)
1612 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001613 llvm_unreachable("impossible LocalStackSize");
1614}
1615
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001616// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1617// We can not use MemSet intrinsic because it may end up calling the actual
1618// memset. Size is a multiple of 8.
1619// Currently this generates 8-byte stores on x86_64; it may be better to
1620// generate wider stores.
1621void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1622 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1623 assert(!(Size % 8));
1624 assert(kAsanStackAfterReturnMagic == 0xf5);
1625 for (int i = 0; i < Size; i += 8) {
1626 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1627 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1628 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1629 }
1630}
1631
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001632static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001633 for (const auto &Inst : F.getEntryBlock())
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001634 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001635 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001636}
1637
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001638PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1639 Value *ValueIfTrue,
1640 Instruction *ThenTerm,
1641 Value *ValueIfFalse) {
1642 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1643 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1644 PHI->addIncoming(ValueIfFalse, CondBlock);
1645 BasicBlock *ThenBlock = ThenTerm->getParent();
1646 PHI->addIncoming(ValueIfTrue, ThenBlock);
1647 return PHI;
1648}
1649
1650Value *FunctionStackPoisoner::createAllocaForLayout(
1651 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1652 AllocaInst *Alloca;
1653 if (Dynamic) {
1654 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1655 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1656 "MyAlloca");
1657 } else {
1658 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1659 nullptr, "MyAlloca");
1660 assert(Alloca->isStaticAlloca());
1661 }
1662 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1663 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1664 Alloca->setAlignment(FrameAlignment);
1665 return IRB.CreatePointerCast(Alloca, IntptrTy);
1666}
1667
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001668void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001669 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1670
Kuba Breckaf5875d32015-02-24 09:47:05 +00001671 if (ClInstrumentAllocas) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001672 // Handle dynamic allocas.
Kuba Breckaf5875d32015-02-24 09:47:05 +00001673 for (auto &AllocaCall : DynamicAllocaVec) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001674 handleDynamicAllocaCall(AllocaCall);
Kuba Breckaf5875d32015-02-24 09:47:05 +00001675 unpoisonDynamicAlloca(AllocaCall);
1676 }
1677 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001678
1679 if (AllocaVec.size() == 0) return;
1680
Kostya Serebryany6805de52013-09-10 13:16:56 +00001681 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001682 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001683
1684 Instruction *InsBefore = AllocaVec[0];
1685 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001686 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001687
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001688 SmallVector<ASanStackVariableDescription, 16> SVD;
1689 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001690 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001691 ASanStackVariableDescription D = {AI->getName().data(),
1692 ASan.getAllocaSizeInBytes(AI),
1693 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001694 SVD.push_back(D);
1695 }
1696 // Minimal header size (left redzone) is 4 pointers,
1697 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1698 size_t MinHeaderSize = ASan.LongSize / 2;
1699 ASanStackFrameLayout L;
1700 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1701 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1702 uint64_t LocalStackSize = L.FrameSize;
1703 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001704 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001705 // Don't do dynamic alloca in presence of inline asm: too often it
1706 // makes assumptions on which registers are available.
1707 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001708
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001709 Value *StaticAlloca =
1710 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1711
1712 Value *FakeStack;
1713 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001714
1715 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001716 // void *FakeStack = __asan_option_detect_stack_use_after_return
1717 // ? __asan_stack_malloc_N(LocalStackSize)
1718 // : nullptr;
1719 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001720 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1721 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001722 Value *UARIsEnabled =
1723 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1724 Constant::getNullValue(IRB.getInt32Ty()));
1725 Instruction *Term =
1726 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001727 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001728 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001729 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1730 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1731 Value *FakeStackValue =
1732 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1733 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001734 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001735 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001736 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1737 ConstantInt::get(IntptrTy, 0));
1738
1739 Value *NoFakeStack =
1740 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1741 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1742 IRBIf.SetInsertPoint(Term);
1743 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1744 Value *AllocaValue =
1745 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1746 IRB.SetInsertPoint(InsBefore);
1747 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1748 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1749 } else {
1750 // void *FakeStack = nullptr;
1751 // void *LocalStackBase = alloca(LocalStackSize);
1752 FakeStack = ConstantInt::get(IntptrTy, 0);
1753 LocalStackBase =
1754 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001755 }
1756
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001757 // Insert poison calls for lifetime intrinsics for alloca.
1758 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001759 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001760 assert(APC.InsBefore);
1761 assert(APC.AI);
1762 IRBuilder<> IRB(APC.InsBefore);
1763 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001764 HavePoisonedAllocas |= APC.DoPoison;
1765 }
1766
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001767 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001768 for (const auto &Desc : SVD) {
1769 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001770 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001771 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001772 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001773 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001774 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001775 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001776
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001777 // The left-most redzone has enough space for at least 4 pointers.
1778 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001779 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1780 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1781 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001782 // Write the frame description constant to redzone[1].
1783 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001784 IRB.CreateAdd(LocalStackBase,
1785 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1786 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001787 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001788 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001789 /*AllowMerging*/ true);
1790 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001791 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001792 // Write the PC to redzone[2].
1793 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001794 IRB.CreateAdd(LocalStackBase,
1795 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1796 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001797 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001798
1799 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001800 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001801 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001802
Kostya Serebryany530e2072013-12-23 14:15:08 +00001803 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001804 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001806 // Mark the current frame as retired.
1807 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1808 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001809 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001810 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001811 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001812 // // In use-after-return mode, poison the whole stack frame.
1813 // if StackMallocIdx <= 4
1814 // // For small sizes inline the whole thing:
1815 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001816 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001817 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001818 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001819 // else
1820 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001821 Value *Cmp =
1822 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001823 TerminatorInst *ThenTerm, *ElseTerm;
1824 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1825
1826 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001827 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001828 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1829 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1830 ClassSize >> Mapping.Scale);
1831 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001832 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001833 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1834 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1835 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1836 IRBPoison.CreateStore(
1837 Constant::getNullValue(IRBPoison.getInt8Ty()),
1838 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1839 } else {
1840 // For larger frames call __asan_stack_free_*.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001841 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1842 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001843 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001844
1845 IRBuilder<> IRBElse(ElseTerm);
1846 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001847 } else if (HavePoisonedAllocas) {
1848 // If we poisoned some allocas in llvm.lifetime analysis,
1849 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001850 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001851 } else {
1852 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001853 }
1854 }
1855
Kostya Serebryany09959942012-10-19 06:20:53 +00001856 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001857 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001858}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001859
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001860void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001861 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001862 // For now just insert the call to ASan runtime.
1863 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1864 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001865 IRB.CreateCall2(
1866 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1867 AddrArg, SizeArg);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001868}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001869
1870// Handling llvm.lifetime intrinsics for a given %alloca:
1871// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1872// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1873// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1874// could be poisoned by previous llvm.lifetime.end instruction, as the
1875// variable may go in and out of scope several times, e.g. in loops).
1876// (3) if we poisoned at least one %alloca in a function,
1877// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001878
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001879AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1880 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1881 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001882 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001883 // See if we've already calculated (or started to calculate) alloca for a
1884 // given value.
1885 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001886 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001887 // Store 0 while we're calculating alloca for value V to avoid
1888 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001889 AllocaForValue[V] = nullptr;
1890 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001891 if (CastInst *CI = dyn_cast<CastInst>(V))
1892 Res = findAllocaForValue(CI->getOperand(0));
1893 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1894 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1895 Value *IncValue = PN->getIncomingValue(i);
1896 // Allow self-referencing phi-nodes.
1897 if (IncValue == PN) continue;
1898 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1899 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001900 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1901 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001902 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001903 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001904 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001905 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001906 return Res;
1907}
Yury Gribov55441bb2014-11-21 10:29:50 +00001908
1909// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1910// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1911// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1912// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1913// 8-byte chunk of user memory respectively.
1914// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1915// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1916
1917// Shift = Padding & ~7; // the number of bits we need to shift to access first
1918// chunk in shadow memory, containing nonzero bytes.
1919// Example:
1920// Padding = 21 Padding = 16
1921// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1922// ^ ^
1923// | |
1924// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1925//
1926// Val1 = 0xcbcbcbcb << Shift;
1927// PartialBits = Padding ? Padding & 7 : 0xcb;
1928// Val2 = PartialBits << Shift;
1929// Result = Val1 | Val2;
1930Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1931 IRBuilder<> &IRB) {
1932 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1933 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1934 unsigned Val1Int = kAsanAllocaPartialVal1;
1935 unsigned Val2Int = kAsanAllocaPartialVal2;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001936 if (!F.getParent()->getDataLayout().isLittleEndian()) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001937 Val1Int = sys::getSwappedBytes(Val1Int);
1938 Val2Int = sys::getSwappedBytes(Val2Int);
1939 }
1940 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1941 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1942 // For BigEndian get 0x000000YZ -> 0xYZ000000.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001943 if (F.getParent()->getDataLayout().isBigEndian())
Yury Gribov55441bb2014-11-21 10:29:50 +00001944 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
1945 Value *Val2 = IRB.getInt32(Val2Int);
1946 Value *Cond =
1947 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
1948 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
1949 shiftAllocaMagic(Val2, IRB, Shift));
1950 return IRB.CreateOr(Val1, Val2);
1951}
1952
1953void FunctionStackPoisoner::handleDynamicAllocaCall(
1954 DynamicAllocaCall &AllocaCall) {
1955 AllocaInst *AI = AllocaCall.AI;
Yury Gribov3ae427d2014-12-01 08:47:58 +00001956 if (!doesDominateAllExits(AI)) {
1957 // We do not yet handle complex allocas
1958 AllocaCall.Poison = false;
1959 return;
1960 }
1961
Yury Gribov55441bb2014-11-21 10:29:50 +00001962 IRBuilder<> IRB(AI);
1963
1964 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
1965 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1966 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1967
1968 Value *Zero = Constant::getNullValue(IntptrTy);
1969 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1970 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
1971 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
1972
1973 // Since we need to extend alloca with additional memory to locate
1974 // redzones, and OldSize is number of allocated blocks with
1975 // ElementSize size, get allocated memory size in bytes by
1976 // OldSize * ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001977 unsigned ElementSize =
1978 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov55441bb2014-11-21 10:29:50 +00001979 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
1980 ConstantInt::get(IntptrTy, ElementSize));
1981
1982 // PartialSize = OldSize % 32
1983 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1984
1985 // Misalign = kAllocaRzSize - PartialSize;
1986 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1987
1988 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1989 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1990 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1991
1992 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1993 // Align is added to locate left redzone, PartialPadding for possible
1994 // partial redzone and kAllocaRzSize for right redzone respectively.
1995 Value *AdditionalChunkSize = IRB.CreateAdd(
1996 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1997
1998 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1999
2000 // Insert new alloca with new NewSize and Align params.
2001 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2002 NewAlloca->setAlignment(Align);
2003
2004 // NewAddress = Address + Align
2005 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2006 ConstantInt::get(IntptrTy, Align));
2007
2008 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2009
2010 // LeftRzAddress = NewAddress - kAllocaRzSize
2011 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
2012
2013 // Poisoning left redzone.
2014 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
2015 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
2016 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
2017
2018 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
2019 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
2020 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
2021
2022 // Poisoning partial redzone.
2023 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
2024 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
2025 IRB.CreateStore(PartialRzMagic,
2026 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
2027
2028 // RightRzAddress
2029 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2030 Value *RightRzAddress = IRB.CreateAnd(
2031 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2032
2033 // Poisoning right redzone.
2034 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2035 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2036 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2037
2038 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2039 AI->replaceAllUsesWith(NewAddressPtr);
2040
2041 // We are done. Erase old alloca and store left, partial and right redzones
2042 // shadow addresses for future unpoisoning.
2043 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00002044 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00002045}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002046
2047// isSafeAccess returns true if Addr is always inbounds with respect to its
2048// base object. For example, it is a field access or an array access with
2049// constant inbounds index.
2050bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2051 Value *Addr, uint64_t TypeSize) const {
2052 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2053 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2054 int64_t Size = SizeOffset.first.getSExtValue();
2055 int64_t Offset = SizeOffset.second.getSExtValue();
2056 // Three checks are required to ensure safety:
2057 // . Offset >= 0 (since the offset is given from the base ptr)
2058 // . Size >= Offset (unsigned)
2059 // . Size - Offset >= NeededSize (unsigned)
2060 return Offset >= 0 && Size >= Offset &&
2061 uint64_t(Size - Offset) >= TypeSize / 8;
2062}