blob: e7ef9f96edc220011e02e2390db0c2ce44701b3e [file] [log] [blame]
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11// Details of the algorithm:
12// http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13//
14//===----------------------------------------------------------------------===//
15
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000017#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000018#include "llvm/ADT/DenseMap.h"
Alexey Samsonov4f319cc2014-07-02 16:54:41 +000019#include "llvm/ADT/DenseSet.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000020#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000024#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000025#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000027#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/TargetLibraryInfo.h"
29#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000033#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Function.h"
35#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000037#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/IntrinsicInst.h"
39#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000040#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000041#include "llvm/IR/Module.h"
42#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000043#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000044#include "llvm/Support/CommandLine.h"
45#include "llvm/Support/DataTypes.h"
46#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000047#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000048#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000049#include "llvm/Support/raw_ostream.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000050#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000051#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000053#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000054#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000055#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000056#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000057#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000058#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000059#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000060
61using namespace llvm;
62
Chandler Carruth964daaa2014-04-22 02:55:47 +000063#define DEBUG_TYPE "asan"
64
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065static const uint64_t kDefaultShadowScale = 3;
66static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000068static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000069static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000070static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000071static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000072static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000073static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000074static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000075static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
76static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000077static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000078
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000079static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000080static const size_t kMaxStackMallocSize = 1 << 16; // 64K
81static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
82static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
83
Craig Topperd3a34f82013-07-16 01:17:10 +000084static const char *const kAsanModuleCtorName = "asan.module_ctor";
85static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000086static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000087static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000089static const char *const kAsanUnregisterGlobalsName =
90 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000091static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
92static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Alexey Samsonov4b7f4132014-12-11 21:53:03 +000093static const char *const kAsanInitName = "__asan_init_v5";
Kostya Serebryany796f6552014-02-27 12:45:36 +000094static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
95static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +000096static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000097static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +000098static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
99static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000100static const char *const kAsanGenPrefix = "__asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000101static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000102static const char *const kAsanPoisonStackMemoryName =
103 "__asan_poison_stack_memory";
104static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000105 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000106
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000107static const char *const kAsanOptionDetectUAR =
108 "__asan_option_detect_stack_use_after_return";
109
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000110static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
111static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000112
Kostya Serebryany874dae62012-07-16 16:15:40 +0000113// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
114static const size_t kNumberOfAccessSizes = 5;
115
Yury Gribov55441bb2014-11-21 10:29:50 +0000116static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000117
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000118// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000119static cl::opt<bool> ClEnableKasan(
120 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
121 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000122
123// This flag may need to be replaced with -f[no-]asan-reads.
124static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000125 cl::desc("instrument read instructions"),
126 cl::Hidden, cl::init(true));
127static cl::opt<bool> ClInstrumentWrites(
128 "asan-instrument-writes", cl::desc("instrument write instructions"),
129 cl::Hidden, cl::init(true));
130static cl::opt<bool> ClInstrumentAtomics(
131 "asan-instrument-atomics",
132 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
133 cl::init(true));
134static cl::opt<bool> ClAlwaysSlowPath(
135 "asan-always-slow-path",
136 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
137 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000138// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000139// in any given BB. Normally, this should be set to unlimited (INT_MAX),
140// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
141// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000142static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
143 "asan-max-ins-per-bb", cl::init(10000),
144 cl::desc("maximal number of instructions to instrument in any given BB"),
145 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000146// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000147static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
148 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000149static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000150 cl::desc("Check return-after-free"),
151 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000152// This flag may need to be replaced with -f[no]asan-globals.
153static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000154 cl::desc("Handle global objects"), cl::Hidden,
155 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000156static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157 cl::desc("Handle C++ initializer order"),
158 cl::Hidden, cl::init(true));
159static cl::opt<bool> ClInvalidPointerPairs(
160 "asan-detect-invalid-pointer-pair",
161 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
162 cl::init(false));
163static cl::opt<unsigned> ClRealignStack(
164 "asan-realign-stack",
165 cl::desc("Realign stack to the value of this flag (power of two)"),
166 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000167static cl::opt<int> ClInstrumentationWithCallsThreshold(
168 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000169 cl::desc(
170 "If the function being instrumented contains more than "
171 "this number of memory accesses, use callbacks instead of "
172 "inline checks (-1 means never use callbacks)."),
173 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000174static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000175 "asan-memory-access-callback-prefix",
176 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
177 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000178static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000179 cl::desc("instrument dynamic allocas"),
180 cl::Hidden, cl::init(false));
181static cl::opt<bool> ClSkipPromotableAllocas(
182 "asan-skip-promotable-allocas",
183 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
184 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000185
186// These flags allow to change the shadow mapping.
187// The shadow mapping looks like
188// Shadow = (Mem >> scale) + (1 << offset_log)
189static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000190 cl::desc("scale of asan shadow mapping"),
191 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000192
193// Optimization flags. Not user visible, used mostly for testing
194// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000195static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
196 cl::Hidden, cl::init(true));
197static cl::opt<bool> ClOptSameTemp(
198 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
199 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000200static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000201 cl::desc("Don't instrument scalar globals"),
202 cl::Hidden, cl::init(true));
203static cl::opt<bool> ClOptStack(
204 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
205 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000206
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000207static cl::opt<bool> ClCheckLifetime(
208 "asan-check-lifetime",
209 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"), cl::Hidden,
210 cl::init(false));
Alexey Samsonovdf624522012-11-29 18:14:24 +0000211
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000212static cl::opt<bool> ClDynamicAllocaStack(
213 "asan-stack-dynamic-alloca",
214 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000215 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000216
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000217static cl::opt<uint32_t> ClForceExperiment(
218 "asan-force-experiment",
219 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
220 cl::init(0));
221
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000222// Debug flags.
223static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
224 cl::init(0));
225static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
226 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000227static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
228 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000229static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
230 cl::Hidden, cl::init(-1));
231static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
232 cl::Hidden, cl::init(-1));
233
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000234STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
235STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000236STATISTIC(NumOptimizedAccessesToGlobalVar,
237 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000238STATISTIC(NumOptimizedAccessesToStackVar,
239 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000242/// Frontend-provided metadata for source location.
243struct LocationMetadata {
244 StringRef Filename;
245 int LineNo;
246 int ColumnNo;
247
248 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
249
250 bool empty() const { return Filename.empty(); }
251
252 void parse(MDNode *MDN) {
253 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000254 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
255 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000256 LineNo =
257 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
258 ColumnNo =
259 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000260 }
261};
262
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000263/// Frontend-provided metadata for global variables.
264class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000265 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000266 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000267 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000268 LocationMetadata SourceLoc;
269 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000270 bool IsDynInit;
271 bool IsBlacklisted;
272 };
273
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000274 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000275
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000276 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000277 assert(!inited_);
278 inited_ = true;
279 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000280 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000281 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000282 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000283 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000284 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000285 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000286 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000287 // We can already have an entry for GV if it was merged with another
288 // global.
289 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000290 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
291 E.SourceLoc.parse(Loc);
292 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
293 E.Name = Name->getString();
294 ConstantInt *IsDynInit =
295 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000296 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000297 ConstantInt *IsBlacklisted =
298 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000299 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000300 }
301 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000302
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000303 /// Returns metadata entry for a given global.
304 Entry get(GlobalVariable *G) const {
305 auto Pos = Entries.find(G);
306 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000307 }
308
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000309 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000310 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000311 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000312};
313
Alexey Samsonov1345d352013-01-16 13:23:28 +0000314/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000315/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000316struct ShadowMapping {
317 int Scale;
318 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000319 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000320};
321
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000322static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
323 bool IsKasan) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000324 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Bob Wilson9868d712014-10-09 05:43:30 +0000325 bool IsIOS = TargetTriple.isiOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000326 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
327 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000328 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
329 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000330 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000331 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
332 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000333 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
334 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000335 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000336 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000337
338 ShadowMapping Mapping;
339
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000340 if (LongSize == 32) {
341 if (IsAndroid)
342 Mapping.Offset = 0;
343 else if (IsMIPS32)
344 Mapping.Offset = kMIPS32_ShadowOffset32;
345 else if (IsFreeBSD)
346 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000347 else if (IsIOS)
348 Mapping.Offset = kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000349 else if (IsWindows)
350 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000351 else
352 Mapping.Offset = kDefaultShadowOffset32;
353 } else { // LongSize == 64
354 if (IsPPC64)
355 Mapping.Offset = kPPC64_ShadowOffset64;
356 else if (IsFreeBSD)
357 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000358 else if (IsLinux && IsX86_64) {
359 if (IsKasan)
360 Mapping.Offset = kLinuxKasan_ShadowOffset64;
361 else
362 Mapping.Offset = kSmallX86_64ShadowOffset;
363 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000364 Mapping.Offset = kMIPS64_ShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000365 else if (IsAArch64)
366 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000367 else
368 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000369 }
370
371 Mapping.Scale = kDefaultShadowScale;
372 if (ClMappingScale) {
373 Mapping.Scale = ClMappingScale;
374 }
375
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000376 // OR-ing shadow offset if more efficient (at least on x86) if the offset
377 // is a power of two, but on ppc64 we have to use add since the shadow
378 // offset is not necessary 1/8-th of the address space.
379 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
380
Alexey Samsonov1345d352013-01-16 13:23:28 +0000381 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000382}
383
Alexey Samsonov1345d352013-01-16 13:23:28 +0000384static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000385 // Redzone used for stack and globals is at least 32 bytes.
386 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000387 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000388}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000389
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000390/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000391struct AddressSanitizer : public FunctionPass {
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000392 explicit AddressSanitizer(bool CompileKernel = false)
393 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000394 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
395 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000396 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000397 return "AddressSanitizerFunctionPass";
398 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000399 void getAnalysisUsage(AnalysisUsage &AU) const override {
400 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000401 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000402 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000403 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
404 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000405 uint64_t SizeInBytes =
406 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000407 return SizeInBytes;
408 }
409 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000410 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000411
412 // Check if we have dynamic alloca.
413 bool isDynamicAlloca(AllocaInst &AI) const {
414 return AI.isArrayAllocation() || !AI.isStaticAlloca();
415 }
416
Anna Zaks8ed1d812015-02-27 03:12:36 +0000417 /// If it is an interesting memory access, return the PointerOperand
418 /// and set IsWrite/Alignment. Otherwise return nullptr.
419 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000420 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000421 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000422 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000423 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000424 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
425 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000426 Value *SizeArgument, bool UseCalls, uint32_t Exp);
427 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
428 uint32_t TypeSize, bool IsWrite,
429 Value *SizeArgument, bool UseCalls,
430 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000431 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
432 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000433 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000434 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000435 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000436 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000437 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000438 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000439 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000440 bool doInitialization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000441 static char ID; // Pass identification, replacement for typeid
442
Yury Gribov3ae427d2014-12-01 08:47:58 +0000443 DominatorTree &getDominatorTree() const { return *DT; }
444
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000445 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000446 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000447
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000448 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000449 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000450 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
451 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000452
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000453 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000454 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000455 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000456 bool CompileKernel;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000457 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000458 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000459 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000460 Function *AsanCtorFunction = nullptr;
461 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000462 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000463 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000464 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
465 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
466 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
467 // This array is indexed by AccessIsWrite and Experiment.
468 Function *AsanErrorCallbackSized[2][2];
469 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000470 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000471 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000472 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000473 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000474
475 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000476};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000477
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000478class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000479 public:
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000480 explicit AddressSanitizerModule(bool CompileKernel = false)
481 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000482 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000483 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000484 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000485
Kostya Serebryany20a79972012-11-22 03:18:50 +0000486 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000487 void initializeCallbacks(Module &M);
488
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000489 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000490 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000491 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000492 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000493 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000494 return RedzoneSizeForScale(Mapping.Scale);
495 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000496
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000497 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000498 bool CompileKernel;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000499 Type *IntptrTy;
500 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000501 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000502 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000503 Function *AsanPoisonGlobals;
504 Function *AsanUnpoisonGlobals;
505 Function *AsanRegisterGlobals;
506 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000507};
508
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000509// Stack poisoning does not play well with exception handling.
510// When an exception is thrown, we essentially bypass the code
511// that unpoisones the stack. This is why the run-time library has
512// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
513// stack in the interceptor. This however does not work inside the
514// actual function which catches the exception. Most likely because the
515// compiler hoists the load of the shadow value somewhere too high.
516// This causes asan to report a non-existing bug on 453.povray.
517// It sounds like an LLVM bug.
518struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
519 Function &F;
520 AddressSanitizer &ASan;
521 DIBuilder DIB;
522 LLVMContext *C;
523 Type *IntptrTy;
524 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000525 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000526
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000527 SmallVector<AllocaInst *, 16> AllocaVec;
528 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000529 unsigned StackAlignment;
530
Kostya Serebryany6805de52013-09-10 13:16:56 +0000531 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000532 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000533 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000534 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000535
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000536 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
537 struct AllocaPoisonCall {
538 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000539 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000540 uint64_t Size;
541 bool DoPoison;
542 };
543 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
544
Yury Gribov98b18592015-05-28 07:51:49 +0000545 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
546 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
547 AllocaInst *DynamicAllocaLayout = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000548
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000549 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000550 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000551 AllocaForValueMapTy AllocaForValue;
552
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000553 bool HasNonEmptyInlineAsm;
554 std::unique_ptr<CallInst> EmptyInlineAsm;
555
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000556 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000557 : F(F),
558 ASan(ASan),
559 DIB(*F.getParent(), /*AllowUnresolved*/ false),
560 C(ASan.C),
561 IntptrTy(ASan.IntptrTy),
562 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
563 Mapping(ASan.Mapping),
564 StackAlignment(1 << Mapping.Scale),
565 HasNonEmptyInlineAsm(false),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000566 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000567
568 bool runOnFunction() {
569 if (!ClStack) return false;
570 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000571 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000572
Yury Gribov55441bb2014-11-21 10:29:50 +0000573 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000574
575 initializeCallbacks(*F.getParent());
576
577 poisonStack();
578
579 if (ClDebugStack) {
580 DEBUG(dbgs() << F);
581 }
582 return true;
583 }
584
Yury Gribov55441bb2014-11-21 10:29:50 +0000585 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000586 // poisoned red zones around all of them.
587 // Then unpoison everything back before the function returns.
588 void poisonStack();
589
Yury Gribov98b18592015-05-28 07:51:49 +0000590 void createDynamicAllocasInitStorage();
591
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000592 // ----------------------- Visitors.
593 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000594 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000595
Yury Gribov98b18592015-05-28 07:51:49 +0000596 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
597 Value *SavedStack) {
598 IRBuilder<> IRB(InstBefore);
Yury Gribov781bce22015-05-28 08:03:28 +0000599 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000600 {IRB.CreateLoad(DynamicAllocaLayout),
Yury Gribov781bce22015-05-28 08:03:28 +0000601 IRB.CreatePtrToInt(SavedStack, IntptrTy)});
Yury Gribov98b18592015-05-28 07:51:49 +0000602 }
603
Yury Gribov55441bb2014-11-21 10:29:50 +0000604 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000605 void unpoisonDynamicAllocas() {
606 for (auto &Ret : RetVec)
607 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000608
Yury Gribov98b18592015-05-28 07:51:49 +0000609 for (auto &StackRestoreInst : StackRestoreVec)
610 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
611 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000612 }
613
Yury Gribov55441bb2014-11-21 10:29:50 +0000614 // Deploy and poison redzones around dynamic alloca call. To do this, we
615 // should replace this call with another one with changed parameters and
616 // replace all its uses with new address, so
617 // addr = alloca type, old_size, align
618 // is replaced by
619 // new_size = (old_size + additional_size) * sizeof(type)
620 // tmp = alloca i8, new_size, max(align, 32)
621 // addr = tmp + 32 (first 32 bytes are for the left redzone).
622 // Additional_size is added to make new memory allocation contain not only
623 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000624 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000625
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000626 /// \brief Collect Alloca instructions we want (and can) handle.
627 void visitAllocaInst(AllocaInst &AI) {
Anna Zaks8ed1d812015-02-27 03:12:36 +0000628 if (!ASan.isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000629
630 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000631 if (ASan.isDynamicAlloca(AI))
632 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000633 else
634 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000635 }
636
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000637 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
638 /// errors.
639 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000640 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000641 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
642 if (!ClCheckLifetime) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000643 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000644 return;
645 // Found lifetime intrinsic, add ASan instrumentation if necessary.
646 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
647 // If size argument is undefined, don't do anything.
648 if (Size->isMinusOne()) return;
649 // Check that size doesn't saturate uint64_t and can
650 // be stored in IntptrTy.
651 const uint64_t SizeValue = Size->getValue().getLimitedValue();
652 if (SizeValue == ~0ULL ||
653 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
654 return;
655 // Find alloca instruction that corresponds to llvm.lifetime argument.
656 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
657 if (!AI) return;
658 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000659 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000660 AllocaPoisonCallVec.push_back(APC);
661 }
662
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000663 void visitCallInst(CallInst &CI) {
664 HasNonEmptyInlineAsm |=
665 CI.isInlineAsm() && !CI.isIdenticalTo(EmptyInlineAsm.get());
666 }
667
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000668 // ---------------------- Helpers.
669 void initializeCallbacks(Module &M);
670
Yury Gribov3ae427d2014-12-01 08:47:58 +0000671 bool doesDominateAllExits(const Instruction *I) const {
672 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000673 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000674 }
675 return true;
676 }
677
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000678 /// Finds alloca where the value comes from.
679 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000680 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000681 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000682 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000683
684 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
685 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000686 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
687 bool Dynamic);
688 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
689 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000690};
691
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000692} // namespace
693
694char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000695INITIALIZE_PASS_BEGIN(
696 AddressSanitizer, "asan",
697 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
698 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000699INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000700INITIALIZE_PASS_END(
701 AddressSanitizer, "asan",
702 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
703 false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000704FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel) {
705 return new AddressSanitizer(CompileKernel);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000706}
707
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000708char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000709INITIALIZE_PASS(
710 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000711 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000712 "ModulePass",
713 false, false)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000714ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel) {
715 return new AddressSanitizerModule(CompileKernel);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000716}
717
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000718static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000719 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000720 assert(Res < kNumberOfAccessSizes);
721 return Res;
722}
723
Bill Wendling58f8cef2013-08-06 22:52:42 +0000724// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000725static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
726 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000727 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000728 // We use private linkage for module-local strings. If they can be merged
729 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000730 GlobalVariable *GV =
731 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000732 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000733 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000734 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
735 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000736}
737
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000738/// \brief Create a global describing a source location.
739static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
740 LocationMetadata MD) {
741 Constant *LocData[] = {
742 createPrivateGlobalForString(M, MD.Filename, true),
743 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
744 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
745 };
746 auto LocStruct = ConstantStruct::getAnon(LocData);
747 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
748 GlobalValue::PrivateLinkage, LocStruct,
749 kAsanGenPrefix);
750 GV->setUnnamedAddr(true);
751 return GV;
752}
753
Kostya Serebryany139a9372012-11-20 14:16:08 +0000754static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000755 return G->getName().find(kAsanGenPrefix) == 0 ||
756 G->getName().find(kSanCovGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000757}
758
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000759Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
760 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000761 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000762 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000763 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000764 if (Mapping.OrShadowOffset)
765 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
766 else
767 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000768}
769
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000770// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000771void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
772 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000773 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000774 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000775 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000776 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
777 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
778 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000779 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000780 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000781 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000782 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
783 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
784 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000785 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000786 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000787}
788
Anna Zaks8ed1d812015-02-27 03:12:36 +0000789/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000790bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
791 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
792
793 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
794 return PreviouslySeenAllocaInfo->getSecond();
795
Yury Gribov98b18592015-05-28 07:51:49 +0000796 bool IsInteresting =
797 (AI.getAllocatedType()->isSized() &&
798 // alloca() may be called with 0 size, ignore it.
799 getAllocaSizeInBytes(&AI) > 0 &&
800 // We are only interested in allocas not promotable to registers.
801 // Promotable allocas are common under -O0.
802 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI) ||
803 isDynamicAlloca(AI)));
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000804
805 ProcessedAllocas[&AI] = IsInteresting;
806 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000807}
808
809/// If I is an interesting memory access, return the PointerOperand
810/// and set IsWrite/Alignment. Otherwise return nullptr.
811Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
812 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000813 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000814 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000815 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000816 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000817
818 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000819 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000820 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000821 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000822 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000823 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000824 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000825 PtrOperand = LI->getPointerOperand();
826 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000827 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000828 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000829 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000830 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000831 PtrOperand = SI->getPointerOperand();
832 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000833 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000834 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000835 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000836 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000837 PtrOperand = RMW->getPointerOperand();
838 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000839 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000840 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000841 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000842 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000843 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000844 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000845
846 // Treat memory accesses to promotable allocas as non-interesting since they
847 // will not cause memory violations. This greatly speeds up the instrumented
848 // executable at -O0.
849 if (ClSkipPromotableAllocas)
850 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
851 return isInterestingAlloca(*AI) ? AI : nullptr;
852
853 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000854}
855
Kostya Serebryany796f6552014-02-27 12:45:36 +0000856static bool isPointerOperand(Value *V) {
857 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
858}
859
860// This is a rough heuristic; it may cause both false positives and
861// false negatives. The proper implementation requires cooperation with
862// the frontend.
863static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
864 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000865 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000866 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000867 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000868 } else {
869 return false;
870 }
871 if (!isPointerOperand(I->getOperand(0)) ||
872 !isPointerOperand(I->getOperand(1)))
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000873 return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000874 return true;
875}
876
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000877bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
878 // If a global variable does not have dynamic initialization we don't
879 // have to instrument it. However, if a global does not have initializer
880 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000881 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000882}
883
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000884void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
885 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000886 IRBuilder<> IRB(I);
887 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
888 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
889 for (int i = 0; i < 2; i++) {
890 if (Param[i]->getType()->isPointerTy())
891 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
892 }
David Blaikieff6409d2015-05-18 22:13:54 +0000893 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000894}
895
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000896void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000897 Instruction *I, bool UseCalls,
898 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000899 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000900 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000901 uint64_t TypeSize = 0;
902 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000903 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000904
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000905 // Optimization experiments.
906 // The experiments can be used to evaluate potential optimizations that remove
907 // instrumentation (assess false negatives). Instead of completely removing
908 // some instrumentation, you set Exp to a non-zero value (mask of optimization
909 // experiments that want to remove instrumentation of this instruction).
910 // If Exp is non-zero, this pass will emit special calls into runtime
911 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
912 // make runtime terminate the program in a special way (with a different
913 // exit status). Then you run the new compiler on a buggy corpus, collect
914 // the special terminations (ideally, you don't see them at all -- no false
915 // negatives) and make the decision on the optimization.
916 uint32_t Exp = ClForceExperiment;
917
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000918 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000919 // If initialization order checking is disabled, a simple access to a
920 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000921 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000922 if (G != NULL && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
923 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
924 NumOptimizedAccessesToGlobalVar++;
925 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000926 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000927 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000928
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000929 if (ClOpt && ClOptStack) {
930 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000931 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000932 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
933 NumOptimizedAccessesToStackVar++;
934 return;
935 }
936 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000937
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000938 if (IsWrite)
939 NumInstrumentedWrites++;
940 else
941 NumInstrumentedReads++;
942
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000943 unsigned Granularity = 1 << Mapping.Scale;
944 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
945 // if the data is properly aligned.
946 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
947 TypeSize == 128) &&
948 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000949 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
950 Exp);
951 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
952 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000953}
954
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000955Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
956 Value *Addr, bool IsWrite,
957 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000958 Value *SizeArgument,
959 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000960 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000961 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
962 CallInst *Call = nullptr;
963 if (SizeArgument) {
964 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +0000965 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
966 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000967 else
David Blaikieff6409d2015-05-18 22:13:54 +0000968 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
969 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000970 } else {
971 if (Exp == 0)
972 Call =
973 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
974 else
David Blaikieff6409d2015-05-18 22:13:54 +0000975 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
976 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000977 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000978
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000979 // We don't do Call->setDoesNotReturn() because the BB already has
980 // UnreachableInst at the end.
981 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +0000982 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000983 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000984}
985
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000986Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000987 Value *ShadowValue,
988 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000989 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000990 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000991 Value *LastAccessedByte =
992 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000993 // (Addr & (Granularity - 1)) + size - 1
994 if (TypeSize / 8 > 1)
995 LastAccessedByte = IRB.CreateAdd(
996 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
997 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000998 LastAccessedByte =
999 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001000 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1001 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1002}
1003
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001004void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001005 Instruction *InsertBefore, Value *Addr,
1006 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001007 Value *SizeArgument, bool UseCalls,
1008 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001009 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001010 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001011 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1012
1013 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001014 if (Exp == 0)
1015 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1016 AddrLong);
1017 else
David Blaikieff6409d2015-05-18 22:13:54 +00001018 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1019 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001020 return;
1021 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001022
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001023 Type *ShadowTy =
1024 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001025 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1026 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1027 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001028 Value *ShadowValue =
1029 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001030
1031 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Alexey Samsonov1345d352013-01-16 13:23:28 +00001032 size_t Granularity = 1 << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001033 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001034
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001035 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001036 // We use branch weights for the slow path check, to indicate that the slow
1037 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001038 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1039 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001040 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001041 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001042 IRB.SetInsertPoint(CheckTerm);
1043 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001044 BasicBlock *CrashBlock =
1045 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001046 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001047 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1048 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001049 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001050 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001051 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001052
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001053 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001054 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001055 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001056}
1057
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001058// Instrument unusual size or unusual alignment.
1059// We can not do it with a single check, so we do 1-byte check for the first
1060// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1061// to report the actual access size.
1062void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1063 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1064 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1065 IRBuilder<> IRB(I);
1066 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1067 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1068 if (UseCalls) {
1069 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001070 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1071 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001072 else
David Blaikieff6409d2015-05-18 22:13:54 +00001073 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1074 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001075 } else {
1076 Value *LastByte = IRB.CreateIntToPtr(
1077 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1078 Addr->getType());
1079 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1080 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1081 }
1082}
1083
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001084void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1085 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001086 // Set up the arguments to our poison/unpoison functions.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001087 IRBuilder<> IRB(GlobalInit.begin()->getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001088
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001089 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001090 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1091 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001092
1093 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001094 for (auto &BB : GlobalInit.getBasicBlockList())
1095 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001096 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001097}
1098
1099void AddressSanitizerModule::createInitializerPoisonCalls(
1100 Module &M, GlobalValue *ModuleName) {
1101 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1102
1103 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1104 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001105 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001106 ConstantStruct *CS = cast<ConstantStruct>(OP);
1107
1108 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001109 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001110 if (F->getName() == kAsanModuleCtorName) continue;
1111 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1112 // Don't instrument CTORs that will run before asan.module_ctor.
1113 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1114 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001115 }
1116 }
1117}
1118
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001119bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001120 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001121 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001122
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001123 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001124 if (!Ty->isSized()) return false;
1125 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001126 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001127 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001128 // Don't handle ODR linkage types and COMDATs since other modules may be built
1129 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001130 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1131 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1132 G->getLinkage() != GlobalVariable::InternalLinkage)
1133 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001134 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001135 // Two problems with thread-locals:
1136 // - The address of the main thread's copy can't be computed at link-time.
1137 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001138 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001139 // For now, just ignore this Global if the alignment is large.
1140 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001141
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001142 if (G->hasSection()) {
1143 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001144
Anna Zaks11904602015-06-09 00:58:08 +00001145 // Globals from llvm.metadata aren't emitted, do not instrument them.
1146 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001147 // Do not instrument globals from special LLVM sections.
1148 if (Section.find("__llvm") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001149
1150 // Callbacks put into the CRT initializer/terminator sections
1151 // should not be instrumented.
1152 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1153 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1154 if (Section.startswith(".CRT")) {
1155 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1156 return false;
1157 }
1158
Kuba Brecka1001bb52014-12-05 22:19:18 +00001159 if (TargetTriple.isOSBinFormatMachO()) {
1160 StringRef ParsedSegment, ParsedSection;
1161 unsigned TAA = 0, StubSize = 0;
1162 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001163 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1164 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001165 if (!ErrorCode.empty()) {
Anna Zaks11904602015-06-09 00:58:08 +00001166 assert(false && "Invalid section specifier.");
1167 return false;
Kuba Brecka1001bb52014-12-05 22:19:18 +00001168 }
1169
1170 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1171 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1172 // them.
1173 if (ParsedSegment == "__OBJC" ||
1174 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1175 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1176 return false;
1177 }
1178 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1179 // Constant CFString instances are compiled in the following way:
1180 // -- the string buffer is emitted into
1181 // __TEXT,__cstring,cstring_literals
1182 // -- the constant NSConstantString structure referencing that buffer
1183 // is placed into __DATA,__cfstring
1184 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1185 // Moreover, it causes the linker to crash on OS X 10.7
1186 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1187 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1188 return false;
1189 }
1190 // The linker merges the contents of cstring_literals and removes the
1191 // trailing zeroes.
1192 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1193 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1194 return false;
1195 }
1196 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001197 }
1198
1199 return true;
1200}
1201
Alexey Samsonov788381b2012-12-25 12:28:20 +00001202void AddressSanitizerModule::initializeCallbacks(Module &M) {
1203 IRBuilder<> IRB(*C);
1204 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001205 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001206 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001207 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001208 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001209 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001210 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1211 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001212 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001213 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001214 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001215 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001216 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1217 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001218 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1219}
1220
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001221// This function replaces all global variables with new variables that have
1222// trailing redzones. It also creates a function that poisons
1223// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001224bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001225 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001226
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001227 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1228
Alexey Samsonova02e6642014-05-29 18:40:48 +00001229 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001230 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001231 }
1232
1233 size_t n = GlobalsToChange.size();
1234 if (n == 0) return false;
1235
1236 // A global is described by a structure
1237 // size_t beg;
1238 // size_t size;
1239 // size_t size_with_redzone;
1240 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001241 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001242 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001243 // void *source_location;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001244 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001245 StructType *GlobalStructTy =
1246 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001247 IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001248 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001249
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001250 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001251
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001252 // We shouldn't merge same module names, as this string serves as unique
1253 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001254 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001255 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001256
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001257 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001258 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001259 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001260 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001261
1262 auto MD = GlobalsMD.get(G);
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001263 // Create string holding the global name (use global name from metadata
1264 // if it's available, otherwise just write the name of global variable).
1265 GlobalVariable *Name = createPrivateGlobalForString(
1266 M, MD.Name.empty() ? G->getName() : MD.Name,
1267 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001268
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001269 PointerType *PtrTy = cast<PointerType>(G->getType());
1270 Type *Ty = PtrTy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001271 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001272 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001273 // MinRZ <= RZ <= kMaxGlobalRedzone
1274 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001275 uint64_t RZ = std::max(
1276 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001277 uint64_t RightRedzoneSize = RZ;
1278 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001279 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001280 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001281 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1282
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001283 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001284 Constant *NewInitializer =
1285 ConstantStruct::get(NewTy, G->getInitializer(),
1286 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001287
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001288 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001289 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1290 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1291 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001292 GlobalVariable *NewGlobal =
1293 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1294 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001295 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001296 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001297
1298 Value *Indices2[2];
1299 Indices2[0] = IRB.getInt32(0);
1300 Indices2[1] = IRB.getInt32(0);
1301
1302 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001303 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001304 NewGlobal->takeName(G);
1305 G->eraseFromParent();
1306
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001307 Constant *SourceLoc;
1308 if (!MD.SourceLoc.empty()) {
1309 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1310 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1311 } else {
1312 SourceLoc = ConstantInt::get(IntptrTy, 0);
1313 }
1314
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001315 Initializers[i] = ConstantStruct::get(
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001316 GlobalStructTy, ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001317 ConstantInt::get(IntptrTy, SizeInBytes),
1318 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1319 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001320 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001321 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc, nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001322
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001323 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001324
Kostya Serebryany20343352012-10-17 13:40:06 +00001325 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001326 }
1327
1328 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1329 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001330 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001331 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1332
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001333 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001334 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001335 createInitializerPoisonCalls(M, ModuleName);
David Blaikieff6409d2015-05-18 22:13:54 +00001336 IRB.CreateCall(AsanRegisterGlobals,
1337 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1338 ConstantInt::get(IntptrTy, n)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001339
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001340 // We also need to unregister globals at the end, e.g. when a shared library
1341 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001342 Function *AsanDtorFunction =
1343 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1344 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001345 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1346 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
David Blaikieff6409d2015-05-18 22:13:54 +00001347 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1348 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1349 ConstantInt::get(IntptrTy, n)});
Alexey Samsonov1f647502014-05-29 01:10:14 +00001350 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001351
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001352 DEBUG(dbgs() << M);
1353 return true;
1354}
1355
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001356bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001357 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001358 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001359 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001360 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001361 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001362 initializeCallbacks(M);
1363
1364 bool Changed = false;
1365
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001366 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1367 if (ClGlobals && !CompileKernel) {
1368 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1369 assert(CtorFunc);
1370 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1371 Changed |= InstrumentGlobals(IRB, M);
1372 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001373
1374 return Changed;
1375}
1376
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001377void AddressSanitizer::initializeCallbacks(Module &M) {
1378 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001379 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001380 // IsWrite, TypeSize and Exp are encoded in the function name.
1381 for (int Exp = 0; Exp < 2; Exp++) {
1382 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1383 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1384 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001385 const std::string SuffixStr = CompileKernel ? "N" : "_n";
1386 const std::string EndingStr = CompileKernel ? "_noabort" : "";
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001387 const Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001388 // TODO(glider): for KASan builds add _noabort to error reporting
1389 // functions and make them actually noabort (remove the UnreachableInst).
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001390 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001391 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001392 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001393 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1394 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001395 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001396 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001397 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1398 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1399 AccessSizeIndex++) {
1400 const std::string Suffix = TypeStr + itostr(1 << AccessSizeIndex);
1401 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001402 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001403 kAsanReportErrorTemplate + ExpStr + Suffix,
1404 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001405 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001406 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001407 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1408 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001409 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001410 }
1411 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001412
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001413 const std::string MemIntrinCallbackPrefix =
1414 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001415 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001416 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001417 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001418 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001419 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001420 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001421 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001422 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001423 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001424
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001425 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001426 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001427
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001428 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001429 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001430 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001431 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001432 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1433 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1434 StringRef(""), StringRef(""),
1435 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001436}
1437
1438// virtual
1439bool AddressSanitizer::doInitialization(Module &M) {
1440 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001441
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001442 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001443
1444 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001445 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001446 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001447 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001448
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001449 if (!CompileKernel) {
1450 std::tie(AsanCtorFunction, AsanInitFunction) =
1451 createSanitizerCtorAndInitFunctions(M, kAsanModuleCtorName, kAsanInitName,
1452 /*InitArgTypes=*/{},
1453 /*InitArgs=*/{});
1454 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1455 }
1456 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001457 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001458}
1459
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001460bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1461 // For each NSObject descendant having a +load method, this method is invoked
1462 // by the ObjC runtime before any of the static constructors is called.
1463 // Therefore we need to instrument such methods with a call to __asan_init
1464 // at the beginning in order to initialize our runtime before any access to
1465 // the shadow memory.
1466 // We cannot just ignore these methods, because they may call other
1467 // instrumented functions.
1468 if (F.getName().find(" load]") != std::string::npos) {
1469 IRBuilder<> IRB(F.begin()->begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001470 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001471 return true;
1472 }
1473 return false;
1474}
1475
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001476bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001477 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001478 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001479 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001480 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001481
Yury Gribov3ae427d2014-12-01 08:47:58 +00001482 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1483
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001484 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001485 maybeInsertAsanInitAtFunctionEntry(F);
1486
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001487 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001488
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001489 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001490
1491 // We want to instrument every address only once per basic block (unless there
1492 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001493 SmallSet<Value *, 16> TempsToInstrument;
1494 SmallVector<Instruction *, 16> ToInstrument;
1495 SmallVector<Instruction *, 8> NoReturnCalls;
1496 SmallVector<BasicBlock *, 16> AllBlocks;
1497 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001498 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001499 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001500 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001501 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001502
1503 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001504 for (auto &BB : F) {
1505 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001506 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001507 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001508 for (auto &Inst : BB) {
1509 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001510 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1511 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001512 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001513 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001514 continue; // We've seen this temp in the current BB.
1515 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001516 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001517 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1518 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001519 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001520 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001521 // ok, take it.
1522 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001523 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001524 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001525 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001526 // A call inside BB.
1527 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001528 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001529 }
1530 continue;
1531 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001532 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001533 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001534 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001535 }
1536 }
1537
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001538 bool UseCalls =
1539 CompileKernel ||
1540 (ClInstrumentationWithCallsThreshold >= 0 &&
1541 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001542 const TargetLibraryInfo *TLI =
1543 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001544 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001545 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1546 /*RoundToAlign=*/true);
1547
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001548 // Instrument.
1549 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001550 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001551 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1552 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001553 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001554 instrumentMop(ObjSizeVis, Inst, UseCalls,
1555 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001556 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001557 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001558 }
1559 NumInstrumented++;
1560 }
1561
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001562 FunctionStackPoisoner FSP(F, *this);
1563 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001564
1565 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1566 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001567 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001568 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001569 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001570 }
1571
Alexey Samsonova02e6642014-05-29 18:40:48 +00001572 for (auto Inst : PointerComparisonsOrSubtracts) {
1573 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001574 NumInstrumented++;
1575 }
1576
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001577 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001578
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001579 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1580
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001581 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001582}
1583
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001584// Workaround for bug 11395: we don't want to instrument stack in functions
1585// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1586// FIXME: remove once the bug 11395 is fixed.
1587bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1588 if (LongSize != 32) return false;
1589 CallInst *CI = dyn_cast<CallInst>(I);
1590 if (!CI || !CI->isInlineAsm()) return false;
1591 if (CI->getNumArgOperands() <= 5) return false;
1592 // We have inline assembly with quite a few arguments.
1593 return true;
1594}
1595
1596void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1597 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001598 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1599 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001600 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1601 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1602 IntptrTy, nullptr));
1603 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001604 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1605 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001606 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001607 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001608 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1609 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001610 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001611 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1612 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001613 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1614 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1615 AsanAllocasUnpoisonFunc =
1616 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1617 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001618}
1619
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001620void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1621 IRBuilder<> &IRB, Value *ShadowBase,
1622 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001623 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001624 size_t i = 0;
1625 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1626 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1627 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1628 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1629 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1630 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1631 uint64_t Val = 0;
1632 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001633 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001634 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1635 else
1636 Val = (Val << 8) | ShadowBytes[i + j];
1637 }
1638 if (!Val) continue;
1639 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1640 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1641 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1642 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001643 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001644 }
1645}
1646
Kostya Serebryany6805de52013-09-10 13:16:56 +00001647// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1648// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1649static int StackMallocSizeClass(uint64_t LocalStackSize) {
1650 assert(LocalStackSize <= kMaxStackMallocSize);
1651 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001652 for (int i = 0;; i++, MaxSize *= 2)
1653 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001654 llvm_unreachable("impossible LocalStackSize");
1655}
1656
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001657// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1658// We can not use MemSet intrinsic because it may end up calling the actual
1659// memset. Size is a multiple of 8.
1660// Currently this generates 8-byte stores on x86_64; it may be better to
1661// generate wider stores.
1662void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1663 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1664 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001665
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001666 // kAsanStackAfterReturnMagic is 0xf5.
1667 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001668
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001669 for (int i = 0; i < Size; i += 8) {
1670 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001671 IRB.CreateStore(
1672 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1673 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001674 }
1675}
1676
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001677PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1678 Value *ValueIfTrue,
1679 Instruction *ThenTerm,
1680 Value *ValueIfFalse) {
1681 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1682 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1683 PHI->addIncoming(ValueIfFalse, CondBlock);
1684 BasicBlock *ThenBlock = ThenTerm->getParent();
1685 PHI->addIncoming(ValueIfTrue, ThenBlock);
1686 return PHI;
1687}
1688
1689Value *FunctionStackPoisoner::createAllocaForLayout(
1690 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1691 AllocaInst *Alloca;
1692 if (Dynamic) {
1693 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1694 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1695 "MyAlloca");
1696 } else {
1697 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1698 nullptr, "MyAlloca");
1699 assert(Alloca->isStaticAlloca());
1700 }
1701 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1702 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1703 Alloca->setAlignment(FrameAlignment);
1704 return IRB.CreatePointerCast(Alloca, IntptrTy);
1705}
1706
Yury Gribov98b18592015-05-28 07:51:49 +00001707void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1708 BasicBlock &FirstBB = *F.begin();
1709 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1710 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1711 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1712 DynamicAllocaLayout->setAlignment(32);
1713}
1714
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001715void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001716 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1717
Yury Gribov98b18592015-05-28 07:51:49 +00001718 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001719 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001720 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001721 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001722
1723 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001724 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001725
1726 if (AllocaVec.size() == 0) return;
1727
Kostya Serebryany6805de52013-09-10 13:16:56 +00001728 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001729 DebugLoc EntryDebugLocation;
1730 if (auto SP = getDISubprogram(&F))
1731 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001732
1733 Instruction *InsBefore = AllocaVec[0];
1734 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001735 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001736
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001737 SmallVector<ASanStackVariableDescription, 16> SVD;
1738 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00001739 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001740 ASanStackVariableDescription D = {AI->getName().data(),
1741 ASan.getAllocaSizeInBytes(AI),
1742 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001743 SVD.push_back(D);
1744 }
1745 // Minimal header size (left redzone) is 4 pointers,
1746 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1747 size_t MinHeaderSize = ASan.LongSize / 2;
1748 ASanStackFrameLayout L;
1749 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1750 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1751 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001752 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
1753 LocalStackSize <= kMaxStackMallocSize;
Anna Zaks4f652b62015-06-25 23:35:45 +00001754 // Don't do dynamic alloca or stack malloc in presence of inline asm:
1755 // too often it makes assumptions on which registers are available.
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001756 bool DoDynamicAlloca = ClDynamicAllocaStack && !HasNonEmptyInlineAsm;
Anna Zaks4f652b62015-06-25 23:35:45 +00001757 DoStackMalloc &= !HasNonEmptyInlineAsm;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001758
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001759 Value *StaticAlloca =
1760 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
1761
1762 Value *FakeStack;
1763 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001764
1765 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001766 // void *FakeStack = __asan_option_detect_stack_use_after_return
1767 // ? __asan_stack_malloc_N(LocalStackSize)
1768 // : nullptr;
1769 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001770 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1771 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001772 Value *UARIsEnabled =
1773 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1774 Constant::getNullValue(IRB.getInt32Ty()));
1775 Instruction *Term =
1776 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001777 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001778 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001779 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1780 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1781 Value *FakeStackValue =
1782 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
1783 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001784 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001785 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001786 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
1787 ConstantInt::get(IntptrTy, 0));
1788
1789 Value *NoFakeStack =
1790 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
1791 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
1792 IRBIf.SetInsertPoint(Term);
1793 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
1794 Value *AllocaValue =
1795 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
1796 IRB.SetInsertPoint(InsBefore);
1797 IRB.SetCurrentDebugLocation(EntryDebugLocation);
1798 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
1799 } else {
1800 // void *FakeStack = nullptr;
1801 // void *LocalStackBase = alloca(LocalStackSize);
1802 FakeStack = ConstantInt::get(IntptrTy, 0);
1803 LocalStackBase =
1804 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001805 }
1806
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001807 // Insert poison calls for lifetime intrinsics for alloca.
1808 bool HavePoisonedAllocas = false;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001809 for (const auto &APC : AllocaPoisonCallVec) {
Alexey Samsonova788b942013-11-18 14:53:55 +00001810 assert(APC.InsBefore);
1811 assert(APC.AI);
1812 IRBuilder<> IRB(APC.InsBefore);
1813 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001814 HavePoisonedAllocas |= APC.DoPoison;
1815 }
1816
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001817 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001818 for (const auto &Desc : SVD) {
1819 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001820 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00001821 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001822 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00001823 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001824 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001825 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001826
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001827 // The left-most redzone has enough space for at least 4 pointers.
1828 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001829 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1830 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1831 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001832 // Write the frame description constant to redzone[1].
1833 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001834 IRB.CreateAdd(LocalStackBase,
1835 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
1836 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001837 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001838 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001839 /*AllowMerging*/ true);
1840 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001841 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001842 // Write the PC to redzone[2].
1843 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001844 IRB.CreateAdd(LocalStackBase,
1845 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
1846 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001847 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001848
1849 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001850 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001851 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001852
Kostya Serebryany530e2072013-12-23 14:15:08 +00001853 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001854 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001855 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001856 // Mark the current frame as retired.
1857 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1858 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001859 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001860 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001861 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00001862 // // In use-after-return mode, poison the whole stack frame.
1863 // if StackMallocIdx <= 4
1864 // // For small sizes inline the whole thing:
1865 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001866 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00001867 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001868 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00001869 // else
1870 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001871 Value *Cmp =
1872 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00001873 TerminatorInst *ThenTerm, *ElseTerm;
1874 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1875
1876 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001877 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001878 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1879 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1880 ClassSize >> Mapping.Scale);
1881 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001882 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001883 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1884 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1885 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1886 IRBPoison.CreateStore(
1887 Constant::getNullValue(IRBPoison.getInt8Ty()),
1888 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1889 } else {
1890 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00001891 IRBPoison.CreateCall(
1892 AsanStackFreeFunc[StackMallocIdx],
1893 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001894 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001895
1896 IRBuilder<> IRBElse(ElseTerm);
1897 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001898 } else if (HavePoisonedAllocas) {
1899 // If we poisoned some allocas in llvm.lifetime analysis,
1900 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00001901 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001902 } else {
1903 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001904 }
1905 }
1906
Kostya Serebryany09959942012-10-19 06:20:53 +00001907 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001908 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001909}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001910
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001911void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001912 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001913 // For now just insert the call to ASan runtime.
1914 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1915 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001916 IRB.CreateCall(
1917 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
1918 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00001919}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001920
1921// Handling llvm.lifetime intrinsics for a given %alloca:
1922// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1923// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1924// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1925// could be poisoned by previous llvm.lifetime.end instruction, as the
1926// variable may go in and out of scope several times, e.g. in loops).
1927// (3) if we poisoned at least one %alloca in a function,
1928// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001929
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001930AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1931 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1932 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00001933 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001934 // See if we've already calculated (or started to calculate) alloca for a
1935 // given value.
1936 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001937 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001938 // Store 0 while we're calculating alloca for value V to avoid
1939 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00001940 AllocaForValue[V] = nullptr;
1941 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001942 if (CastInst *CI = dyn_cast<CastInst>(V))
1943 Res = findAllocaForValue(CI->getOperand(0));
1944 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00001945 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001946 // Allow self-referencing phi-nodes.
1947 if (IncValue == PN) continue;
1948 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1949 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00001950 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
1951 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001952 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001953 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001954 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001955 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001956 return Res;
1957}
Yury Gribov55441bb2014-11-21 10:29:50 +00001958
Yury Gribov98b18592015-05-28 07:51:49 +00001959void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001960 IRBuilder<> IRB(AI);
1961
Yury Gribov55441bb2014-11-21 10:29:50 +00001962 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
1963 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
1964
1965 Value *Zero = Constant::getNullValue(IntptrTy);
1966 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
1967 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00001968
1969 // Since we need to extend alloca with additional memory to locate
1970 // redzones, and OldSize is number of allocated blocks with
1971 // ElementSize size, get allocated memory size in bytes by
1972 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00001973 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001974 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00001975 Value *OldSize =
1976 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
1977 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00001978
1979 // PartialSize = OldSize % 32
1980 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
1981
1982 // Misalign = kAllocaRzSize - PartialSize;
1983 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
1984
1985 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
1986 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
1987 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
1988
1989 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
1990 // Align is added to locate left redzone, PartialPadding for possible
1991 // partial redzone and kAllocaRzSize for right redzone respectively.
1992 Value *AdditionalChunkSize = IRB.CreateAdd(
1993 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
1994
1995 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
1996
1997 // Insert new alloca with new NewSize and Align params.
1998 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
1999 NewAlloca->setAlignment(Align);
2000
2001 // NewAddress = Address + Align
2002 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2003 ConstantInt::get(IntptrTy, Align));
2004
Yury Gribov98b18592015-05-28 07:51:49 +00002005 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002006 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002007
2008 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2009 // for unpoisoning stuff.
2010 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2011
Yury Gribov55441bb2014-11-21 10:29:50 +00002012 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2013
Yury Gribov98b18592015-05-28 07:51:49 +00002014 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002015 AI->replaceAllUsesWith(NewAddressPtr);
2016
Yury Gribov98b18592015-05-28 07:51:49 +00002017 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002018 AI->eraseFromParent();
2019}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002020
2021// isSafeAccess returns true if Addr is always inbounds with respect to its
2022// base object. For example, it is a field access or an array access with
2023// constant inbounds index.
2024bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2025 Value *Addr, uint64_t TypeSize) const {
2026 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2027 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002028 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002029 int64_t Offset = SizeOffset.second.getSExtValue();
2030 // Three checks are required to ensure safety:
2031 // . Offset >= 0 (since the offset is given from the base ptr)
2032 // . Size >= Offset (unsigned)
2033 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002034 return Offset >= 0 && Size >= uint64_t(Offset) &&
2035 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002036}