blob: 8d6d3ce3e61e8110ad864380f6ceb80c8c9c14d3 [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000027#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000037#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000043#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/DataTypes.h"
46#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000047#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000048#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000050#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000051#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000053#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000054#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000055#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000056#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000059#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060
61using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "asan"
64
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065static const uint64_t kDefaultShadowScale = 3;
66static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000069static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000070static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000071static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000072static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000073static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000074static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
75static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000076static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000077
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000078static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000079static const size_t kMaxStackMallocSize = 1 << 16; // 64K
80static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
81static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
82
Craig Topperd3a34f82013-07-16 01:17:10 +000083static const char *const kAsanModuleCtorName = "asan.module_ctor";
84static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000085static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000088static const char *const kAsanUnregisterGlobalsName =
89 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
91static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000092static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000093static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
94static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000096static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000097static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
98static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000099static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000100static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000101static const char *const kAsanPoisonStackMemoryName =
102 "__asan_poison_stack_memory";
103static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000104 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000105
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000106static const char *const kAsanOptionDetectUAR =
107 "__asan_option_detect_stack_use_after_return";
108
Kostya Serebryany874dae62012-07-16 16:15:40 +0000109// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
110static const size_t kNumberOfAccessSizes = 5;
111
Yury Gribov55441bb2014-11-21 10:29:50 +0000112static const unsigned kAllocaRzSize = 32;
113static const unsigned kAsanAllocaLeftMagic = 0xcacacacaU;
114static const unsigned kAsanAllocaRightMagic = 0xcbcbcbcbU;
115static const unsigned kAsanAllocaPartialVal1 = 0xcbcbcb00U;
116static const unsigned kAsanAllocaPartialVal2 = 0x000000cbU;
117
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000118// Command-line flags.
119
120// This flag may need to be replaced with -f[no-]asan-reads.
121static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000122 cl::desc("instrument read instructions"),
123 cl::Hidden, cl::init(true));
124static cl::opt<bool> ClInstrumentWrites(
125 "asan-instrument-writes", cl::desc("instrument write instructions"),
126 cl::Hidden, cl::init(true));
127static cl::opt<bool> ClInstrumentAtomics(
128 "asan-instrument-atomics",
129 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
130 cl::init(true));
131static cl::opt<bool> ClAlwaysSlowPath(
132 "asan-always-slow-path",
133 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
134 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000135// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000136// in any given BB. Normally, this should be set to unlimited (INT_MAX),
137// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
138// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000139static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
140 "asan-max-ins-per-bb", cl::init(10000),
141 cl::desc("maximal number of instructions to instrument in any given BB"),
142 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000143// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000144static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
145 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000146static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000147 cl::desc("Check return-after-free"),
148 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000149// This flag may need to be replaced with -f[no]asan-globals.
150static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000151 cl::desc("Handle global objects"), cl::Hidden,
152 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000153static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000154 cl::desc("Handle C++ initializer order"),
155 cl::Hidden, cl::init(true));
156static cl::opt<bool> ClInvalidPointerPairs(
157 "asan-detect-invalid-pointer-pair",
158 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
159 cl::init(false));
160static cl::opt<unsigned> ClRealignStack(
161 "asan-realign-stack",
162 cl::desc("Realign stack to the value of this flag (power of two)"),
163 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000164static cl::opt<int> ClInstrumentationWithCallsThreshold(
165 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000166 cl::desc(
167 "If the function being instrumented contains more than "
168 "this number of memory accesses, use callbacks instead of "
169 "inline checks (-1 means never use callbacks)."),
170 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000171static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172 "asan-memory-access-callback-prefix",
173 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
174 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000175static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000176 cl::desc("instrument dynamic allocas"),
177 cl::Hidden, cl::init(false));
178static cl::opt<bool> ClSkipPromotableAllocas(
179 "asan-skip-promotable-allocas",
180 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
181 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000182
183// These flags allow to change the shadow mapping.
184// The shadow mapping looks like
185// Shadow = (Mem >> scale) + (1 << offset_log)
186static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000187 cl::desc("scale of asan shadow mapping"),
188 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000189
190// Optimization flags. Not user visible, used mostly for testing
191// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
193 cl::Hidden, cl::init(true));
194static cl::opt<bool> ClOptSameTemp(
195 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
196 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000197static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000198 cl::desc("Don't instrument scalar globals"),
199 cl::Hidden, cl::init(true));
200static cl::opt<bool> ClOptStack(
201 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
202 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000203
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000204static cl::opt<bool> ClCheckLifetime(
205 "asan-check-lifetime",
206 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
207 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000208
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000209static cl::opt<bool> ClDynamicAllocaStack(
210 "asan-stack-dynamic-alloca",
211 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000212 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000213
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000214static cl::opt<uint32_t> ClForceExperiment(
215 "asan-force-experiment",
216 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
217 cl::init(0));
218
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.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000404 bool isInterestingAlloca(AllocaInst &AI);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000405 /// 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 Zaksbf28d3a2015-03-27 18:52:01 +0000409 unsigned *Alignment);
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,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000415 Value *SizeArgument, bool UseCalls, uint32_t Exp);
416 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
417 uint32_t TypeSize, bool IsWrite,
418 Value *SizeArgument, bool UseCalls,
419 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000420 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
421 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000422 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000423 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000424 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000425 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000426 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000427 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000428 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000429 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000430 static char ID; // Pass identification, replacement for typeid
431
Yury Gribov3ae427d2014-12-01 08:47:58 +0000432 DominatorTree &getDominatorTree() const { return *DT; }
433
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000434 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000435 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000436
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000437 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000438 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000439 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
440 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000441
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000442 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000443 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000444 int LongSize;
445 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000446 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000447 DominatorTree *DT;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000448 Function *AsanCtorFunction;
449 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000450 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000451 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000452 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
453 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
454 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
455 // This array is indexed by AccessIsWrite and Experiment.
456 Function *AsanErrorCallbackSized[2][2];
457 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000458 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000459 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000460 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000461 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000462
463 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000464};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000465
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000466class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000467 public:
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000468 AddressSanitizerModule() : ModulePass(ID) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000469 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000470 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000471 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000472
Kostya Serebryany20a79972012-11-22 03:18:50 +0000473 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000474 void initializeCallbacks(Module &M);
475
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000476 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000477 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000478 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000479 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000480 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000481 return RedzoneSizeForScale(Mapping.Scale);
482 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000483
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000484 GlobalsMetadata GlobalsMD;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000485 Type *IntptrTy;
486 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000487 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000488 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000489 Function *AsanPoisonGlobals;
490 Function *AsanUnpoisonGlobals;
491 Function *AsanRegisterGlobals;
492 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000493};
494
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000495// Stack poisoning does not play well with exception handling.
496// When an exception is thrown, we essentially bypass the code
497// that unpoisones the stack. This is why the run-time library has
498// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
499// stack in the interceptor. This however does not work inside the
500// actual function which catches the exception. Most likely because the
501// compiler hoists the load of the shadow value somewhere too high.
502// This causes asan to report a non-existing bug on 453.povray.
503// It sounds like an LLVM bug.
504struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
505 Function &F;
506 AddressSanitizer &ASan;
507 DIBuilder DIB;
508 LLVMContext *C;
509 Type *IntptrTy;
510 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000511 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000512
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000513 SmallVector<AllocaInst *, 16> AllocaVec;
514 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000515 unsigned StackAlignment;
516
Kostya Serebryany6805de52013-09-10 13:16:56 +0000517 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000518 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000519 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
520
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000521 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
522 struct AllocaPoisonCall {
523 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000524 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000525 uint64_t Size;
526 bool DoPoison;
527 };
528 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
529
Yury Gribov55441bb2014-11-21 10:29:50 +0000530 // Stores left and right redzone shadow addresses for dynamic alloca
531 // and pointer to alloca instruction itself.
532 // LeftRzAddr is a shadow address for alloca left redzone.
533 // RightRzAddr is a shadow address for alloca right redzone.
534 struct DynamicAllocaCall {
535 AllocaInst *AI;
536 Value *LeftRzAddr;
537 Value *RightRzAddr;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000538 bool Poison;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000539 explicit DynamicAllocaCall(AllocaInst *AI, Value *LeftRzAddr = nullptr,
540 Value *RightRzAddr = nullptr)
541 : AI(AI),
542 LeftRzAddr(LeftRzAddr),
543 RightRzAddr(RightRzAddr),
544 Poison(true) {}
Yury Gribov55441bb2014-11-21 10:29:50 +0000545 };
546 SmallVector<DynamicAllocaCall, 1> DynamicAllocaVec;
547
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000548 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000549 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000550 AllocaForValueMapTy AllocaForValue;
551
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000552 bool HasNonEmptyInlineAsm;
553 std::unique_ptr<CallInst> EmptyInlineAsm;
554
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000555 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000556 : F(F),
557 ASan(ASan),
558 DIB(*F.getParent(), /*AllowUnresolved*/ false),
559 C(ASan.C),
560 IntptrTy(ASan.IntptrTy),
561 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
562 Mapping(ASan.Mapping),
563 StackAlignment(1 << Mapping.Scale),
564 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000565 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000566
567 bool runOnFunction() {
568 if (!ClStack) return false;
569 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000570 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000571
Yury Gribov55441bb2014-11-21 10:29:50 +0000572 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000573
574 initializeCallbacks(*F.getParent());
575
576 poisonStack();
577
578 if (ClDebugStack) {
579 DEBUG(dbgs() << F);
580 }
581 return true;
582 }
583
Yury Gribov55441bb2014-11-21 10:29:50 +0000584 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000585 // poisoned red zones around all of them.
586 // Then unpoison everything back before the function returns.
587 void poisonStack();
588
589 // ----------------------- Visitors.
590 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000591 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000592
Yury Gribov55441bb2014-11-21 10:29:50 +0000593 // Unpoison dynamic allocas redzones.
594 void unpoisonDynamicAlloca(DynamicAllocaCall &AllocaCall) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000595 if (!AllocaCall.Poison) return;
Yury Gribov55441bb2014-11-21 10:29:50 +0000596 for (auto Ret : RetVec) {
597 IRBuilder<> IRBRet(Ret);
598 PointerType *Int32PtrTy = PointerType::getUnqual(IRBRet.getInt32Ty());
599 Value *Zero = Constant::getNullValue(IRBRet.getInt32Ty());
600 Value *PartialRzAddr = IRBRet.CreateSub(AllocaCall.RightRzAddr,
601 ConstantInt::get(IntptrTy, 4));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000602 IRBRet.CreateStore(
603 Zero, IRBRet.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
604 IRBRet.CreateStore(Zero,
605 IRBRet.CreateIntToPtr(PartialRzAddr, Int32PtrTy));
606 IRBRet.CreateStore(
607 Zero, IRBRet.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
Yury Gribov55441bb2014-11-21 10:29:50 +0000608 }
609 }
610
611 // Right shift for BigEndian and left shift for LittleEndian.
612 Value *shiftAllocaMagic(Value *Val, IRBuilder<> &IRB, Value *Shift) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000613 auto &DL = F.getParent()->getDataLayout();
614 return DL.isLittleEndian() ? IRB.CreateShl(Val, Shift)
615 : IRB.CreateLShr(Val, Shift);
Yury Gribov55441bb2014-11-21 10:29:50 +0000616 }
617
618 // Compute PartialRzMagic for dynamic alloca call. Since we don't know the
619 // size of requested memory until runtime, we should compute it dynamically.
620 // If PartialSize is 0, PartialRzMagic would contain kAsanAllocaRightMagic,
621 // otherwise it would contain the value that we will use to poison the
622 // partial redzone for alloca call.
623 Value *computePartialRzMagic(Value *PartialSize, IRBuilder<> &IRB);
624
625 // Deploy and poison redzones around dynamic alloca call. To do this, we
626 // should replace this call with another one with changed parameters and
627 // replace all its uses with new address, so
628 // addr = alloca type, old_size, align
629 // is replaced by
630 // new_size = (old_size + additional_size) * sizeof(type)
631 // tmp = alloca i8, new_size, max(align, 32)
632 // addr = tmp + 32 (first 32 bytes are for the left redzone).
633 // Additional_size is added to make new memory allocation contain not only
634 // requested memory, but also left, partial and right redzones.
635 // After that, we should poison redzones:
636 // (1) Left redzone with kAsanAllocaLeftMagic.
637 // (2) Partial redzone with the value, computed in runtime by
638 // computePartialRzMagic function.
639 // (3) Right redzone with kAsanAllocaRightMagic.
640 void handleDynamicAllocaCall(DynamicAllocaCall &AllocaCall);
641
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000642 /// \brief Collect Alloca instructions we want (and can) handle.
643 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000644 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000645
646 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov55441bb2014-11-21 10:29:50 +0000647 if (isDynamicAlloca(AI))
648 DynamicAllocaVec.push_back(DynamicAllocaCall(&AI));
649 else
650 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000651 }
652
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000653 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
654 /// errors.
655 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000656 if (!ClCheckLifetime) return;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000657 Intrinsic::ID ID = II.getIntrinsicID();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000658 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000659 return;
660 // Found lifetime intrinsic, add ASan instrumentation if necessary.
661 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
662 // If size argument is undefined, don't do anything.
663 if (Size->isMinusOne()) return;
664 // Check that size doesn't saturate uint64_t and can
665 // be stored in IntptrTy.
666 const uint64_t SizeValue = Size->getValue().getLimitedValue();
667 if (SizeValue == ~0ULL ||
668 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
669 return;
670 // Find alloca instruction that corresponds to llvm.lifetime argument.
671 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
672 if (!AI) return;
673 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000674 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000675 AllocaPoisonCallVec.push_back(APC);
676 }
677
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000678 void visitCallInst(CallInst &CI) {
679 HasNonEmptyInlineAsm |=
680 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
681 }
682
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000683 // ---------------------- Helpers.
684 void initializeCallbacks(Module &M);
685
Yury Gribov3ae427d2014-12-01 08:47:58 +0000686 bool doesDominateAllExits(const Instruction *I) const {
687 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000688 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000689 }
690 return true;
691 }
692
Yury Gribov55441bb2014-11-21 10:29:50 +0000693 bool isDynamicAlloca(AllocaInst &AI) const {
694 return AI.isArrayAllocation() || !AI.isStaticAlloca();
695 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000696 /// Finds alloca where the value comes from.
697 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000698 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000699 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000700 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000701
702 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
703 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000704 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
705 bool Dynamic);
706 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
707 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000708};
709
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000710} // namespace
711
712char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000713INITIALIZE_PASS_BEGIN(
714 AddressSanitizer, "asan",
715 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
716 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000717INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000718INITIALIZE_PASS_END(
719 AddressSanitizer, "asan",
720 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
721 false)
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000722FunctionPass *llvm::createAddressSanitizerFunctionPass() {
723 return new AddressSanitizer();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000724}
725
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000726char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000727INITIALIZE_PASS(
728 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000729 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000730 "ModulePass",
731 false, false)
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000732ModulePass *llvm::createAddressSanitizerModulePass() {
733 return new AddressSanitizerModule();
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000734}
735
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000736static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000737 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000738 assert(Res < kNumberOfAccessSizes);
739 return Res;
740}
741
Bill Wendling58f8cef2013-08-06 22:52:42 +0000742// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000743static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
744 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000745 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000746 // We use private linkage for module-local strings. If they can be merged
747 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000748 GlobalVariable *GV =
749 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000750 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000751 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000752 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
753 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000754}
755
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000756/// \brief Create a global describing a source location.
757static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
758 LocationMetadata MD) {
759 Constant *LocData[] = {
760 createPrivateGlobalForString(M, MD.Filename, true),
761 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
762 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
763 };
764 auto LocStruct = ConstantStruct::getAnon(LocData);
765 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
766 GlobalValue::PrivateLinkage, LocStruct,
767 kAsanGenPrefix);
768 GV->setUnnamedAddr(true);
769 return GV;
770}
771
Kostya Serebryany139a9372012-11-20 14:16:08 +0000772static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000773 return G->getName().find(kAsanGenPrefix) == 0 ||
774 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000775}
776
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000777Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
778 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000779 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000780 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000781 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000782 if (Mapping.OrShadowOffset)
783 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
784 else
785 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000786}
787
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000788// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000789void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
790 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000791 if (isa<MemTransferInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000792 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000793 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
794 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
795 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
796 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
797 } else if (isa<MemSetInst>(MI)) {
Evgeniy Stepanoved31ca42014-05-14 10:56:19 +0000798 IRB.CreateCall3(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000799 AsanMemset,
800 IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
801 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
802 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000803 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000804 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000805}
806
Anna Zaks8ed1d812015-02-27 03:12:36 +0000807/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000808bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
809 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
810
811 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
812 return PreviouslySeenAllocaInfo->getSecond();
813
814 bool IsInteresting = (AI.getAllocatedType()->isSized() &&
815 // alloca() may be called with 0 size, ignore it.
816 getAllocaSizeInBytes(&AI) > 0 &&
817 // We are only interested in allocas not promotable to registers.
818 // Promotable allocas are common under -O0.
819 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)));
820
821 ProcessedAllocas[&AI] = IsInteresting;
822 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000823}
824
825/// If I is an interesting memory access, return the PointerOperand
826/// and set IsWrite/Alignment. Otherwise return nullptr.
827Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
828 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000829 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000830 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000831 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000832 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000833
834 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000835 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000836 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000837 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000838 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000839 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000840 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000841 PtrOperand = LI->getPointerOperand();
842 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000843 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000844 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000845 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000846 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000847 PtrOperand = SI->getPointerOperand();
848 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000849 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000850 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000851 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000852 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000853 PtrOperand = RMW->getPointerOperand();
854 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000855 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000856 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000857 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000858 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000859 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000860 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000861
862 // Treat memory accesses to promotable allocas as non-interesting since they
863 // will not cause memory violations. This greatly speeds up the instrumented
864 // executable at -O0.
865 if (ClSkipPromotableAllocas)
866 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
867 return isInterestingAlloca(*AI) ? AI : nullptr;
868
869 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000870}
871
Kostya Serebryany796f6552014-02-27 12:45:36 +0000872static bool isPointerOperand(Value *V) {
873 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
874}
875
876// This is a rough heuristic; it may cause both false positives and
877// false negatives. The proper implementation requires cooperation with
878// the frontend.
879static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
880 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000881 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000882 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000883 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000884 } else {
885 return false;
886 }
887 if (!isPointerOperand(I->getOperand(0)) ||
888 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000889 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000890 return true;
891}
892
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000893bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
894 // If a global variable does not have dynamic initialization we don't
895 // have to instrument it. However, if a global does not have initializer
896 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000897 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000898}
899
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000900void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
901 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000902 IRBuilder<> IRB(I);
903 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
904 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
905 for (int i = 0; i < 2; i++) {
906 if (Param[i]->getType()->isPointerTy())
907 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
908 }
909 IRB.CreateCall2(F, Param[0], Param[1]);
910}
911
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000912void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000913 Instruction *I, bool UseCalls,
914 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000915 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000916 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000917 uint64_t TypeSize = 0;
918 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000919 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000920
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000921 // Optimization experiments.
922 // The experiments can be used to evaluate potential optimizations that remove
923 // instrumentation (assess false negatives). Instead of completely removing
924 // some instrumentation, you set Exp to a non-zero value (mask of optimization
925 // experiments that want to remove instrumentation of this instruction).
926 // If Exp is non-zero, this pass will emit special calls into runtime
927 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
928 // make runtime terminate the program in a special way (with a different
929 // exit status). Then you run the new compiler on a buggy corpus, collect
930 // the special terminations (ideally, you don't see them at all -- no false
931 // negatives) and make the decision on the optimization.
932 uint32_t Exp = ClForceExperiment;
933
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000934 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000935 // If initialization order checking is disabled, a simple access to a
936 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000937 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000938 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
939 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
940 NumOptimizedAccessesToGlobalVar++;
941 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000942 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000943 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000944
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000945 if (ClOpt && ClOptStack) {
946 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000947 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000948 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
949 NumOptimizedAccessesToStackVar++;
950 return;
951 }
952 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000953
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000954 if (IsWrite)
955 NumInstrumentedWrites++;
956 else
957 NumInstrumentedReads++;
958
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000959 unsigned Granularity = 1 << Mapping.Scale;
960 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
961 // if the data is properly aligned.
962 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
963 TypeSize == 128) &&
964 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000965 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
966 Exp);
967 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
968 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000969}
970
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000971Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
972 Value *Addr, bool IsWrite,
973 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000974 Value *SizeArgument,
975 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000976 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000977 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
978 CallInst *Call = nullptr;
979 if (SizeArgument) {
980 if (Exp == 0)
981 Call = IRB.CreateCall2(AsanErrorCallbackSized[IsWrite][0], Addr,
982 SizeArgument);
983 else
984 Call = IRB.CreateCall3(AsanErrorCallbackSized[IsWrite][1], Addr,
985 SizeArgument, ExpVal);
986 } else {
987 if (Exp == 0)
988 Call =
989 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
990 else
991 Call = IRB.CreateCall2(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
992 Addr, ExpVal);
993 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000994
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000995 // We don't do Call->setDoesNotReturn() because the BB already has
996 // UnreachableInst at the end.
997 // This EmptyAsm is required to avoid callback merge.
998 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000999 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001000}
1001
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001002Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001003 Value *ShadowValue,
1004 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +00001005 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001006 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001007 Value *LastAccessedByte =
1008 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001009 // (Addr & (Granularity - 1)) + size - 1
1010 if (TypeSize / 8 > 1)
1011 LastAccessedByte = IRB.CreateAdd(
1012 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1013 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001014 LastAccessedByte =
1015 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001016 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1017 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1018}
1019
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001020void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001021 Instruction *InsertBefore, Value *Addr,
1022 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001023 Value *SizeArgument, bool UseCalls,
1024 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001025 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001026 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001027 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1028
1029 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001030 if (Exp == 0)
1031 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1032 AddrLong);
1033 else
1034 IRB.CreateCall2(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1035 AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp));
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001036 return;
1037 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001038
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001039 Type *ShadowTy =
1040 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001041 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1042 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1043 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001044 Value *ShadowValue =
1045 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001046
1047 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001048 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001049 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001050
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001051 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001052 // We use branch weights for the slow path check, to indicate that the slow
1053 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001054 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1055 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001056 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001057 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001058 IRB.SetInsertPoint(CheckTerm);
1059 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001060 BasicBlock *CrashBlock =
1061 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001062 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001063 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1064 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001065 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001066 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001067 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001068
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001069 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001070 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001071 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001072}
1073
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001074// Instrument unusual size or unusual alignment.
1075// We can not do it with a single check, so we do 1-byte check for the first
1076// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1077// to report the actual access size.
1078void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1079 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1080 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1081 IRBuilder<> IRB(I);
1082 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1083 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1084 if (UseCalls) {
1085 if (Exp == 0)
1086 IRB.CreateCall2(AsanMemoryAccessCallbackSized[IsWrite][0], AddrLong,
1087 Size);
1088 else
1089 IRB.CreateCall3(AsanMemoryAccessCallbackSized[IsWrite][1], AddrLong, Size,
1090 ConstantInt::get(IRB.getInt32Ty(), Exp));
1091 } else {
1092 Value *LastByte = IRB.CreateIntToPtr(
1093 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1094 Addr->getType());
1095 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1096 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1097 }
1098}
1099
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001100void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1101 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001102 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001103 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001104
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001105 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001106 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1107 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001108
1109 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001110 for (auto &BB : GlobalInit.getBasicBlockList())
1111 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001112 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001113}
1114
1115void AddressSanitizerModule::createInitializerPoisonCalls(
1116 Module &M, GlobalValue *ModuleName) {
1117 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1118
1119 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1120 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001121 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001122 ConstantStruct *CS = cast<ConstantStruct>(OP);
1123
1124 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001125 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001126 if (F->getName() == kAsanModuleCtorName) continue;
1127 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1128 // Don't instrument CTORs that will run before asan.module_ctor.
1129 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1130 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001131 }
1132 }
1133}
1134
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001135bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001136 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001137 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001138
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001139 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001140 if (!Ty->isSized()) return false;
1141 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001142 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001143 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001144 // Don't handle ODR linkage types and COMDATs since other modules may be built
1145 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001146 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1147 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1148 G->getLinkage() != GlobalVariable::InternalLinkage)
1149 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001150 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001151 // Two problems with thread-locals:
1152 // - The address of the main thread's copy can't be computed at link-time.
1153 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001154 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001155 // For now, just ignore this Global if the alignment is large.
1156 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001157
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001158 if (G->hasSection()) {
1159 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001160
Kuba Brecka1001bb52014-12-05 22:19:18 +00001161 if (TargetTriple.isOSBinFormatMachO()) {
1162 StringRef ParsedSegment, ParsedSection;
1163 unsigned TAA = 0, StubSize = 0;
1164 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001165 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1166 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001167 if (!ErrorCode.empty()) {
1168 report_fatal_error("Invalid section specifier '" + ParsedSection +
1169 "': " + ErrorCode + ".");
1170 }
1171
1172 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1173 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1174 // them.
1175 if (ParsedSegment == "__OBJC" ||
1176 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1177 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1178 return false;
1179 }
1180 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1181 // Constant CFString instances are compiled in the following way:
1182 // -- the string buffer is emitted into
1183 // __TEXT,__cstring,cstring_literals
1184 // -- the constant NSConstantString structure referencing that buffer
1185 // is placed into __DATA,__cfstring
1186 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1187 // Moreover, it causes the linker to crash on OS X 10.7
1188 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1189 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1190 return false;
1191 }
1192 // The linker merges the contents of cstring_literals and removes the
1193 // trailing zeroes.
1194 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1195 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1196 return false;
1197 }
1198 }
Timur Iskhodzhanov9dbc2062014-05-05 14:28:38 +00001199
1200 // Callbacks put into the CRT initializer/terminator sections
1201 // should not be instrumented.
1202 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1203 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1204 if (Section.startswith(".CRT")) {
1205 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1206 return false;
1207 }
1208
Alexander Potapenko04969e82014-03-20 10:48:34 +00001209 // Globals from llvm.metadata aren't emitted, do not instrument them.
1210 if (Section == "llvm.metadata") return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001211 }
1212
1213 return true;
1214}
1215
Alexey Samsonov788381b2012-12-25 12:28:20 +00001216void AddressSanitizerModule::initializeCallbacks(Module &M) {
1217 IRBuilder<> IRB(*C);
1218 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001219 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001220 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001221 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001222 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001223 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001224 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1225 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001226 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001227 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001228 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001229 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001230 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1231 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001232 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1233}
1234
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001235// This function replaces all global variables with new variables that have
1236// trailing redzones. It also creates a function that poisons
1237// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001238bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001239 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001241 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1242
Alexey Samsonova02e6642014-05-29 18:40:48 +00001243 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001244 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001245 }
1246
1247 size_t n = GlobalsToChange.size();
1248 if (n == 0) return false;
1249
1250 // A global is described by a structure
1251 // size_t beg;
1252 // size_t size;
1253 // size_t size_with_redzone;
1254 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001255 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001256 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001257 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001258 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001259 StructType *GlobalStructTy =
1260 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001261 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001262 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001263
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001264 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001265
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001266 // We shouldn't merge same module names, as this string serves as unique
1267 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001268 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001269 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001270
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001271 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001272 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001273 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001274 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001275
1276 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001277 // Create string holding the global name (use global name from metadata
1278 // if it's available, otherwise just write the name of global variable).
1279 GlobalVariable *Name = createPrivateGlobalForString(
1280 M, MD.Name.empty() ? G->getName() : MD.Name,
1281 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001282
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001283 PointerType *PtrTy = cast<PointerType>(G->getType());
1284 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001285 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001286 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001287 // MinRZ <= RZ <= kMaxGlobalRedzone
1288 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001289 uint64_t RZ = std::max(
1290 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001291 uint64_t RightRedzoneSize = RZ;
1292 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001293 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001294 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001295 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1296
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001297 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001298 Constant *NewInitializer =
1299 ConstantStruct::get(NewTy, G->getInitializer(),
1300 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001301
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001302 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001303 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1304 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1305 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001306 GlobalVariable *NewGlobal =
1307 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1308 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001309 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001310 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001311
1312 Value *Indices2[2];
1313 Indices2[0] = IRB.getInt32(0);
1314 Indices2[1] = IRB.getInt32(0);
1315
1316 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001317 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001318 NewGlobal->takeName(G);
1319 G->eraseFromParent();
1320
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001321 Constant *SourceLoc;
1322 if (!MD.SourceLoc.empty()) {
1323 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1324 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1325 } else {
1326 SourceLoc = ConstantInt::get(IntptrTy, 0);
1327 }
1328
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001329 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001330 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001331 ConstantInt::get(IntptrTy, SizeInBytes),
1332 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1333 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001334 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001335 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001336
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001337 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001338
Kostya Serebryany20343352012-10-17 13:40:06 +00001339 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001340 }
1341
1342 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1343 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001344 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001345 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1346
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001347 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001348 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001349 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001350 IRB.CreateCall2(AsanRegisterGlobals,
1351 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1352 ConstantInt::get(IntptrTy, n));
1353
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001354 // We also need to unregister globals at the end, e.g. when a shared library
1355 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001356 Function *AsanDtorFunction =
1357 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1358 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001359 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1360 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001361 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1362 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1363 ConstantInt::get(IntptrTy, n));
Alexey Samsonov1f647502014-05-29 01:10:14 +00001364 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001365
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001366 DEBUG(dbgs() << M);
1367 return true;
1368}
1369
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001370bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001371 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001372 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001373 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001374 TargetTriple = Triple(M.getTargetTriple());
1375 Mapping = getShadowMapping(TargetTriple, LongSize);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001376 initializeCallbacks(M);
1377
1378 bool Changed = false;
1379
1380 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1381 assert(CtorFunc);
1382 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1383
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001384 if (ClGlobals) Changed |= InstrumentGlobals(IRB, M);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001385
1386 return Changed;
1387}
1388
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001389void AddressSanitizer::initializeCallbacks(Module &M) {
1390 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001391 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001392 // IsWrite, TypeSize and Exp are encoded in the function name.
1393 for (int Exp = 0; Exp < 2; Exp++) {
1394 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1395 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1396 const std::string ExpStr = Exp ? "exp_" : "";
1397 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1398 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001399 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001400 kAsanReportErrorTemplate + ExpStr + TypeStr + "_n",
1401 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1402 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001403 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001404 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N",
1405 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1406 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1407 AccessSizeIndex++) {
1408 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1409 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001410 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001411 kAsanReportErrorTemplate + ExpStr + Suffix, IRB.getVoidTy(),
1412 IntptrTy, ExpType, nullptr));
1413 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001414 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001415 ClMemoryAccessCallbackPrefix + ExpStr + Suffix, IRB.getVoidTy(),
1416 IntptrTy, ExpType, nullptr));
1417 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001418 }
1419 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001420
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001421 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001422 ClMemoryAccessCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001423 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001424 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001425 ClMemoryAccessCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001426 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001427 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001428 ClMemoryAccessCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001429 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001430
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001431 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001432 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001433
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001434 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001435 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001436 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001437 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001438 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1439 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1440 StringRef(""), StringRef(""),
1441 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001442}
1443
1444// virtual
1445bool AddressSanitizer::doInitialization(Module &M) {
1446 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001447
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001448 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001449
1450 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001451 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001452 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001453 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001454
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001455 AsanCtorFunction =
1456 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1457 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001458 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1459 // call __asan_init in the module ctor.
1460 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001461 AsanInitFunction = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001462 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001463 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1464 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001465
Kuba Brecka1001bb52014-12-05 22:19:18 +00001466 Mapping = getShadowMapping(TargetTriple, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001467
Alexey Samsonov1f647502014-05-29 01:10:14 +00001468 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001469 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001470}
1471
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001472bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1473 // For each NSObject descendant having a +load method, this method is invoked
1474 // by the ObjC runtime before any of the static constructors is called.
1475 // Therefore we need to instrument such methods with a call to __asan_init
1476 // at the beginning in order to initialize our runtime before any access to
1477 // the shadow memory.
1478 // We cannot just ignore these methods, because they may call other
1479 // instrumented functions.
1480 if (F.getName().find(" load]") != std::string::npos) {
1481 IRBuilder<> IRB(F.begin()->begin());
1482 IRB.CreateCall(AsanInitFunction);
1483 return true;
1484 }
1485 return false;
1486}
1487
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001488bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001489 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001490 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001491 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001492 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001493
Yury Gribov3ae427d2014-12-01 08:47:58 +00001494 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1495
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001496 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001497 maybeInsertAsanInitAtFunctionEntry(F);
1498
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001499 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001500
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001501 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001502
1503 // We want to instrument every address only once per basic block (unless there
1504 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001505 SmallSet<Value *, 16> TempsToInstrument;
1506 SmallVector<Instruction *, 16> ToInstrument;
1507 SmallVector<Instruction *, 8> NoReturnCalls;
1508 SmallVector<BasicBlock *, 16> AllBlocks;
1509 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001510 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001511 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001512 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001513 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514
1515 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001516 for (auto &BB : F) {
1517 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001518 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001519 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001520 for (auto &Inst : BB) {
1521 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001522 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1523 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001524 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001525 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001526 continue; // We've seen this temp in the current BB.
1527 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001528 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001529 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1530 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001531 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001532 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001533 // ok, take it.
1534 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001535 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001536 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001537 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001538 // A call inside BB.
1539 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001540 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001541 }
1542 continue;
1543 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001544 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001545 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001546 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001547 }
1548 }
1549
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001550 bool UseCalls = false;
1551 if (ClInstrumentationWithCallsThreshold >= 0 &&
1552 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold)
1553 UseCalls = true;
1554
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001555 const TargetLibraryInfo *TLI =
1556 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001557 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001558 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1559 /*RoundToAlign=*/true);
1560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001561 // Instrument.
1562 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001563 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001564 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1565 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001566 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 instrumentMop(ObjSizeVis, Inst, UseCalls,
1568 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001569 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001570 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001571 }
1572 NumInstrumented++;
1573 }
1574
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001575 FunctionStackPoisoner FSP(F, *this);
1576 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001577
1578 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1579 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001580 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001581 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001582 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001583 }
1584
Alexey Samsonova02e6642014-05-29 18:40:48 +00001585 for (auto Inst : PointerComparisonsOrSubtracts) {
1586 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001587 NumInstrumented++;
1588 }
1589
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001590 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001591
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001592 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1593
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001594 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001595}
1596
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001597// Workaround for bug 11395: we don't want to instrument stack in functions
1598// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1599// FIXME: remove once the bug 11395 is fixed.
1600bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1601 if (LongSize != 32) return false;
1602 CallInst *CI = dyn_cast<CallInst>(I);
1603 if (!CI || !CI->isInlineAsm()) return false;
1604 if (CI->getNumArgOperands() <= 5) return false;
1605 // We have inline assembly with quite a few arguments.
1606 return true;
1607}
1608
1609void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1610 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001611 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1612 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001613 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1614 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1615 IntptrTy, nullptr));
1616 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001617 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1618 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001619 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001620 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001621 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1622 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001623 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001624 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1625 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001626}
1627
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001628void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1629 IRBuilder<> &IRB, Value *ShadowBase,
1630 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001631 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001632 size_t i = 0;
1633 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1634 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1635 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1636 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1637 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1638 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1639 uint64_t Val = 0;
1640 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001641 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001642 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1643 else
1644 Val = (Val << 8) | ShadowBytes[i + j];
1645 }
1646 if (!Val) continue;
1647 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1648 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1649 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1650 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001651 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001652 }
1653}
1654
Kostya Serebryany6805de52013-09-10 13:16:56 +00001655// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1656// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1657static int StackMallocSizeClass(uint64_t LocalStackSize) {
1658 assert(LocalStackSize <= kMaxStackMallocSize);
1659 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001660 for (int i = 0;; i++, MaxSize *= 2)
1661 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001662 llvm_unreachable("impossible LocalStackSize");
1663}
1664
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001665// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1666// We can not use MemSet intrinsic because it may end up calling the actual
1667// memset. Size is a multiple of 8.
1668// Currently this generates 8-byte stores on x86_64; it may be better to
1669// generate wider stores.
1670void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1671 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1672 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001673
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001674 // kAsanStackAfterReturnMagic is 0xf5.
1675 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001676
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001677 for (int i = 0; i < Size; i += 8) {
1678 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001679 IRB.CreateStore(
1680 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1681 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001682 }
1683}
1684
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001685static DebugLoc getFunctionEntryDebugLocation(Function &F) {
Alexey Samsonova02e6642014-05-29 18:40:48 +00001686 for (const auto &Inst : F.getEntryBlock())
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001687 if (!isa<AllocaInst>(Inst)) return Inst.getDebugLoc();
Alexey Samsonova02e6642014-05-29 18:40:48 +00001688 return DebugLoc();
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001689}
1690
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001691PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1692 Value *ValueIfTrue,
1693 Instruction *ThenTerm,
1694 Value *ValueIfFalse) {
1695 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1696 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1697 PHI->addIncoming(ValueIfFalse, CondBlock);
1698 BasicBlock *ThenBlock = ThenTerm->getParent();
1699 PHI->addIncoming(ValueIfTrue, ThenBlock);
1700 return PHI;
1701}
1702
1703Value *FunctionStackPoisoner::createAllocaForLayout(
1704 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1705 AllocaInst *Alloca;
1706 if (Dynamic) {
1707 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1708 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1709 "MyAlloca");
1710 } else {
1711 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1712 nullptr, "MyAlloca");
1713 assert(Alloca->isStaticAlloca());
1714 }
1715 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1716 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1717 Alloca->setAlignment(FrameAlignment);
1718 return IRB.CreatePointerCast(Alloca, IntptrTy);
1719}
1720
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001721void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001722 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1723
Kuba Breckaf5875d32015-02-24 09:47:05 +00001724 if (ClInstrumentAllocas) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001725 // Handle dynamic allocas.
Kuba Breckaf5875d32015-02-24 09:47:05 +00001726 for (auto &AllocaCall : DynamicAllocaVec) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001727 handleDynamicAllocaCall(AllocaCall);
Kuba Breckaf5875d32015-02-24 09:47:05 +00001728 unpoisonDynamicAlloca(AllocaCall);
1729 }
1730 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001731
1732 if (AllocaVec.size() == 0) return;
1733
Kostya Serebryany6805de52013-09-10 13:16:56 +00001734 int StackMallocIdx = -1;
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001735 DebugLoc EntryDebugLocation = getFunctionEntryDebugLocation(F);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001736
1737 Instruction *InsBefore = AllocaVec[0];
1738 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001739 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001740
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001741 SmallVector<ASanStackVariableDescription, 16> SVD;
1742 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001743 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001744 ASanStackVariableDescription D = {AI->getName().data(),
1745 ASan.getAllocaSizeInBytes(AI),
1746 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001747 SVD.push_back(D);
1748 }
1749 // Minimal header size (left redzone) is 4 pointers,
1750 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1751 size_t MinHeaderSize = ASan.LongSize / 2;
1752 ASanStackFrameLayout L;
1753 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1754 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1755 uint64_t LocalStackSize = L.FrameSize;
1756 bool DoStackMalloc =
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001757 ClUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001758 // Don't do dynamic alloca in presence of inline asm: too often it makes
1759 // assumptions on which registers are available. Don't do stack malloc in the
1760 // presence of inline asm on 32-bit platforms for the same reason.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001761 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Reid Kleckner92b9c6e2015-04-02 21:44:55 +00001762 DoStackMalloc &= !HasNonEmptyInlineAsm || ASan.LongSize != 32;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001763
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001764 Value *StaticAlloca =
1765 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1766
1767 Value *FakeStack;
1768 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001769
1770 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001771 // void *FakeStack = __asan_option_detect_stack_use_after_return
1772 // ? __asan_stack_malloc_N(LocalStackSize)
1773 // : nullptr;
1774 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001775 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1776 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001777 Value *UARIsEnabled =
1778 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1779 Constant::getNullValue(IRB.getInt32Ty()));
1780 Instruction *Term =
1781 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001782 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001783 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001784 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1785 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1786 Value *FakeStackValue =
1787 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1788 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001789 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001790 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001791 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1792 ConstantInt::get(IntptrTy, 0));
1793
1794 Value *NoFakeStack =
1795 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1796 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1797 IRBIf.SetInsertPoint(Term);
1798 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1799 Value *AllocaValue =
1800 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1801 IRB.SetInsertPoint(InsBefore);
1802 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1803 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1804 } else {
1805 // void *FakeStack = nullptr;
1806 // void *LocalStackBase = alloca(LocalStackSize);
1807 FakeStack = ConstantInt::get(IntptrTy, 0);
1808 LocalStackBase =
1809 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001810 }
1811
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001812 // Insert poison calls for lifetime intrinsics for alloca.
1813 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001814 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001815 assert(APC.InsBefore);
1816 assert(APC.AI);
1817 IRBuilder<> IRB(APC.InsBefore);
1818 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001819 HavePoisonedAllocas |= APC.DoPoison;
1820 }
1821
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001822 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001823 for (const auto &Desc : SVD) {
1824 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001825 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001826 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001827 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001828 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001829 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001830 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001831
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001832 // The left-most redzone has enough space for at least 4 pointers.
1833 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001834 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1835 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1836 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001837 // Write the frame description constant to redzone[1].
1838 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001839 IRB.CreateAdd(LocalStackBase,
1840 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1841 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001842 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001843 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001844 /*AllowMerging*/ true);
1845 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001846 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001847 // Write the PC to redzone[2].
1848 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001849 IRB.CreateAdd(LocalStackBase,
1850 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1851 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001852 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001853
1854 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001855 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001856 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001857
Kostya Serebryany530e2072013-12-23 14:15:08 +00001858 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001859 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001860 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001861 // Mark the current frame as retired.
1862 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1863 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001864 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001865 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001866 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001867 // // In use-after-return mode, poison the whole stack frame.
1868 // if StackMallocIdx <= 4
1869 // // For small sizes inline the whole thing:
1870 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001871 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001872 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001873 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001874 // else
1875 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001876 Value *Cmp =
1877 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001878 TerminatorInst *ThenTerm, *ElseTerm;
1879 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1880
1881 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001882 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001883 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1884 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1885 ClassSize >> Mapping.Scale);
1886 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001887 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001888 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1889 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1890 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1891 IRBPoison.CreateStore(
1892 Constant::getNullValue(IRBPoison.getInt8Ty()),
1893 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1894 } else {
1895 // For larger frames call __asan_stack_free_*.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001896 IRBPoison.CreateCall2(AsanStackFreeFunc[StackMallocIdx], FakeStack,
1897 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001898 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001899
1900 IRBuilder<> IRBElse(ElseTerm);
1901 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001902 } else if (HavePoisonedAllocas) {
1903 // If we poisoned some allocas in llvm.lifetime analysis,
1904 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001905 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001906 } else {
1907 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001908 }
1909 }
1910
Kostya Serebryany09959942012-10-19 06:20:53 +00001911 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001912 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001913}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001914
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001915void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001916 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001917 // For now just insert the call to ASan runtime.
1918 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1919 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001920 IRB.CreateCall2(
1921 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1922 AddrArg, SizeArg);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001923}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001924
1925// Handling llvm.lifetime intrinsics for a given %alloca:
1926// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1927// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1928// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1929// could be poisoned by previous llvm.lifetime.end instruction, as the
1930// variable may go in and out of scope several times, e.g. in loops).
1931// (3) if we poisoned at least one %alloca in a function,
1932// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001933
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001934AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1935 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1936 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001937 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001938 // See if we've already calculated (or started to calculate) alloca for a
1939 // given value.
1940 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001941 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001942 // Store 0 while we're calculating alloca for value V to avoid
1943 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001944 AllocaForValue[V] = nullptr;
1945 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001946 if (CastInst *CI = dyn_cast<CastInst>(V))
1947 Res = findAllocaForValue(CI->getOperand(0));
1948 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1949 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1950 Value *IncValue = PN->getIncomingValue(i);
1951 // Allow self-referencing phi-nodes.
1952 if (IncValue == PN) continue;
1953 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1954 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001955 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1956 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001957 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001958 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001959 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001960 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001961 return Res;
1962}
Yury Gribov55441bb2014-11-21 10:29:50 +00001963
1964// Compute PartialRzMagic for dynamic alloca call. PartialRzMagic is
1965// constructed from two separate 32-bit numbers: PartialRzMagic = Val1 | Val2.
1966// (1) Val1 is resposible for forming base value for PartialRzMagic, containing
1967// only 00 for fully addressable and 0xcb for fully poisoned bytes for each
1968// 8-byte chunk of user memory respectively.
1969// (2) Val2 forms the value for marking first poisoned byte in shadow memory
1970// with appropriate value (0x01 - 0x07 or 0xcb if Padding % 8 == 0).
1971
1972// Shift = Padding & ~7; // the number of bits we need to shift to access first
1973// chunk in shadow memory, containing nonzero bytes.
1974// Example:
1975// Padding = 21 Padding = 16
1976// Shadow: |00|00|05|cb| Shadow: |00|00|cb|cb|
1977// ^ ^
1978// | |
1979// Shift = 21 & ~7 = 16 Shift = 16 & ~7 = 16
1980//
1981// Val1 = 0xcbcbcbcb << Shift;
1982// PartialBits = Padding ? Padding & 7 : 0xcb;
1983// Val2 = PartialBits << Shift;
1984// Result = Val1 | Val2;
1985Value *FunctionStackPoisoner::computePartialRzMagic(Value *PartialSize,
1986 IRBuilder<> &IRB) {
1987 PartialSize = IRB.CreateIntCast(PartialSize, IRB.getInt32Ty(), false);
1988 Value *Shift = IRB.CreateAnd(PartialSize, IRB.getInt32(~7));
1989 unsigned Val1Int = kAsanAllocaPartialVal1;
1990 unsigned Val2Int = kAsanAllocaPartialVal2;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001991 if (!F.getParent()->getDataLayout().isLittleEndian()) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001992 Val1Int = sys::getSwappedBytes(Val1Int);
1993 Val2Int = sys::getSwappedBytes(Val2Int);
1994 }
1995 Value *Val1 = shiftAllocaMagic(IRB.getInt32(Val1Int), IRB, Shift);
1996 Value *PartialBits = IRB.CreateAnd(PartialSize, IRB.getInt32(7));
1997 // For BigEndian get 0x000000YZ -> 0xYZ000000.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001998 if (F.getParent()->getDataLayout().isBigEndian())
Yury Gribov55441bb2014-11-21 10:29:50 +00001999 PartialBits = IRB.CreateShl(PartialBits, IRB.getInt32(24));
2000 Value *Val2 = IRB.getInt32(Val2Int);
2001 Value *Cond =
2002 IRB.CreateICmpNE(PartialBits, Constant::getNullValue(IRB.getInt32Ty()));
2003 Val2 = IRB.CreateSelect(Cond, shiftAllocaMagic(PartialBits, IRB, Shift),
2004 shiftAllocaMagic(Val2, IRB, Shift));
2005 return IRB.CreateOr(Val1, Val2);
2006}
2007
2008void FunctionStackPoisoner::handleDynamicAllocaCall(
2009 DynamicAllocaCall &AllocaCall) {
2010 AllocaInst *AI = AllocaCall.AI;
Yury Gribov3ae427d2014-12-01 08:47:58 +00002011 if (!doesDominateAllExits(AI)) {
2012 // We do not yet handle complex allocas
2013 AllocaCall.Poison = false;
2014 return;
2015 }
2016
Yury Gribov55441bb2014-11-21 10:29:50 +00002017 IRBuilder<> IRB(AI);
2018
2019 PointerType *Int32PtrTy = PointerType::getUnqual(IRB.getInt32Ty());
2020 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2021 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2022
2023 Value *Zero = Constant::getNullValue(IntptrTy);
2024 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2025 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2026 Value *NotAllocaRzMask = ConstantInt::get(IntptrTy, ~AllocaRedzoneMask);
2027
2028 // Since we need to extend alloca with additional memory to locate
2029 // redzones, and OldSize is number of allocated blocks with
2030 // ElementSize size, get allocated memory size in bytes by
2031 // OldSize * ElementSize.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002032 unsigned ElementSize =
2033 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov55441bb2014-11-21 10:29:50 +00002034 Value *OldSize = IRB.CreateMul(AI->getArraySize(),
2035 ConstantInt::get(IntptrTy, ElementSize));
2036
2037 // PartialSize = OldSize % 32
2038 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2039
2040 // Misalign = kAllocaRzSize - PartialSize;
2041 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2042
2043 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2044 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2045 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2046
2047 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2048 // Align is added to locate left redzone, PartialPadding for possible
2049 // partial redzone and kAllocaRzSize for right redzone respectively.
2050 Value *AdditionalChunkSize = IRB.CreateAdd(
2051 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2052
2053 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2054
2055 // Insert new alloca with new NewSize and Align params.
2056 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2057 NewAlloca->setAlignment(Align);
2058
2059 // NewAddress = Address + Align
2060 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2061 ConstantInt::get(IntptrTy, Align));
2062
2063 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2064
2065 // LeftRzAddress = NewAddress - kAllocaRzSize
2066 Value *LeftRzAddress = IRB.CreateSub(NewAddress, AllocaRzSize);
2067
2068 // Poisoning left redzone.
2069 AllocaCall.LeftRzAddr = ASan.memToShadow(LeftRzAddress, IRB);
2070 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaLeftMagic),
2071 IRB.CreateIntToPtr(AllocaCall.LeftRzAddr, Int32PtrTy));
2072
2073 // PartialRzAligned = PartialRzAddr & ~AllocaRzMask
2074 Value *PartialRzAddr = IRB.CreateAdd(NewAddress, OldSize);
2075 Value *PartialRzAligned = IRB.CreateAnd(PartialRzAddr, NotAllocaRzMask);
2076
2077 // Poisoning partial redzone.
2078 Value *PartialRzMagic = computePartialRzMagic(PartialSize, IRB);
2079 Value *PartialRzShadowAddr = ASan.memToShadow(PartialRzAligned, IRB);
2080 IRB.CreateStore(PartialRzMagic,
2081 IRB.CreateIntToPtr(PartialRzShadowAddr, Int32PtrTy));
2082
2083 // RightRzAddress
2084 // = (PartialRzAddr + AllocaRzMask) & ~AllocaRzMask
2085 Value *RightRzAddress = IRB.CreateAnd(
2086 IRB.CreateAdd(PartialRzAddr, AllocaRzMask), NotAllocaRzMask);
2087
2088 // Poisoning right redzone.
2089 AllocaCall.RightRzAddr = ASan.memToShadow(RightRzAddress, IRB);
2090 IRB.CreateStore(ConstantInt::get(IRB.getInt32Ty(), kAsanAllocaRightMagic),
2091 IRB.CreateIntToPtr(AllocaCall.RightRzAddr, Int32PtrTy));
2092
2093 // Replace all uses of AddessReturnedByAlloca with NewAddress.
2094 AI->replaceAllUsesWith(NewAddressPtr);
2095
2096 // We are done. Erase old alloca and store left, partial and right redzones
2097 // shadow addresses for future unpoisoning.
2098 AI->eraseFromParent();
Kostya Serebryanyea2cb6f2014-11-21 21:25:18 +00002099 NumInstrumentedDynamicAllocas++;
Yury Gribov55441bb2014-11-21 10:29:50 +00002100}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002101
2102// isSafeAccess returns true if Addr is always inbounds with respect to its
2103// base object. For example, it is a field access or an array access with
2104// constant inbounds index.
2105bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2106 Value *Addr, uint64_t TypeSize) const {
2107 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2108 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002109 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002110 int64_t Offset = SizeOffset.second.getSExtValue();
2111 // Three checks are required to ensure safety:
2112 // . Offset >= 0 (since the offset is given from the base ptr)
2113 // . Size >= Offset (unsigned)
2114 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002115 return Offset >= 0 && Size >= uint64_t(Offset) &&
2116 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002117}