blob: 072eab29405dad7e32a51f60bd1b1ee2553207af [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"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000021#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000025#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000026#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000027#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000028#include "llvm/Analysis/MemoryBuiltins.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000031#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000032#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Function.h"
36#include "llvm/IR/IRBuilder.h"
37#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000038#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IntrinsicInst.h"
40#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000042#include "llvm/IR/Module.h"
43#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000044#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000045#include "llvm/Support/CommandLine.h"
46#include "llvm/Support/DataTypes.h"
47#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000048#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000049#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000050#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000051#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000052#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000054#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000055#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000057#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000058#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000059#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000060#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000061
62using namespace llvm;
63
Chandler Carruth964daaa2014-04-22 02:55:47 +000064#define DEBUG_TYPE "asan"
65
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000066static const uint64_t kDefaultShadowScale = 3;
67static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
68static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000069static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
70static const uint64_t kIOSShadowOffset64 = 0x120200000;
71static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
72static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000073static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000074static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000075static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000076static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000077static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000078static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000079static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
80static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000081static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000082
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000083static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000084static const size_t kMaxStackMallocSize = 1 << 16; // 64K
85static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
86static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
87
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanModuleCtorName = "asan.module_ctor";
89static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000090static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000092static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000093static const char *const kAsanUnregisterGlobalsName =
94 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000095static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
96static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +000097static const char *const kAsanInitName = "__asan_init";
98static const char *const kAsanVersionCheckName =
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +000099 "__asan_version_mismatch_check_v7";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000100static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
101static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000103static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000104static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
105static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000106static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000107static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000108static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000109static const char *const kAsanPoisonStackMemoryName =
110 "__asan_poison_stack_memory";
111static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000112 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000113
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000114static const char *const kAsanOptionDetectUAR =
115 "__asan_option_detect_stack_use_after_return";
116
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000117static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
118static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000119
Kostya Serebryany874dae62012-07-16 16:15:40 +0000120// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
121static const size_t kNumberOfAccessSizes = 5;
122
Yury Gribov55441bb2014-11-21 10:29:50 +0000123static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000124
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000126static cl::opt<bool> ClEnableKasan(
127 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
128 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000129static cl::opt<bool> ClRecover(
130 "asan-recover",
131 cl::desc("Enable recovery mode (continue-after-error)."),
132 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000133
134// This flag may need to be replaced with -f[no-]asan-reads.
135static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000136 cl::desc("instrument read instructions"),
137 cl::Hidden, cl::init(true));
138static cl::opt<bool> ClInstrumentWrites(
139 "asan-instrument-writes", cl::desc("instrument write instructions"),
140 cl::Hidden, cl::init(true));
141static cl::opt<bool> ClInstrumentAtomics(
142 "asan-instrument-atomics",
143 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
144 cl::init(true));
145static cl::opt<bool> ClAlwaysSlowPath(
146 "asan-always-slow-path",
147 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
148 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000149// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000150// in any given BB. Normally, this should be set to unlimited (INT_MAX),
151// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
152// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000153static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
154 "asan-max-ins-per-bb", cl::init(10000),
155 cl::desc("maximal number of instructions to instrument in any given BB"),
156 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000157// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000158static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
159 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000160static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000161 cl::desc("Check return-after-free"),
162 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000163// This flag may need to be replaced with -f[no]asan-globals.
164static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000165 cl::desc("Handle global objects"), cl::Hidden,
166 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000167static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000168 cl::desc("Handle C++ initializer order"),
169 cl::Hidden, cl::init(true));
170static cl::opt<bool> ClInvalidPointerPairs(
171 "asan-detect-invalid-pointer-pair",
172 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
173 cl::init(false));
174static cl::opt<unsigned> ClRealignStack(
175 "asan-realign-stack",
176 cl::desc("Realign stack to the value of this flag (power of two)"),
177 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000178static cl::opt<int> ClInstrumentationWithCallsThreshold(
179 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000180 cl::desc(
181 "If the function being instrumented contains more than "
182 "this number of memory accesses, use callbacks instead of "
183 "inline checks (-1 means never use callbacks)."),
184 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000185static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000186 "asan-memory-access-callback-prefix",
187 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
188 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000189static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000191 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000192static cl::opt<bool> ClSkipPromotableAllocas(
193 "asan-skip-promotable-allocas",
194 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
195 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000196
197// These flags allow to change the shadow mapping.
198// The shadow mapping looks like
199// Shadow = (Mem >> scale) + (1 << offset_log)
200static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000201 cl::desc("scale of asan shadow mapping"),
202 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000203
204// Optimization flags. Not user visible, used mostly for testing
205// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000206static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
207 cl::Hidden, cl::init(true));
208static cl::opt<bool> ClOptSameTemp(
209 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
210 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000211static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000212 cl::desc("Don't instrument scalar globals"),
213 cl::Hidden, cl::init(true));
214static cl::opt<bool> ClOptStack(
215 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
216 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000217
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000218static cl::opt<bool> ClCheckLifetime(
219 "asan-check-lifetime",
220 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
221 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000222
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000223static cl::opt<bool> ClDynamicAllocaStack(
224 "asan-stack-dynamic-alloca",
225 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000226 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000227
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000228static cl::opt<uint32_t> ClForceExperiment(
229 "asan-force-experiment",
230 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
231 cl::init(0));
232
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000233static cl::opt<bool>
234 ClUsePrivateAliasForGlobals("asan-use-private-alias",
235 cl::desc("Use private aliases for global"
236 " variables"),
237 cl::Hidden, cl::init(false));
238
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000239// Debug flags.
240static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
241 cl::init(0));
242static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
243 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000244static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
245 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000246static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
247 cl::Hidden, cl::init(-1));
248static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
249 cl::Hidden, cl::init(-1));
250
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000251STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
252STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000253STATISTIC(NumOptimizedAccessesToGlobalVar,
254 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000255STATISTIC(NumOptimizedAccessesToStackVar,
256 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000257
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000258namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000259/// Frontend-provided metadata for source location.
260struct LocationMetadata {
261 StringRef Filename;
262 int LineNo;
263 int ColumnNo;
264
265 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
266
267 bool empty() const { return Filename.empty(); }
268
269 void parse(MDNode *MDN) {
270 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000271 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
272 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000273 LineNo =
274 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
275 ColumnNo =
276 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000277 }
278};
279
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000280/// Frontend-provided metadata for global variables.
281class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000282 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000283 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000284 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000285 LocationMetadata SourceLoc;
286 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 bool IsDynInit;
288 bool IsBlacklisted;
289 };
290
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000291 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000292
Keno Fischere03fae42015-12-05 14:42:34 +0000293 void reset() {
294 inited_ = false;
295 Entries.clear();
296 }
297
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000298 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000299 assert(!inited_);
300 inited_ = true;
301 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000302 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000303 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000304 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000305 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000306 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000307 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000308 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000309 // We can already have an entry for GV if it was merged with another
310 // global.
311 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000312 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
313 E.SourceLoc.parse(Loc);
314 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
315 E.Name = Name->getString();
316 ConstantInt *IsDynInit =
317 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000318 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000319 ConstantInt *IsBlacklisted =
320 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000321 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000322 }
323 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000324
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000325 /// Returns metadata entry for a given global.
326 Entry get(GlobalVariable *G) const {
327 auto Pos = Entries.find(G);
328 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000329 }
330
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000331 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000332 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000333 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000334};
335
Alexey Samsonov1345d352013-01-16 13:23:28 +0000336/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000337/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000338struct ShadowMapping {
339 int Scale;
340 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000341 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000342};
343
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000344static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
345 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000346 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000347 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000348 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
349 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000350 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
351 TargetTriple.getArch() == llvm::Triple::ppc64le;
Anna Zaks3b50e702016-02-02 22:05:07 +0000352 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000353 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000354 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
355 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000356 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
357 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000358 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000359 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000360
361 ShadowMapping Mapping;
362
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000363 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000364 // Android is always PIE, which means that the beginning of the address
365 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000366 if (IsAndroid)
367 Mapping.Offset = 0;
368 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000369 Mapping.Offset = kMIPS32_ShadowOffset32;
370 else if (IsFreeBSD)
371 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000372 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000373 // If we're targeting iOS and x86, the binary is built for iOS simulator.
374 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000375 else if (IsWindows)
376 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000377 else
378 Mapping.Offset = kDefaultShadowOffset32;
379 } else { // LongSize == 64
380 if (IsPPC64)
381 Mapping.Offset = kPPC64_ShadowOffset64;
382 else if (IsFreeBSD)
383 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000384 else if (IsLinux && IsX86_64) {
385 if (IsKasan)
386 Mapping.Offset = kLinuxKasan_ShadowOffset64;
387 else
388 Mapping.Offset = kSmallX86_64ShadowOffset;
389 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000390 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000391 else if (IsIOS)
392 // If we're targeting iOS and x86, the binary is built for iOS simulator.
393 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000394 else if (IsAArch64)
395 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000396 else
397 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000398 }
399
400 Mapping.Scale = kDefaultShadowScale;
401 if (ClMappingScale) {
402 Mapping.Scale = ClMappingScale;
403 }
404
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000405 // OR-ing shadow offset if more efficient (at least on x86) if the offset
406 // is a power of two, but on ppc64 we have to use add since the shadow
407 // offset is not necessary 1/8-th of the address space.
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000408 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64
409 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000410
Alexey Samsonov1345d352013-01-16 13:23:28 +0000411 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000412}
413
Alexey Samsonov1345d352013-01-16 13:23:28 +0000414static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000415 // Redzone used for stack and globals is at least 32 bytes.
416 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000417 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000418}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000419
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000420/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000421struct AddressSanitizer : public FunctionPass {
Yury Gribovd7731982015-11-11 10:36:49 +0000422 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false)
423 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
424 Recover(Recover || ClRecover) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000425 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
426 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000427 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000428 return "AddressSanitizerFunctionPass";
429 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000430 void getAnalysisUsage(AnalysisUsage &AU) const override {
431 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000432 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000433 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000434 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
435 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000436 uint64_t SizeInBytes =
437 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000438 return SizeInBytes;
439 }
440 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000441 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000442
443 // Check if we have dynamic alloca.
444 bool isDynamicAlloca(AllocaInst &AI) const {
445 return AI.isArrayAllocation() || !AI.isStaticAlloca();
446 }
447
Anna Zaks8ed1d812015-02-27 03:12:36 +0000448 /// If it is an interesting memory access, return the PointerOperand
449 /// and set IsWrite/Alignment. Otherwise return nullptr.
450 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000451 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000452 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000453 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000454 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000455 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
456 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000457 Value *SizeArgument, bool UseCalls, uint32_t Exp);
458 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
459 uint32_t TypeSize, bool IsWrite,
460 Value *SizeArgument, bool UseCalls,
461 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000462 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
463 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000464 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000465 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000466 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000467 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000468 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000469 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000470 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000471 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000472 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000473 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000474 static char ID; // Pass identification, replacement for typeid
475
Yury Gribov3ae427d2014-12-01 08:47:58 +0000476 DominatorTree &getDominatorTree() const { return *DT; }
477
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000478 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000479 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000480
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000481 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000482 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000483 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
484 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000485
Reid Kleckner2f907552015-07-21 17:40:14 +0000486 /// Helper to cleanup per-function state.
487 struct FunctionStateRAII {
488 AddressSanitizer *Pass;
489 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
490 assert(Pass->ProcessedAllocas.empty() &&
491 "last pass forgot to clear cache");
492 }
493 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
494 };
495
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000496 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000497 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000498 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000499 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000500 bool Recover;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000501 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000502 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000503 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000504 Function *AsanCtorFunction = nullptr;
505 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000506 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000507 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000508 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
509 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
510 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
511 // This array is indexed by AccessIsWrite and Experiment.
512 Function *AsanErrorCallbackSized[2][2];
513 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000514 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000515 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000516 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000517 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000518
519 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000520};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000521
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000522class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000523 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000524 explicit AddressSanitizerModule(bool CompileKernel = false,
525 bool Recover = false)
526 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
527 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000528 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000529 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000530 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000531
Kostya Serebryany20a79972012-11-22 03:18:50 +0000532 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000533 void initializeCallbacks(Module &M);
534
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000535 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000536 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000537 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000538 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000539 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000540 return RedzoneSizeForScale(Mapping.Scale);
541 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000542
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000543 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000544 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000545 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000546 Type *IntptrTy;
547 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000548 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000549 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000550 Function *AsanPoisonGlobals;
551 Function *AsanUnpoisonGlobals;
552 Function *AsanRegisterGlobals;
553 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000554};
555
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000556// Stack poisoning does not play well with exception handling.
557// When an exception is thrown, we essentially bypass the code
558// that unpoisones the stack. This is why the run-time library has
559// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
560// stack in the interceptor. This however does not work inside the
561// actual function which catches the exception. Most likely because the
562// compiler hoists the load of the shadow value somewhere too high.
563// This causes asan to report a non-existing bug on 453.povray.
564// It sounds like an LLVM bug.
565struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
566 Function &F;
567 AddressSanitizer &ASan;
568 DIBuilder DIB;
569 LLVMContext *C;
570 Type *IntptrTy;
571 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000572 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000573
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000574 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000575 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000576 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000577 unsigned StackAlignment;
578
Kostya Serebryany6805de52013-09-10 13:16:56 +0000579 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000580 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000581 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000582 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000583
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000584 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
585 struct AllocaPoisonCall {
586 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000587 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000588 uint64_t Size;
589 bool DoPoison;
590 };
591 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
592
Yury Gribov98b18592015-05-28 07:51:49 +0000593 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
594 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
595 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000596 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000597
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000598 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000599 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000600 AllocaForValueMapTy AllocaForValue;
601
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000602 bool HasNonEmptyInlineAsm = false;
603 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000604 std::unique_ptr<CallInst> EmptyInlineAsm;
605
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000606 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000607 : F(F),
608 ASan(ASan),
609 DIB(*F.getParent(), /*AllowUnresolved*/ false),
610 C(ASan.C),
611 IntptrTy(ASan.IntptrTy),
612 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
613 Mapping(ASan.Mapping),
614 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000615 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000616
617 bool runOnFunction() {
618 if (!ClStack) return false;
619 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000620 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000621
Yury Gribov55441bb2014-11-21 10:29:50 +0000622 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000623
624 initializeCallbacks(*F.getParent());
625
626 poisonStack();
627
628 if (ClDebugStack) {
629 DEBUG(dbgs() << F);
630 }
631 return true;
632 }
633
Yury Gribov55441bb2014-11-21 10:29:50 +0000634 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000635 // poisoned red zones around all of them.
636 // Then unpoison everything back before the function returns.
637 void poisonStack();
638
Yury Gribov98b18592015-05-28 07:51:49 +0000639 void createDynamicAllocasInitStorage();
640
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000641 // ----------------------- Visitors.
642 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000643 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000644
Yury Gribov98b18592015-05-28 07:51:49 +0000645 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
646 Value *SavedStack) {
647 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000648 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
649 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
650 // need to adjust extracted SP to compute the address of the most recent
651 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
652 // this purpose.
653 if (!isa<ReturnInst>(InstBefore)) {
654 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
655 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
656 {IntptrTy});
657
658 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
659
660 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
661 DynamicAreaOffset);
662 }
663
Yury Gribov781bce22015-05-28 08:03:28 +0000664 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000665 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000666 }
667
Yury Gribov55441bb2014-11-21 10:29:50 +0000668 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000669 void unpoisonDynamicAllocas() {
670 for (auto &Ret : RetVec)
671 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000672
Yury Gribov98b18592015-05-28 07:51:49 +0000673 for (auto &StackRestoreInst : StackRestoreVec)
674 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
675 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000676 }
677
Yury Gribov55441bb2014-11-21 10:29:50 +0000678 // Deploy and poison redzones around dynamic alloca call. To do this, we
679 // should replace this call with another one with changed parameters and
680 // replace all its uses with new address, so
681 // addr = alloca type, old_size, align
682 // is replaced by
683 // new_size = (old_size + additional_size) * sizeof(type)
684 // tmp = alloca i8, new_size, max(align, 32)
685 // addr = tmp + 32 (first 32 bytes are for the left redzone).
686 // Additional_size is added to make new memory allocation contain not only
687 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000688 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000689
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000690 /// \brief Collect Alloca instructions we want (and can) handle.
691 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000692 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000693 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000694 return;
695 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000696
697 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000698 if (ASan.isDynamicAlloca(AI))
699 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000700 else
701 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000702 }
703
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000704 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
705 /// errors.
706 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000707 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000708 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000709 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Yury Gribov98b18592015-05-28 07:51:49 +0000710 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000711 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000712 return;
713 // Found lifetime intrinsic, add ASan instrumentation if necessary.
714 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
715 // If size argument is undefined, don't do anything.
716 if (Size->isMinusOne()) return;
717 // Check that size doesn't saturate uint64_t and can
718 // be stored in IntptrTy.
719 const uint64_t SizeValue = Size->getValue().getLimitedValue();
720 if (SizeValue == ~0ULL ||
721 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
722 return;
723 // Find alloca instruction that corresponds to llvm.lifetime argument.
724 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
725 if (!AI) return;
726 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000727 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000728 AllocaPoisonCallVec.push_back(APC);
729 }
730
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000731 void visitCallSite(CallSite CS) {
732 Instruction *I = CS.getInstruction();
733 if (CallInst *CI = dyn_cast<CallInst>(I)) {
734 HasNonEmptyInlineAsm |=
735 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
736 HasReturnsTwiceCall |= CI->canReturnTwice();
737 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000738 }
739
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000740 // ---------------------- Helpers.
741 void initializeCallbacks(Module &M);
742
Yury Gribov3ae427d2014-12-01 08:47:58 +0000743 bool doesDominateAllExits(const Instruction *I) const {
744 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000745 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000746 }
747 return true;
748 }
749
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000750 /// Finds alloca where the value comes from.
751 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000752 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000753 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000754 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000755
756 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
757 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000758 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
759 bool Dynamic);
760 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
761 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000762};
763
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000764} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000765
766char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000767INITIALIZE_PASS_BEGIN(
768 AddressSanitizer, "asan",
769 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
770 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000771INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000772INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000773INITIALIZE_PASS_END(
774 AddressSanitizer, "asan",
775 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
776 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000777FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
778 bool Recover) {
779 assert(!CompileKernel || Recover);
780 return new AddressSanitizer(CompileKernel, Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000781}
782
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000783char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000784INITIALIZE_PASS(
785 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000786 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000787 "ModulePass",
788 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000789ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
790 bool Recover) {
791 assert(!CompileKernel || Recover);
792 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000793}
794
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000795static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000796 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000797 assert(Res < kNumberOfAccessSizes);
798 return Res;
799}
800
Bill Wendling58f8cef2013-08-06 22:52:42 +0000801// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000802static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
803 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000804 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000805 // We use private linkage for module-local strings. If they can be merged
806 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000807 GlobalVariable *GV =
808 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000809 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000810 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000811 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
812 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000813}
814
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000815/// \brief Create a global describing a source location.
816static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
817 LocationMetadata MD) {
818 Constant *LocData[] = {
819 createPrivateGlobalForString(M, MD.Filename, true),
820 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
821 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
822 };
823 auto LocStruct = ConstantStruct::getAnon(LocData);
824 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
825 GlobalValue::PrivateLinkage, LocStruct,
826 kAsanGenPrefix);
827 GV->setUnnamedAddr(true);
828 return GV;
829}
830
Kostya Serebryany139a9372012-11-20 14:16:08 +0000831static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000832 return G->getName().find(kAsanGenPrefix) == 0 ||
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000833 G->getName().find(kSanCovGenPrefix) == 0 ||
834 G->getName().find(kODRGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000835}
836
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000837Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
838 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000839 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000840 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000841 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000842 if (Mapping.OrShadowOffset)
843 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
844 else
845 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000846}
847
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000848// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000849void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
850 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000851 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000852 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000853 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000854 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
855 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
856 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000857 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000858 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000859 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000860 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
861 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
862 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000863 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000864 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000865}
866
Anna Zaks8ed1d812015-02-27 03:12:36 +0000867/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000868bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
869 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
870
871 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
872 return PreviouslySeenAllocaInfo->getSecond();
873
Yury Gribov98b18592015-05-28 07:51:49 +0000874 bool IsInteresting =
875 (AI.getAllocatedType()->isSized() &&
876 // alloca() may be called with 0 size, ignore it.
877 getAllocaSizeInBytes(&AI) > 0 &&
878 // We are only interested in allocas not promotable to registers.
879 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000880 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
881 // inalloca allocas are not treated as static, and we don't want
882 // dynamic alloca instrumentation for them as well.
883 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000884
885 ProcessedAllocas[&AI] = IsInteresting;
886 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000887}
888
889/// If I is an interesting memory access, return the PointerOperand
890/// and set IsWrite/Alignment. Otherwise return nullptr.
891Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
892 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000893 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000894 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000895 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000896 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000897
898 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000899 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000900 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000901 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000902 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000903 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000904 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000905 PtrOperand = LI->getPointerOperand();
906 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000907 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000908 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000909 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000910 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000911 PtrOperand = SI->getPointerOperand();
912 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000913 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000914 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000915 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000916 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000917 PtrOperand = RMW->getPointerOperand();
918 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000919 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000920 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000921 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000922 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000923 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000924 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000925
926 // Treat memory accesses to promotable allocas as non-interesting since they
927 // will not cause memory violations. This greatly speeds up the instrumented
928 // executable at -O0.
929 if (ClSkipPromotableAllocas)
930 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
931 return isInterestingAlloca(*AI) ? AI : nullptr;
932
933 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000934}
935
Kostya Serebryany796f6552014-02-27 12:45:36 +0000936static bool isPointerOperand(Value *V) {
937 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
938}
939
940// This is a rough heuristic; it may cause both false positives and
941// false negatives. The proper implementation requires cooperation with
942// the frontend.
943static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
944 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000945 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000946 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000947 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000948 } else {
949 return false;
950 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000951 return isPointerOperand(I->getOperand(0)) &&
952 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000953}
954
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000955bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
956 // If a global variable does not have dynamic initialization we don't
957 // have to instrument it. However, if a global does not have initializer
958 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000959 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000960}
961
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000962void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
963 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000964 IRBuilder<> IRB(I);
965 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
966 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
967 for (int i = 0; i < 2; i++) {
968 if (Param[i]->getType()->isPointerTy())
969 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
970 }
David Blaikieff6409d2015-05-18 22:13:54 +0000971 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000972}
973
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000974void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000975 Instruction *I, bool UseCalls,
976 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000977 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000978 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000979 uint64_t TypeSize = 0;
980 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000981 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000982
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000983 // Optimization experiments.
984 // The experiments can be used to evaluate potential optimizations that remove
985 // instrumentation (assess false negatives). Instead of completely removing
986 // some instrumentation, you set Exp to a non-zero value (mask of optimization
987 // experiments that want to remove instrumentation of this instruction).
988 // If Exp is non-zero, this pass will emit special calls into runtime
989 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
990 // make runtime terminate the program in a special way (with a different
991 // exit status). Then you run the new compiler on a buggy corpus, collect
992 // the special terminations (ideally, you don't see them at all -- no false
993 // negatives) and make the decision on the optimization.
994 uint32_t Exp = ClForceExperiment;
995
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000996 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000997 // If initialization order checking is disabled, a simple access to a
998 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000999 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001000 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001001 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1002 NumOptimizedAccessesToGlobalVar++;
1003 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001004 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001005 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001006
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001007 if (ClOpt && ClOptStack) {
1008 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001009 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001010 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1011 NumOptimizedAccessesToStackVar++;
1012 return;
1013 }
1014 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001015
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001016 if (IsWrite)
1017 NumInstrumentedWrites++;
1018 else
1019 NumInstrumentedReads++;
1020
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001021 unsigned Granularity = 1 << Mapping.Scale;
1022 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1023 // if the data is properly aligned.
1024 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1025 TypeSize == 128) &&
1026 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001027 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1028 Exp);
1029 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1030 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001031}
1032
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001033Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1034 Value *Addr, bool IsWrite,
1035 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001036 Value *SizeArgument,
1037 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001038 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001039 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1040 CallInst *Call = nullptr;
1041 if (SizeArgument) {
1042 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001043 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1044 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001045 else
David Blaikieff6409d2015-05-18 22:13:54 +00001046 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1047 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001048 } else {
1049 if (Exp == 0)
1050 Call =
1051 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1052 else
David Blaikieff6409d2015-05-18 22:13:54 +00001053 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1054 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001055 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001056
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001057 // We don't do Call->setDoesNotReturn() because the BB already has
1058 // UnreachableInst at the end.
1059 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001060 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001061 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001062}
1063
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001064Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001065 Value *ShadowValue,
1066 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +00001067 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001068 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001069 Value *LastAccessedByte =
1070 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001071 // (Addr & (Granularity - 1)) + size - 1
1072 if (TypeSize / 8 > 1)
1073 LastAccessedByte = IRB.CreateAdd(
1074 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1075 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001076 LastAccessedByte =
1077 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001078 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1079 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1080}
1081
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001082void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001083 Instruction *InsertBefore, Value *Addr,
1084 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001085 Value *SizeArgument, bool UseCalls,
1086 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001087 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001088 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001089 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1090
1091 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001092 if (Exp == 0)
1093 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1094 AddrLong);
1095 else
David Blaikieff6409d2015-05-18 22:13:54 +00001096 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1097 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001098 return;
1099 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001100
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001101 Type *ShadowTy =
1102 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001103 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1104 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1105 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001106 Value *ShadowValue =
1107 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001108
1109 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001110 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001111 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001112
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001113 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001114 // We use branch weights for the slow path check, to indicate that the slow
1115 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001116 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1117 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001118 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001119 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001120 IRB.SetInsertPoint(CheckTerm);
1121 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001122 if (Recover) {
1123 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1124 } else {
1125 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001126 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001127 CrashTerm = new UnreachableInst(*C, CrashBlock);
1128 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1129 ReplaceInstWithInst(CheckTerm, NewTerm);
1130 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001131 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001132 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001133 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001134
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001135 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001136 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001137 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001138}
1139
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001140// Instrument unusual size or unusual alignment.
1141// We can not do it with a single check, so we do 1-byte check for the first
1142// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1143// to report the actual access size.
1144void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1145 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1146 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1147 IRBuilder<> IRB(I);
1148 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1149 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1150 if (UseCalls) {
1151 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001152 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1153 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001154 else
David Blaikieff6409d2015-05-18 22:13:54 +00001155 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1156 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001157 } else {
1158 Value *LastByte = IRB.CreateIntToPtr(
1159 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1160 Addr->getType());
1161 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1162 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1163 }
1164}
1165
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001166void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1167 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001168 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001169 IRBuilder<> IRB(&GlobalInit.front(),
1170 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001171
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001172 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001173 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1174 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001175
1176 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001177 for (auto &BB : GlobalInit.getBasicBlockList())
1178 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001179 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001180}
1181
1182void AddressSanitizerModule::createInitializerPoisonCalls(
1183 Module &M, GlobalValue *ModuleName) {
1184 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1185
1186 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1187 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001188 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001189 ConstantStruct *CS = cast<ConstantStruct>(OP);
1190
1191 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001192 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001193 if (F->getName() == kAsanModuleCtorName) continue;
1194 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1195 // Don't instrument CTORs that will run before asan.module_ctor.
1196 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1197 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001198 }
1199 }
1200}
1201
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001202bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001203 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001204 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001205
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001206 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001207 if (!Ty->isSized()) return false;
1208 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001209 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001210 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001211 // Don't handle ODR linkage types and COMDATs since other modules may be built
1212 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001213 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1214 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1215 G->getLinkage() != GlobalVariable::InternalLinkage)
1216 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001217 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001218 // Two problems with thread-locals:
1219 // - The address of the main thread's copy can't be computed at link-time.
1220 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001221 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001222 // For now, just ignore this Global if the alignment is large.
1223 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001224
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001225 if (G->hasSection()) {
1226 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001227
Anna Zaks11904602015-06-09 00:58:08 +00001228 // Globals from llvm.metadata aren't emitted, do not instrument them.
1229 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001230 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001231 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001232
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001233 // Do not instrument function pointers to initialization and termination
1234 // routines: dynamic linker will not properly handle redzones.
1235 if (Section.startswith(".preinit_array") ||
1236 Section.startswith(".init_array") ||
1237 Section.startswith(".fini_array")) {
1238 return false;
1239 }
1240
Anna Zaks11904602015-06-09 00:58:08 +00001241 // Callbacks put into the CRT initializer/terminator sections
1242 // should not be instrumented.
1243 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1244 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1245 if (Section.startswith(".CRT")) {
1246 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1247 return false;
1248 }
1249
Kuba Brecka1001bb52014-12-05 22:19:18 +00001250 if (TargetTriple.isOSBinFormatMachO()) {
1251 StringRef ParsedSegment, ParsedSection;
1252 unsigned TAA = 0, StubSize = 0;
1253 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001254 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1255 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001256 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001257
1258 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1259 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1260 // them.
1261 if (ParsedSegment == "__OBJC" ||
1262 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1263 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1264 return false;
1265 }
1266 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1267 // Constant CFString instances are compiled in the following way:
1268 // -- the string buffer is emitted into
1269 // __TEXT,__cstring,cstring_literals
1270 // -- the constant NSConstantString structure referencing that buffer
1271 // is placed into __DATA,__cfstring
1272 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1273 // Moreover, it causes the linker to crash on OS X 10.7
1274 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1275 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1276 return false;
1277 }
1278 // The linker merges the contents of cstring_literals and removes the
1279 // trailing zeroes.
1280 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1281 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1282 return false;
1283 }
1284 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001285 }
1286
1287 return true;
1288}
1289
Alexey Samsonov788381b2012-12-25 12:28:20 +00001290void AddressSanitizerModule::initializeCallbacks(Module &M) {
1291 IRBuilder<> IRB(*C);
1292 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001293 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001294 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001295 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001296 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001297 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001298 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1299 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001300 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001301 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001302 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001303 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001304 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1305 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001306 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1307}
1308
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001309// This function replaces all global variables with new variables that have
1310// trailing redzones. It also creates a function that poisons
1311// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001312bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001313 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001314
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001315 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1316
Alexey Samsonova02e6642014-05-29 18:40:48 +00001317 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001318 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001319 }
1320
1321 size_t n = GlobalsToChange.size();
1322 if (n == 0) return false;
1323
1324 // A global is described by a structure
1325 // size_t beg;
1326 // size_t size;
1327 // size_t size_with_redzone;
1328 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001329 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001330 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001331 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001332 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001333 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001334 StructType *GlobalStructTy =
1335 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001336 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001337 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001338
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001339 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001340
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001341 // We shouldn't merge same module names, as this string serves as unique
1342 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001343 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001344 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001345
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001346 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001347 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001348 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001349 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001350
1351 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001352 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001353 // Create string holding the global name (use global name from metadata
1354 // if it's available, otherwise just write the name of global variable).
1355 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001356 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001357 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001358
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001359 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001360 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001361 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001362 // MinRZ <= RZ <= kMaxGlobalRedzone
1363 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001364 uint64_t RZ = std::max(
1365 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001366 uint64_t RightRedzoneSize = RZ;
1367 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001368 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001369 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001370 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1371
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001372 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001373 Constant *NewInitializer =
1374 ConstantStruct::get(NewTy, G->getInitializer(),
1375 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001376
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001377 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001378 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1379 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1380 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001381 GlobalVariable *NewGlobal =
1382 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1383 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001384 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001385 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001386
1387 Value *Indices2[2];
1388 Indices2[0] = IRB.getInt32(0);
1389 Indices2[1] = IRB.getInt32(0);
1390
1391 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001392 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001393 NewGlobal->takeName(G);
1394 G->eraseFromParent();
1395
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001396 Constant *SourceLoc;
1397 if (!MD.SourceLoc.empty()) {
1398 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1399 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1400 } else {
1401 SourceLoc = ConstantInt::get(IntptrTy, 0);
1402 }
1403
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001404 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1405 GlobalValue *InstrumentedGlobal = NewGlobal;
1406
1407 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1408 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1409 // Create local alias for NewGlobal to avoid crash on ODR between
1410 // instrumented and non-instrumented libraries.
1411 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1412 NameForGlobal + M.getName(), NewGlobal);
1413
1414 // With local aliases, we need to provide another externally visible
1415 // symbol __odr_asan_XXX to detect ODR violation.
1416 auto *ODRIndicatorSym =
1417 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1418 Constant::getNullValue(IRB.getInt8Ty()),
1419 kODRGenPrefix + NameForGlobal, nullptr,
1420 NewGlobal->getThreadLocalMode());
1421
1422 // Set meaningful attributes for indicator symbol.
1423 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1424 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1425 ODRIndicatorSym->setAlignment(1);
1426 ODRIndicator = ODRIndicatorSym;
1427 InstrumentedGlobal = GA;
1428 }
1429
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001430 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001431 GlobalStructTy,
1432 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001433 ConstantInt::get(IntptrTy, SizeInBytes),
1434 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1435 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001436 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001437 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1438 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001439
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001440 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001441
Kostya Serebryany20343352012-10-17 13:40:06 +00001442 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001443 }
1444
1445 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1446 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001447 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001448 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1449
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001450 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001451 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001452 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001453 IRB.CreateCall(AsanRegisterGlobals,
1454 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1455 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001456
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001457 // We also need to unregister globals at the end, e.g. when a shared library
1458 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001459 Function *AsanDtorFunction =
1460 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1461 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001462 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1463 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001464 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1465 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1466 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001467 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001468
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469 DEBUG(dbgs() << M);
1470 return true;
1471}
1472
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001473bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001474 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001475 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001476 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001477 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001478 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001479 initializeCallbacks(M);
1480
1481 bool Changed = false;
1482
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001483 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1484 if (ClGlobals && !CompileKernel) {
1485 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1486 assert(CtorFunc);
1487 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1488 Changed |= InstrumentGlobals(IRB, M);
1489 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001490
1491 return Changed;
1492}
1493
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001494void AddressSanitizer::initializeCallbacks(Module &M) {
1495 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001496 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001497 // IsWrite, TypeSize and Exp are encoded in the function name.
1498 for (int Exp = 0; Exp < 2; Exp++) {
1499 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1500 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1501 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001502 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001503 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001504 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001505 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001506 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001507 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001508 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1509 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001510 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001511 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001512 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1513 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1514 AccessSizeIndex++) {
1515 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1516 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001517 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001518 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001519 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001520 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001521 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001522 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1523 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001524 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001525 }
1526 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001527
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001528 const std::string MemIntrinCallbackPrefix =
1529 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001530 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001531 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001532 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001533 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001534 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001535 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001536 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001537 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001538 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001539
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001540 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001541 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001542
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001543 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001544 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001545 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001546 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001547 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1548 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1549 StringRef(""), StringRef(""),
1550 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001551}
1552
1553// virtual
1554bool AddressSanitizer::doInitialization(Module &M) {
1555 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001556
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001557 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001558
1559 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001560 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001561 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001562 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001563
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001564 if (!CompileKernel) {
1565 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001566 createSanitizerCtorAndInitFunctions(
1567 M, kAsanModuleCtorName, kAsanInitName,
1568 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001569 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1570 }
1571 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001572 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001573}
1574
Keno Fischere03fae42015-12-05 14:42:34 +00001575bool AddressSanitizer::doFinalization(Module &M) {
1576 GlobalsMD.reset();
1577 return false;
1578}
1579
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001580bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1581 // For each NSObject descendant having a +load method, this method is invoked
1582 // by the ObjC runtime before any of the static constructors is called.
1583 // Therefore we need to instrument such methods with a call to __asan_init
1584 // at the beginning in order to initialize our runtime before any access to
1585 // the shadow memory.
1586 // We cannot just ignore these methods, because they may call other
1587 // instrumented functions.
1588 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001589 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001590 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001591 return true;
1592 }
1593 return false;
1594}
1595
Reid Kleckner2f907552015-07-21 17:40:14 +00001596void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1597 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1598 // to it as uninteresting. This assumes we haven't started processing allocas
1599 // yet. This check is done up front because iterating the use list in
1600 // isInterestingAlloca would be algorithmically slower.
1601 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1602
1603 // Try to get the declaration of llvm.localescape. If it's not in the module,
1604 // we can exit early.
1605 if (!F.getParent()->getFunction("llvm.localescape")) return;
1606
1607 // Look for a call to llvm.localescape call in the entry block. It can't be in
1608 // any other block.
1609 for (Instruction &I : F.getEntryBlock()) {
1610 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1611 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1612 // We found a call. Mark all the allocas passed in as uninteresting.
1613 for (Value *Arg : II->arg_operands()) {
1614 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1615 assert(AI && AI->isStaticAlloca() &&
1616 "non-static alloca arg to localescape");
1617 ProcessedAllocas[AI] = false;
1618 }
1619 break;
1620 }
1621 }
1622}
1623
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001624bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001625 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001626 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001627 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001628 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001629
Yury Gribov3ae427d2014-12-01 08:47:58 +00001630 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1631
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001632 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001633 maybeInsertAsanInitAtFunctionEntry(F);
1634
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001635 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001636
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001637 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001638
Reid Kleckner2f907552015-07-21 17:40:14 +00001639 FunctionStateRAII CleanupObj(this);
1640
1641 // We can't instrument allocas used with llvm.localescape. Only static allocas
1642 // can be passed to that intrinsic.
1643 markEscapedLocalAllocas(F);
1644
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001645 // We want to instrument every address only once per basic block (unless there
1646 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001647 SmallSet<Value *, 16> TempsToInstrument;
1648 SmallVector<Instruction *, 16> ToInstrument;
1649 SmallVector<Instruction *, 8> NoReturnCalls;
1650 SmallVector<BasicBlock *, 16> AllBlocks;
1651 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001652 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001653 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001654 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001655 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001656
1657 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001658 for (auto &BB : F) {
1659 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001660 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001661 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001662 for (auto &Inst : BB) {
1663 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001664 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1665 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001666 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001667 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001668 continue; // We've seen this temp in the current BB.
1669 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001670 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001671 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1672 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001673 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001674 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001675 // ok, take it.
1676 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001677 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001678 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001679 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001680 // A call inside BB.
1681 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001682 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001683 }
1684 continue;
1685 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001686 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001687 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001688 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001689 }
1690 }
1691
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001692 bool UseCalls =
1693 CompileKernel ||
1694 (ClInstrumentationWithCallsThreshold >= 0 &&
1695 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001696 const TargetLibraryInfo *TLI =
1697 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001698 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001699 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1700 /*RoundToAlign=*/true);
1701
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001702 // Instrument.
1703 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001704 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001705 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1706 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001707 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001708 instrumentMop(ObjSizeVis, Inst, UseCalls,
1709 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001710 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001711 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001712 }
1713 NumInstrumented++;
1714 }
1715
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001716 FunctionStackPoisoner FSP(F, *this);
1717 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001718
1719 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1720 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001721 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001722 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001723 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001724 }
1725
Alexey Samsonova02e6642014-05-29 18:40:48 +00001726 for (auto Inst : PointerComparisonsOrSubtracts) {
1727 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001728 NumInstrumented++;
1729 }
1730
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001731 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001732
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001733 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1734
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001735 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001736}
1737
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001738// Workaround for bug 11395: we don't want to instrument stack in functions
1739// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1740// FIXME: remove once the bug 11395 is fixed.
1741bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1742 if (LongSize != 32) return false;
1743 CallInst *CI = dyn_cast<CallInst>(I);
1744 if (!CI || !CI->isInlineAsm()) return false;
1745 if (CI->getNumArgOperands() <= 5) return false;
1746 // We have inline assembly with quite a few arguments.
1747 return true;
1748}
1749
1750void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1751 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001752 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1753 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001754 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1755 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1756 IntptrTy, nullptr));
1757 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001758 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1759 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001760 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001761 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001762 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1763 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001764 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001765 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1766 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001767 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1768 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1769 AsanAllocasUnpoisonFunc =
1770 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1771 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001772}
1773
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001774void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1775 IRBuilder<> &IRB, Value *ShadowBase,
1776 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001777 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001778 size_t i = 0;
1779 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1780 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1781 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1782 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1783 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1784 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1785 uint64_t Val = 0;
1786 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001787 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001788 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1789 else
1790 Val = (Val << 8) | ShadowBytes[i + j];
1791 }
1792 if (!Val) continue;
1793 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1794 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1795 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1796 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001797 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001798 }
1799}
1800
Kostya Serebryany6805de52013-09-10 13:16:56 +00001801// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1802// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1803static int StackMallocSizeClass(uint64_t LocalStackSize) {
1804 assert(LocalStackSize <= kMaxStackMallocSize);
1805 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001806 for (int i = 0;; i++, MaxSize *= 2)
1807 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001808 llvm_unreachable("impossible LocalStackSize");
1809}
1810
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001811// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1812// We can not use MemSet intrinsic because it may end up calling the actual
1813// memset. Size is a multiple of 8.
1814// Currently this generates 8-byte stores on x86_64; it may be better to
1815// generate wider stores.
1816void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1817 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1818 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001819
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001820 // kAsanStackAfterReturnMagic is 0xf5.
1821 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001822
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001823 for (int i = 0; i < Size; i += 8) {
1824 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001825 IRB.CreateStore(
1826 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1827 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001828 }
1829}
1830
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001831PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1832 Value *ValueIfTrue,
1833 Instruction *ThenTerm,
1834 Value *ValueIfFalse) {
1835 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1836 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1837 PHI->addIncoming(ValueIfFalse, CondBlock);
1838 BasicBlock *ThenBlock = ThenTerm->getParent();
1839 PHI->addIncoming(ValueIfTrue, ThenBlock);
1840 return PHI;
1841}
1842
1843Value *FunctionStackPoisoner::createAllocaForLayout(
1844 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1845 AllocaInst *Alloca;
1846 if (Dynamic) {
1847 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1848 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1849 "MyAlloca");
1850 } else {
1851 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1852 nullptr, "MyAlloca");
1853 assert(Alloca->isStaticAlloca());
1854 }
1855 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1856 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1857 Alloca->setAlignment(FrameAlignment);
1858 return IRB.CreatePointerCast(Alloca, IntptrTy);
1859}
1860
Yury Gribov98b18592015-05-28 07:51:49 +00001861void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1862 BasicBlock &FirstBB = *F.begin();
1863 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1864 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1865 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1866 DynamicAllocaLayout->setAlignment(32);
1867}
1868
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001869void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001870 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1871
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001872 // Insert poison calls for lifetime intrinsics for alloca.
1873 bool HavePoisonedAllocas = false;
1874 for (const auto &APC : AllocaPoisonCallVec) {
1875 assert(APC.InsBefore);
1876 assert(APC.AI);
1877 IRBuilder<> IRB(APC.InsBefore);
1878 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1879 HavePoisonedAllocas |= APC.DoPoison;
1880 }
1881
Yury Gribov98b18592015-05-28 07:51:49 +00001882 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001883 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001884 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001885 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001886
1887 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001888 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001889
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001890 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001891
Kostya Serebryany6805de52013-09-10 13:16:56 +00001892 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001893 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00001894 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001895 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001896
1897 Instruction *InsBefore = AllocaVec[0];
1898 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001899 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001900
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001901 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1902 // debug info is broken, because only entry-block allocas are treated as
1903 // regular stack slots.
1904 auto InsBeforeB = InsBefore->getParent();
1905 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001906 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
1907 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001908 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
1909 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00001910
Reid Kleckner2f907552015-07-21 17:40:14 +00001911 // If we have a call to llvm.localescape, keep it in the entry block.
1912 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
1913
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001914 SmallVector<ASanStackVariableDescription, 16> SVD;
1915 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001916 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001917 ASanStackVariableDescription D = {AI->getName().data(),
1918 ASan.getAllocaSizeInBytes(AI),
1919 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001920 SVD.push_back(D);
1921 }
1922 // Minimal header size (left redzone) is 4 pointers,
1923 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1924 size_t MinHeaderSize = ASan.LongSize / 2;
1925 ASanStackFrameLayout L;
1926 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1927 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1928 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001929 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1930 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00001931 bool DoDynamicAlloca = ClDynamicAllocaStack;
1932 // Don't do dynamic alloca or stack malloc if:
1933 // 1) There is inline asm: too often it makes assumptions on which registers
1934 // are available.
1935 // 2) There is a returns_twice call (typically setjmp), which is
1936 // optimization-hostile, and doesn't play well with introduced indirect
1937 // register-relative calculation of local variable addresses.
1938 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
1939 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001940
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001941 Value *StaticAlloca =
1942 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1943
1944 Value *FakeStack;
1945 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001946
1947 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001948 // void *FakeStack = __asan_option_detect_stack_use_after_return
1949 // ? __asan_stack_malloc_N(LocalStackSize)
1950 // : nullptr;
1951 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001952 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1953 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001954 Value *UARIsEnabled =
1955 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1956 Constant::getNullValue(IRB.getInt32Ty()));
1957 Instruction *Term =
1958 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001959 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001960 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001961 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1962 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1963 Value *FakeStackValue =
1964 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1965 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001966 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001967 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001968 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1969 ConstantInt::get(IntptrTy, 0));
1970
1971 Value *NoFakeStack =
1972 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1973 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1974 IRBIf.SetInsertPoint(Term);
1975 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1976 Value *AllocaValue =
1977 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1978 IRB.SetInsertPoint(InsBefore);
1979 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1980 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1981 } else {
1982 // void *FakeStack = nullptr;
1983 // void *LocalStackBase = alloca(LocalStackSize);
1984 FakeStack = ConstantInt::get(IntptrTy, 0);
1985 LocalStackBase =
1986 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001987 }
1988
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001989 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001990 for (const auto &Desc : SVD) {
1991 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001992 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001993 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001994 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001995 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001996 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001997 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001998
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001999 // The left-most redzone has enough space for at least 4 pointers.
2000 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002001 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2002 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2003 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002004 // Write the frame description constant to redzone[1].
2005 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002006 IRB.CreateAdd(LocalStackBase,
2007 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2008 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002009 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002010 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002011 /*AllowMerging*/ true);
2012 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002013 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002014 // Write the PC to redzone[2].
2015 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002016 IRB.CreateAdd(LocalStackBase,
2017 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2018 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002019 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002020
2021 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002022 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002023 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002024
Kostya Serebryany530e2072013-12-23 14:15:08 +00002025 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002026 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002027 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002028 // Mark the current frame as retired.
2029 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2030 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002031 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002032 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002033 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002034 // // In use-after-return mode, poison the whole stack frame.
2035 // if StackMallocIdx <= 4
2036 // // For small sizes inline the whole thing:
2037 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002038 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002039 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002040 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002041 // else
2042 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002043 Value *Cmp =
2044 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002045 TerminatorInst *ThenTerm, *ElseTerm;
2046 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2047
2048 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002049 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002050 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2051 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2052 ClassSize >> Mapping.Scale);
2053 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002054 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002055 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2056 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2057 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2058 IRBPoison.CreateStore(
2059 Constant::getNullValue(IRBPoison.getInt8Ty()),
2060 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2061 } else {
2062 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002063 IRBPoison.CreateCall(
2064 AsanStackFreeFunc[StackMallocIdx],
2065 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002066 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002067
2068 IRBuilder<> IRBElse(ElseTerm);
2069 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002070 } else if (HavePoisonedAllocas) {
2071 // If we poisoned some allocas in llvm.lifetime analysis,
2072 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002073 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002074 } else {
2075 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002076 }
2077 }
2078
Kostya Serebryany09959942012-10-19 06:20:53 +00002079 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002080 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002081}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002082
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002083void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002084 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002085 // For now just insert the call to ASan runtime.
2086 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2087 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002088 IRB.CreateCall(
2089 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2090 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002091}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002092
2093// Handling llvm.lifetime intrinsics for a given %alloca:
2094// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2095// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2096// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2097// could be poisoned by previous llvm.lifetime.end instruction, as the
2098// variable may go in and out of scope several times, e.g. in loops).
2099// (3) if we poisoned at least one %alloca in a function,
2100// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002101
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002102AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2103 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2104 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002105 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002106 // See if we've already calculated (or started to calculate) alloca for a
2107 // given value.
2108 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002109 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002110 // Store 0 while we're calculating alloca for value V to avoid
2111 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002112 AllocaForValue[V] = nullptr;
2113 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002114 if (CastInst *CI = dyn_cast<CastInst>(V))
2115 Res = findAllocaForValue(CI->getOperand(0));
2116 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002117 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002118 // Allow self-referencing phi-nodes.
2119 if (IncValue == PN) continue;
2120 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2121 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002122 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2123 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002124 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002125 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002126 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002127 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002128 return Res;
2129}
Yury Gribov55441bb2014-11-21 10:29:50 +00002130
Yury Gribov98b18592015-05-28 07:51:49 +00002131void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002132 IRBuilder<> IRB(AI);
2133
Yury Gribov55441bb2014-11-21 10:29:50 +00002134 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2135 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2136
2137 Value *Zero = Constant::getNullValue(IntptrTy);
2138 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2139 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002140
2141 // Since we need to extend alloca with additional memory to locate
2142 // redzones, and OldSize is number of allocated blocks with
2143 // ElementSize size, get allocated memory size in bytes by
2144 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002145 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002146 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002147 Value *OldSize =
2148 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2149 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002150
2151 // PartialSize = OldSize % 32
2152 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2153
2154 // Misalign = kAllocaRzSize - PartialSize;
2155 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2156
2157 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2158 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2159 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2160
2161 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2162 // Align is added to locate left redzone, PartialPadding for possible
2163 // partial redzone and kAllocaRzSize for right redzone respectively.
2164 Value *AdditionalChunkSize = IRB.CreateAdd(
2165 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2166
2167 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2168
2169 // Insert new alloca with new NewSize and Align params.
2170 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2171 NewAlloca->setAlignment(Align);
2172
2173 // NewAddress = Address + Align
2174 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2175 ConstantInt::get(IntptrTy, Align));
2176
Yury Gribov98b18592015-05-28 07:51:49 +00002177 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002178 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002179
2180 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2181 // for unpoisoning stuff.
2182 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2183
Yury Gribov55441bb2014-11-21 10:29:50 +00002184 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2185
Yury Gribov98b18592015-05-28 07:51:49 +00002186 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002187 AI->replaceAllUsesWith(NewAddressPtr);
2188
Yury Gribov98b18592015-05-28 07:51:49 +00002189 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002190 AI->eraseFromParent();
2191}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002192
2193// isSafeAccess returns true if Addr is always inbounds with respect to its
2194// base object. For example, it is a field access or an array access with
2195// constant inbounds index.
2196bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2197 Value *Addr, uint64_t TypeSize) const {
2198 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2199 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002200 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002201 int64_t Offset = SizeOffset.second.getSExtValue();
2202 // Three checks are required to ensure safety:
2203 // . Offset >= 0 (since the offset is given from the base ptr)
2204 // . Size >= Offset (unsigned)
2205 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002206 return Offset >= 0 && Size >= uint64_t(Offset) &&
2207 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002208}