blob: 24fdee10a34431694c34489d7fdb1558dfe22d8d [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
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000016#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000017#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000018#include "llvm/ADT/DepthFirstIterator.h"
Kuba Brecka8ec94ea2015-07-22 10:25:38 +000019#include "llvm/ADT/SetVector.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000020#include "llvm/ADT/SmallSet.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000021#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000022#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000023#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000024#include "llvm/ADT/Triple.h"
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000025#include "llvm/Analysis/MemoryBuiltins.h"
26#include "llvm/Analysis/TargetLibraryInfo.h"
27#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000029#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Yury Gribov3ae427d2014-12-01 08:47:58 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Function.h"
33#include "llvm/IR/IRBuilder.h"
34#include "llvm/IR/InlineAsm.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000035#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000038#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Module.h"
40#include "llvm/IR/Type.h"
Kuba Brecka1001bb52014-12-05 22:19:18 +000041#include "llvm/MC/MCSectionMachO.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000042#include "llvm/Support/CommandLine.h"
43#include "llvm/Support/DataTypes.h"
44#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000045#include "llvm/Support/Endian.h"
Yury Gribov55441bb2014-11-21 10:29:50 +000046#include "llvm/Support/SwapByteOrder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000047#include "llvm/Support/raw_ostream.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000048#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany351b0782014-09-03 22:37:37 +000049#include "llvm/Transforms/Scalar.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000050#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000052#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000053#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054#include "llvm/Transforms/Utils/ModuleUtils.h"
Anna Zaks8ed1d812015-02-27 03:12:36 +000055#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000056#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include <string>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000058#include <system_error>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000059
60using namespace llvm;
61
Chandler Carruth964daaa2014-04-22 02:55:47 +000062#define DEBUG_TYPE "asan"
63
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000064static const uint64_t kDefaultShadowScale = 3;
65static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
66static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Anna Zaks3b50e702016-02-02 22:05:07 +000067static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
68static const uint64_t kIOSShadowOffset64 = 0x120200000;
69static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
70static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000071static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +000072static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
Kostya Serebryany4766fe62013-01-23 12:54:55 +000073static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryanyc5bd9812014-11-04 19:46:15 +000074static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
Kumar Sukhani9559a5c2015-01-31 10:43:18 +000075static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
Renato Golinaf213722015-02-03 11:20:45 +000076static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000077static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
78static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Timur Iskhodzhanovb4b6b742015-01-22 12:24:21 +000079static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000080
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000081static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000082static const size_t kMaxStackMallocSize = 1 << 16; // 64K
83static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
84static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
85
Craig Topperd3a34f82013-07-16 01:17:10 +000086static const char *const kAsanModuleCtorName = "asan.module_ctor";
87static const char *const kAsanModuleDtorName = "asan.module_dtor";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +000088static const uint64_t kAsanCtorAndDtorPriority = 1;
Craig Topperd3a34f82013-07-16 01:17:10 +000089static const char *const kAsanReportErrorTemplate = "__asan_report_";
Craig Topperd3a34f82013-07-16 01:17:10 +000090static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000091static const char *const kAsanUnregisterGlobalsName =
92 "__asan_unregister_globals";
Ryan Govostes653f9d02016-03-28 20:28:57 +000093static const char *const kAsanRegisterImageGlobalsName =
94 "__asan_register_image_globals";
95static const char *const kAsanUnregisterImageGlobalsName =
96 "__asan_unregister_image_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000097static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
98static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kuba Brecka45dbffd2015-07-23 10:54:06 +000099static const char *const kAsanInitName = "__asan_init";
100static const char *const kAsanVersionCheckName =
Ryan Govostes653f9d02016-03-28 20:28:57 +0000101 "__asan_version_mismatch_check_v8";
Kostya Serebryany796f6552014-02-27 12:45:36 +0000102static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
103static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
Craig Topperd3a34f82013-07-16 01:17:10 +0000104static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000105static const int kMaxAsanStackMallocSizeClass = 10;
Kostya Serebryany6805de52013-09-10 13:16:56 +0000106static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
107static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000108static const char *const kAsanGenPrefix = "__asan_gen_";
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000109static const char *const kODRGenPrefix = "__odr_asan_gen_";
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000110static const char *const kSanCovGenPrefix = "__sancov_gen_";
Craig Topperd3a34f82013-07-16 01:17:10 +0000111static const char *const kAsanPoisonStackMemoryName =
112 "__asan_poison_stack_memory";
113static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +0000114 "__asan_unpoison_stack_memory";
Ryan Govostes653f9d02016-03-28 20:28:57 +0000115static const char *const kAsanGlobalsRegisteredFlagName =
116 "__asan_globals_registered";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000117
Kostya Serebryanyf3223822013-09-18 14:07:14 +0000118static const char *const kAsanOptionDetectUAR =
119 "__asan_option_detect_stack_use_after_return";
120
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000121static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
122static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
Yury Gribov98b18592015-05-28 07:51:49 +0000123
Kostya Serebryany874dae62012-07-16 16:15:40 +0000124// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
125static const size_t kNumberOfAccessSizes = 5;
126
Yury Gribov55441bb2014-11-21 10:29:50 +0000127static const unsigned kAllocaRzSize = 32;
Yury Gribov55441bb2014-11-21 10:29:50 +0000128
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000129// Command-line flags.
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000130static cl::opt<bool> ClEnableKasan(
131 "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
132 cl::Hidden, cl::init(false));
Yury Gribovd7731982015-11-11 10:36:49 +0000133static cl::opt<bool> ClRecover(
134 "asan-recover",
135 cl::desc("Enable recovery mode (continue-after-error)."),
136 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000137
138// This flag may need to be replaced with -f[no-]asan-reads.
139static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000140 cl::desc("instrument read instructions"),
141 cl::Hidden, cl::init(true));
142static cl::opt<bool> ClInstrumentWrites(
143 "asan-instrument-writes", cl::desc("instrument write instructions"),
144 cl::Hidden, cl::init(true));
145static cl::opt<bool> ClInstrumentAtomics(
146 "asan-instrument-atomics",
147 cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
148 cl::init(true));
149static cl::opt<bool> ClAlwaysSlowPath(
150 "asan-always-slow-path",
151 cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
152 cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000153// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000154// in any given BB. Normally, this should be set to unlimited (INT_MAX),
155// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
156// set it to 10000.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000157static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
158 "asan-max-ins-per-bb", cl::init(10000),
159 cl::desc("maximal number of instructions to instrument in any given BB"),
160 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000161// This flag may need to be replaced with -f[no]asan-stack.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000162static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
163 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000164static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000165 cl::desc("Check return-after-free"),
166 cl::Hidden, cl::init(true));
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000167static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
168 cl::desc("Check stack-use-after-scope"),
169 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000170// This flag may need to be replaced with -f[no]asan-globals.
171static cl::opt<bool> ClGlobals("asan-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000172 cl::desc("Handle global objects"), cl::Hidden,
173 cl::init(true));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000174static cl::opt<bool> ClInitializers("asan-initialization-order",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000175 cl::desc("Handle C++ initializer order"),
176 cl::Hidden, cl::init(true));
177static cl::opt<bool> ClInvalidPointerPairs(
178 "asan-detect-invalid-pointer-pair",
179 cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
180 cl::init(false));
181static cl::opt<unsigned> ClRealignStack(
182 "asan-realign-stack",
183 cl::desc("Realign stack to the value of this flag (power of two)"),
184 cl::Hidden, cl::init(32));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000185static cl::opt<int> ClInstrumentationWithCallsThreshold(
186 "asan-instrumentation-with-call-threshold",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000187 cl::desc(
188 "If the function being instrumented contains more than "
189 "this number of memory accesses, use callbacks instead of "
190 "inline checks (-1 means never use callbacks)."),
191 cl::Hidden, cl::init(7000));
Kostya Serebryany0c02d262014-04-16 12:12:19 +0000192static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000193 "asan-memory-access-callback-prefix",
194 cl::desc("Prefix for memory access callbacks"), cl::Hidden,
195 cl::init("__asan_"));
Yury Gribov55441bb2014-11-21 10:29:50 +0000196static cl::opt<bool> ClInstrumentAllocas("asan-instrument-allocas",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000197 cl::desc("instrument dynamic allocas"),
Alexey Samsonovf4fb5f52015-10-22 20:07:28 +0000198 cl::Hidden, cl::init(true));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000199static cl::opt<bool> ClSkipPromotableAllocas(
200 "asan-skip-promotable-allocas",
201 cl::desc("Do not instrument promotable allocas"), cl::Hidden,
202 cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000203
204// These flags allow to change the shadow mapping.
205// The shadow mapping looks like
206// Shadow = (Mem >> scale) + (1 << offset_log)
207static cl::opt<int> ClMappingScale("asan-mapping-scale",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000208 cl::desc("scale of asan shadow mapping"),
209 cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000210
211// Optimization flags. Not user visible, used mostly for testing
212// and benchmarking the tool.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000213static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
214 cl::Hidden, cl::init(true));
215static cl::opt<bool> ClOptSameTemp(
216 "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
217 cl::Hidden, cl::init(true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000218static cl::opt<bool> ClOptGlobals("asan-opt-globals",
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000219 cl::desc("Don't instrument scalar globals"),
220 cl::Hidden, cl::init(true));
221static cl::opt<bool> ClOptStack(
222 "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
223 cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000224
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000225static cl::opt<bool> ClDynamicAllocaStack(
226 "asan-stack-dynamic-alloca",
227 cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
Alexey Samsonov19763c42015-02-05 19:39:20 +0000228 cl::init(true));
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000229
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000230static cl::opt<uint32_t> ClForceExperiment(
231 "asan-force-experiment",
232 cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
233 cl::init(0));
234
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000235static cl::opt<bool>
236 ClUsePrivateAliasForGlobals("asan-use-private-alias",
237 cl::desc("Use private aliases for global"
238 " variables"),
239 cl::Hidden, cl::init(false));
240
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000241// Debug flags.
242static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
243 cl::init(0));
244static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
245 cl::Hidden, cl::init(0));
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000246static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
247 cl::desc("Debug func"));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000248static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
249 cl::Hidden, cl::init(-1));
250static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
251 cl::Hidden, cl::init(-1));
252
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000253STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
254STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000255STATISTIC(NumOptimizedAccessesToGlobalVar,
256 "Number of optimized accesses to global vars");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000257STATISTIC(NumOptimizedAccessesToStackVar,
258 "Number of optimized accesses to stack vars");
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000259
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000260namespace {
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000261/// Frontend-provided metadata for source location.
262struct LocationMetadata {
263 StringRef Filename;
264 int LineNo;
265 int ColumnNo;
266
267 LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
268
269 bool empty() const { return Filename.empty(); }
270
271 void parse(MDNode *MDN) {
272 assert(MDN->getNumOperands() == 3);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000273 MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
274 Filename = DIFilename->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000275 LineNo =
276 mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
277 ColumnNo =
278 mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000279 }
280};
281
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000282/// Frontend-provided metadata for global variables.
283class GlobalsMetadata {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000284 public:
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000285 struct Entry {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000286 Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000287 LocationMetadata SourceLoc;
288 StringRef Name;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000289 bool IsDynInit;
290 bool IsBlacklisted;
291 };
292
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000293 GlobalsMetadata() : inited_(false) {}
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000294
Keno Fischere03fae42015-12-05 14:42:34 +0000295 void reset() {
296 inited_ = false;
297 Entries.clear();
298 }
299
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000300 void init(Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000301 assert(!inited_);
302 inited_ = true;
303 NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000304 if (!Globals) return;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000305 for (auto MDN : Globals->operands()) {
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000306 // Metadata node contains the global and the fields of "Entry".
Alexey Samsonov15c96692014-07-12 00:42:52 +0000307 assert(MDN->getNumOperands() == 5);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000308 auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000309 // The optimizer may optimize away a global entirely.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000310 if (!GV) continue;
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000311 // We can already have an entry for GV if it was merged with another
312 // global.
313 Entry &E = Entries[GV];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000314 if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
315 E.SourceLoc.parse(Loc);
316 if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
317 E.Name = Name->getString();
318 ConstantInt *IsDynInit =
319 mdconst::extract<ConstantInt>(MDN->getOperand(3));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000320 E.IsDynInit |= IsDynInit->isOne();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000321 ConstantInt *IsBlacklisted =
322 mdconst::extract<ConstantInt>(MDN->getOperand(4));
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000323 E.IsBlacklisted |= IsBlacklisted->isOne();
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000324 }
325 }
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000326
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000327 /// Returns metadata entry for a given global.
328 Entry get(GlobalVariable *G) const {
329 auto Pos = Entries.find(G);
330 return (Pos != Entries.end()) ? Pos->second : Entry();
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000331 }
332
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000333 private:
Alexey Samsonov0c5ecdd2014-07-02 20:25:42 +0000334 bool inited_;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000335 DenseMap<GlobalVariable *, Entry> Entries;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000336};
337
Alexey Samsonov1345d352013-01-16 13:23:28 +0000338/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000339/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000340struct ShadowMapping {
341 int Scale;
342 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000343 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000344};
345
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000346static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
347 bool IsKasan) {
Evgeniy Stepanov5fe279e2015-10-08 21:21:24 +0000348 bool IsAndroid = TargetTriple.isAndroid();
Anna Zaks3b50e702016-02-02 22:05:07 +0000349 bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
Simon Pilgrima2794102014-11-22 19:12:10 +0000350 bool IsFreeBSD = TargetTriple.isOSFreeBSD();
351 bool IsLinux = TargetTriple.isOSLinux();
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000352 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
353 TargetTriple.getArch() == llvm::Triple::ppc64le;
Anna Zaks3b50e702016-02-02 22:05:07 +0000354 bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000355 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000356 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
357 TargetTriple.getArch() == llvm::Triple::mipsel;
Kostya Serebryany231bd082014-11-11 23:02:57 +0000358 bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
359 TargetTriple.getArch() == llvm::Triple::mips64el;
Renato Golinaf213722015-02-03 11:20:45 +0000360 bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000361 bool IsWindows = TargetTriple.isOSWindows();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000362
363 ShadowMapping Mapping;
364
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000365 if (LongSize == 32) {
Evgeniy Stepanov9cb08f82015-07-17 23:51:18 +0000366 // Android is always PIE, which means that the beginning of the address
367 // space is always available.
Evgeniy Stepanov4d81f862015-07-29 18:22:25 +0000368 if (IsAndroid)
369 Mapping.Offset = 0;
370 else if (IsMIPS32)
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000371 Mapping.Offset = kMIPS32_ShadowOffset32;
372 else if (IsFreeBSD)
373 Mapping.Offset = kFreeBSD_ShadowOffset32;
Alexander Potapenkoa51e4832014-04-23 17:14:45 +0000374 else if (IsIOS)
Anna Zaks3b50e702016-02-02 22:05:07 +0000375 // If we're targeting iOS and x86, the binary is built for iOS simulator.
376 Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
Timur Iskhodzhanov00ede842015-01-12 17:38:58 +0000377 else if (IsWindows)
378 Mapping.Offset = kWindowsShadowOffset32;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000379 else
380 Mapping.Offset = kDefaultShadowOffset32;
381 } else { // LongSize == 64
382 if (IsPPC64)
383 Mapping.Offset = kPPC64_ShadowOffset64;
384 else if (IsFreeBSD)
385 Mapping.Offset = kFreeBSD_ShadowOffset64;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000386 else if (IsLinux && IsX86_64) {
387 if (IsKasan)
388 Mapping.Offset = kLinuxKasan_ShadowOffset64;
389 else
390 Mapping.Offset = kSmallX86_64ShadowOffset;
391 } else if (IsMIPS64)
Kostya Serebryany231bd082014-11-11 23:02:57 +0000392 Mapping.Offset = kMIPS64_ShadowOffset64;
Anna Zaks3b50e702016-02-02 22:05:07 +0000393 else if (IsIOS)
394 // If we're targeting iOS and x86, the binary is built for iOS simulator.
395 Mapping.Offset = IsX86_64 ? kIOSSimShadowOffset64 : kIOSShadowOffset64;
Renato Golinaf213722015-02-03 11:20:45 +0000396 else if (IsAArch64)
397 Mapping.Offset = kAArch64_ShadowOffset64;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000398 else
399 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000400 }
401
402 Mapping.Scale = kDefaultShadowScale;
403 if (ClMappingScale) {
404 Mapping.Scale = ClMappingScale;
405 }
406
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000407 // OR-ing shadow offset if more efficient (at least on x86) if the offset
408 // is a power of two, but on ppc64 we have to use add since the shadow
409 // offset is not necessary 1/8-th of the address space.
Adhemerval Zanella35891fe2015-11-09 18:03:48 +0000410 Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64
411 && !(Mapping.Offset & (Mapping.Offset - 1));
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000412
Alexey Samsonov1345d352013-01-16 13:23:28 +0000413 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000414}
415
Alexey Samsonov1345d352013-01-16 13:23:28 +0000416static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000417 // Redzone used for stack and globals is at least 32 bytes.
418 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000419 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000420}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000421
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000422/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000423struct AddressSanitizer : public FunctionPass {
Yury Gribovd7731982015-11-11 10:36:49 +0000424 explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false)
425 : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
426 Recover(Recover || ClRecover) {
Yury Gribov3ae427d2014-12-01 08:47:58 +0000427 initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
428 }
Craig Topper3e4c6972014-03-05 09:10:37 +0000429 const char *getPassName() const override {
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000430 return "AddressSanitizerFunctionPass";
431 }
Yury Gribov3ae427d2014-12-01 08:47:58 +0000432 void getAnalysisUsage(AnalysisUsage &AU) const override {
433 AU.addRequired<DominatorTreeWrapperPass>();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000434 AU.addRequired<TargetLibraryInfoWrapperPass>();
Yury Gribov3ae427d2014-12-01 08:47:58 +0000435 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000436 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
437 Type *Ty = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000438 uint64_t SizeInBytes =
439 AI->getModule()->getDataLayout().getTypeAllocSize(Ty);
Anna Zaks8ed1d812015-02-27 03:12:36 +0000440 return SizeInBytes;
441 }
442 /// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000443 bool isInterestingAlloca(AllocaInst &AI);
Yury Gribov98b18592015-05-28 07:51:49 +0000444
445 // Check if we have dynamic alloca.
446 bool isDynamicAlloca(AllocaInst &AI) const {
447 return AI.isArrayAllocation() || !AI.isStaticAlloca();
448 }
449
Anna Zaks8ed1d812015-02-27 03:12:36 +0000450 /// If it is an interesting memory access, return the PointerOperand
451 /// and set IsWrite/Alignment. Otherwise return nullptr.
452 Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
Alexander Potapenkof90556e2015-06-12 11:27:06 +0000453 uint64_t *TypeSize, unsigned *Alignment);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000454 void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000455 bool UseCalls, const DataLayout &DL);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000456 void instrumentPointerComparisonOrSubtraction(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000457 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
458 Value *Addr, uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000459 Value *SizeArgument, bool UseCalls, uint32_t Exp);
460 void instrumentUnusualSizeOrAlignment(Instruction *I, Value *Addr,
461 uint32_t TypeSize, bool IsWrite,
462 Value *SizeArgument, bool UseCalls,
463 uint32_t Exp);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000464 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
465 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000466 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000467 bool IsWrite, size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000468 Value *SizeArgument, uint32_t Exp);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000469 void instrumentMemIntrinsic(MemIntrinsic *MI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000470 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Craig Topper3e4c6972014-03-05 09:10:37 +0000471 bool runOnFunction(Function &F) override;
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000472 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Reid Kleckner2f907552015-07-21 17:40:14 +0000473 void markEscapedLocalAllocas(Function &F);
Craig Topper3e4c6972014-03-05 09:10:37 +0000474 bool doInitialization(Module &M) override;
Keno Fischere03fae42015-12-05 14:42:34 +0000475 bool doFinalization(Module &M) override;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000476 static char ID; // Pass identification, replacement for typeid
477
Yury Gribov3ae427d2014-12-01 08:47:58 +0000478 DominatorTree &getDominatorTree() const { return *DT; }
479
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000480 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000481 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000482
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000483 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000484 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000485 bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
486 uint64_t TypeSize) const;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000487
Reid Kleckner2f907552015-07-21 17:40:14 +0000488 /// Helper to cleanup per-function state.
489 struct FunctionStateRAII {
490 AddressSanitizer *Pass;
491 FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
492 assert(Pass->ProcessedAllocas.empty() &&
493 "last pass forgot to clear cache");
494 }
495 ~FunctionStateRAII() { Pass->ProcessedAllocas.clear(); }
496 };
497
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000498 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000499 Triple TargetTriple;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000500 int LongSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000501 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000502 bool Recover;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000503 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000504 ShadowMapping Mapping;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000505 DominatorTree *DT;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000506 Function *AsanCtorFunction = nullptr;
507 Function *AsanInitFunction = nullptr;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000508 Function *AsanHandleNoReturnFunc;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000509 Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000510 // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
511 Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
512 Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
513 // This array is indexed by AccessIsWrite and Experiment.
514 Function *AsanErrorCallbackSized[2][2];
515 Function *AsanMemoryAccessCallbackSized[2][2];
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000516 Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000517 InlineAsm *EmptyAsm;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000518 GlobalsMetadata GlobalsMD;
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000519 DenseMap<AllocaInst *, bool> ProcessedAllocas;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000520
521 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000522};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000523
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000524class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000525 public:
Yury Gribovd7731982015-11-11 10:36:49 +0000526 explicit AddressSanitizerModule(bool CompileKernel = false,
527 bool Recover = false)
528 : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
529 Recover(Recover || ClRecover) {}
Craig Topper3e4c6972014-03-05 09:10:37 +0000530 bool runOnModule(Module &M) override;
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000531 static char ID; // Pass identification, replacement for typeid
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000532 const char *getPassName() const override { return "AddressSanitizerModule"; }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000533
Kostya Serebryany20a79972012-11-22 03:18:50 +0000534 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000535 void initializeCallbacks(Module &M);
536
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +0000537 bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000538 bool ShouldInstrumentGlobal(GlobalVariable *G);
Ryan Govostes653f9d02016-03-28 20:28:57 +0000539 bool ShouldUseMachOGlobalsSection() const;
Alexey Samsonov96e239f2014-05-29 00:51:15 +0000540 void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000541 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000542 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000543 return RedzoneSizeForScale(Mapping.Scale);
544 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000545
Alexey Samsonov4f319cc2014-07-02 16:54:41 +0000546 GlobalsMetadata GlobalsMD;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000547 bool CompileKernel;
Yury Gribovd7731982015-11-11 10:36:49 +0000548 bool Recover;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000549 Type *IntptrTy;
550 LLVMContext *C;
Kuba Brecka1001bb52014-12-05 22:19:18 +0000551 Triple TargetTriple;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000552 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000553 Function *AsanPoisonGlobals;
554 Function *AsanUnpoisonGlobals;
555 Function *AsanRegisterGlobals;
556 Function *AsanUnregisterGlobals;
Ryan Govostes653f9d02016-03-28 20:28:57 +0000557 Function *AsanRegisterImageGlobals;
558 Function *AsanUnregisterImageGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000559};
560
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000561// Stack poisoning does not play well with exception handling.
562// When an exception is thrown, we essentially bypass the code
563// that unpoisones the stack. This is why the run-time library has
564// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
565// stack in the interceptor. This however does not work inside the
566// actual function which catches the exception. Most likely because the
567// compiler hoists the load of the shadow value somewhere too high.
568// This causes asan to report a non-existing bug on 453.povray.
569// It sounds like an LLVM bug.
570struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
571 Function &F;
572 AddressSanitizer &ASan;
573 DIBuilder DIB;
574 LLVMContext *C;
575 Type *IntptrTy;
576 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000577 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000578
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000579 SmallVector<AllocaInst *, 16> AllocaVec;
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000580 SmallSetVector<AllocaInst *, 16> NonInstrumentedStaticAllocaVec;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000581 SmallVector<Instruction *, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000582 unsigned StackAlignment;
583
Kostya Serebryany6805de52013-09-10 13:16:56 +0000584 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000585 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000586 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
Yury Gribov98b18592015-05-28 07:51:49 +0000587 Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000588
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000589 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
590 struct AllocaPoisonCall {
591 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000592 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000593 uint64_t Size;
594 bool DoPoison;
595 };
596 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
597
Yury Gribov98b18592015-05-28 07:51:49 +0000598 SmallVector<AllocaInst *, 1> DynamicAllocaVec;
599 SmallVector<IntrinsicInst *, 1> StackRestoreVec;
600 AllocaInst *DynamicAllocaLayout = nullptr;
Reid Kleckner2f907552015-07-21 17:40:14 +0000601 IntrinsicInst *LocalEscapeCall = nullptr;
Yury Gribov55441bb2014-11-21 10:29:50 +0000602
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000603 // Maps Value to an AllocaInst from which the Value is originated.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000604 typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000605 AllocaForValueMapTy AllocaForValue;
606
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000607 bool HasNonEmptyInlineAsm = false;
608 bool HasReturnsTwiceCall = false;
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000609 std::unique_ptr<CallInst> EmptyInlineAsm;
610
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000611 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000612 : F(F),
613 ASan(ASan),
614 DIB(*F.getParent(), /*AllowUnresolved*/ false),
615 C(ASan.C),
616 IntptrTy(ASan.IntptrTy),
617 IntptrPtrTy(PointerType::get(IntptrTy, 0)),
618 Mapping(ASan.Mapping),
619 StackAlignment(1 << Mapping.Scale),
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000620 EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000621
622 bool runOnFunction() {
623 if (!ClStack) return false;
624 // Collect alloca, ret, lifetime instructions etc.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000625 for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
David Blaikieceec2bd2014-04-11 01:50:01 +0000626
Yury Gribov55441bb2014-11-21 10:29:50 +0000627 if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000628
629 initializeCallbacks(*F.getParent());
630
631 poisonStack();
632
633 if (ClDebugStack) {
634 DEBUG(dbgs() << F);
635 }
636 return true;
637 }
638
Yury Gribov55441bb2014-11-21 10:29:50 +0000639 // Finds all Alloca instructions and puts
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000640 // poisoned red zones around all of them.
641 // Then unpoison everything back before the function returns.
642 void poisonStack();
643
Yury Gribov98b18592015-05-28 07:51:49 +0000644 void createDynamicAllocasInitStorage();
645
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000646 // ----------------------- Visitors.
647 /// \brief Collect all Ret instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000648 void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000649
Yury Gribov98b18592015-05-28 07:51:49 +0000650 void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
651 Value *SavedStack) {
652 IRBuilder<> IRB(InstBefore);
Yury Gribov6ff0a662015-12-04 09:19:14 +0000653 Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
654 // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
655 // need to adjust extracted SP to compute the address of the most recent
656 // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
657 // this purpose.
658 if (!isa<ReturnInst>(InstBefore)) {
659 Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
660 InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
661 {IntptrTy});
662
663 Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
664
665 DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
666 DynamicAreaOffset);
667 }
668
Yury Gribov781bce22015-05-28 08:03:28 +0000669 IRB.CreateCall(AsanAllocasUnpoisonFunc,
Yury Gribov6ff0a662015-12-04 09:19:14 +0000670 {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
Yury Gribov98b18592015-05-28 07:51:49 +0000671 }
672
Yury Gribov55441bb2014-11-21 10:29:50 +0000673 // Unpoison dynamic allocas redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000674 void unpoisonDynamicAllocas() {
675 for (auto &Ret : RetVec)
676 unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
Yury Gribov55441bb2014-11-21 10:29:50 +0000677
Yury Gribov98b18592015-05-28 07:51:49 +0000678 for (auto &StackRestoreInst : StackRestoreVec)
679 unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
680 StackRestoreInst->getOperand(0));
Yury Gribov55441bb2014-11-21 10:29:50 +0000681 }
682
Yury Gribov55441bb2014-11-21 10:29:50 +0000683 // Deploy and poison redzones around dynamic alloca call. To do this, we
684 // should replace this call with another one with changed parameters and
685 // replace all its uses with new address, so
686 // addr = alloca type, old_size, align
687 // is replaced by
688 // new_size = (old_size + additional_size) * sizeof(type)
689 // tmp = alloca i8, new_size, max(align, 32)
690 // addr = tmp + 32 (first 32 bytes are for the left redzone).
691 // Additional_size is added to make new memory allocation contain not only
692 // requested memory, but also left, partial and right redzones.
Yury Gribov98b18592015-05-28 07:51:49 +0000693 void handleDynamicAllocaCall(AllocaInst *AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000694
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000695 /// \brief Collect Alloca instructions we want (and can) handle.
696 void visitAllocaInst(AllocaInst &AI) {
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000697 if (!ASan.isInterestingAlloca(AI)) {
Kuba Brecka8ec94ea2015-07-22 10:25:38 +0000698 if (AI.isStaticAlloca()) NonInstrumentedStaticAllocaVec.insert(&AI);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +0000699 return;
700 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000701
702 StackAlignment = std::max(StackAlignment, AI.getAlignment());
Yury Gribov98b18592015-05-28 07:51:49 +0000703 if (ASan.isDynamicAlloca(AI))
704 DynamicAllocaVec.push_back(&AI);
Yury Gribov55441bb2014-11-21 10:29:50 +0000705 else
706 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000707 }
708
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000709 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
710 /// errors.
711 void visitIntrinsicInst(IntrinsicInst &II) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000712 Intrinsic::ID ID = II.getIntrinsicID();
Yury Gribov98b18592015-05-28 07:51:49 +0000713 if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
Reid Kleckner2f907552015-07-21 17:40:14 +0000714 if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
Kostya Serebryanya83bfea2016-04-20 20:02:58 +0000715 if (!ClUseAfterScope) return;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000716 if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000717 return;
718 // Found lifetime intrinsic, add ASan instrumentation if necessary.
719 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
720 // If size argument is undefined, don't do anything.
721 if (Size->isMinusOne()) return;
722 // Check that size doesn't saturate uint64_t and can
723 // be stored in IntptrTy.
724 const uint64_t SizeValue = Size->getValue().getLimitedValue();
725 if (SizeValue == ~0ULL ||
726 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
727 return;
728 // Find alloca instruction that corresponds to llvm.lifetime argument.
729 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
730 if (!AI) return;
731 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000732 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000733 AllocaPoisonCallVec.push_back(APC);
734 }
735
Alexey Samsonov869a5ff2015-07-29 19:36:08 +0000736 void visitCallSite(CallSite CS) {
737 Instruction *I = CS.getInstruction();
738 if (CallInst *CI = dyn_cast<CallInst>(I)) {
739 HasNonEmptyInlineAsm |=
740 CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
741 HasReturnsTwiceCall |= CI->canReturnTwice();
742 }
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000743 }
744
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000745 // ---------------------- Helpers.
746 void initializeCallbacks(Module &M);
747
Yury Gribov3ae427d2014-12-01 08:47:58 +0000748 bool doesDominateAllExits(const Instruction *I) const {
749 for (auto Ret : RetVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000750 if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
Yury Gribov3ae427d2014-12-01 08:47:58 +0000751 }
752 return true;
753 }
754
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000755 /// Finds alloca where the value comes from.
756 AllocaInst *findAllocaForValue(Value *V);
Craig Topper3af97222014-08-27 05:25:00 +0000757 void poisonRedZones(ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000758 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000759 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000760
761 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
762 int Size);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +0000763 Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
764 bool Dynamic);
765 PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
766 Instruction *ThenTerm, Value *ValueIfFalse);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000767};
768
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000769} // anonymous namespace
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000770
771char AddressSanitizer::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000772INITIALIZE_PASS_BEGIN(
773 AddressSanitizer, "asan",
774 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
775 false)
Yury Gribov3ae427d2014-12-01 08:47:58 +0000776INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Keno Fischera010cfa2015-10-20 10:13:55 +0000777INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000778INITIALIZE_PASS_END(
779 AddressSanitizer, "asan",
780 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
781 false)
Yury Gribovd7731982015-11-11 10:36:49 +0000782FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
783 bool Recover) {
784 assert(!CompileKernel || Recover);
785 return new AddressSanitizer(CompileKernel, Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000786}
787
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000788char AddressSanitizerModule::ID = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000789INITIALIZE_PASS(
790 AddressSanitizerModule, "asan-module",
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000791 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000792 "ModulePass",
793 false, false)
Yury Gribovd7731982015-11-11 10:36:49 +0000794ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
795 bool Recover) {
796 assert(!CompileKernel || Recover);
797 return new AddressSanitizerModule(CompileKernel, Recover);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000798}
799
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000800static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000801 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000802 assert(Res < kNumberOfAccessSizes);
803 return Res;
804}
805
Bill Wendling58f8cef2013-08-06 22:52:42 +0000806// \brief Create a constant for Str so that we can pass it to the run-time lib.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000807static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
808 bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000809 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000810 // We use private linkage for module-local strings. If they can be merged
811 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000812 GlobalVariable *GV =
813 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000814 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000815 if (AllowMerging) GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000816 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
817 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000818}
819
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +0000820/// \brief Create a global describing a source location.
821static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
822 LocationMetadata MD) {
823 Constant *LocData[] = {
824 createPrivateGlobalForString(M, MD.Filename, true),
825 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
826 ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
827 };
828 auto LocStruct = ConstantStruct::getAnon(LocData);
829 auto GV = new GlobalVariable(M, LocStruct->getType(), true,
830 GlobalValue::PrivateLinkage, LocStruct,
831 kAsanGenPrefix);
832 GV->setUnnamedAddr(true);
833 return GV;
834}
835
Kostya Serebryany139a9372012-11-20 14:16:08 +0000836static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
Kostya Serebryanycb45b122014-11-19 00:22:58 +0000837 return G->getName().find(kAsanGenPrefix) == 0 ||
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +0000838 G->getName().find(kSanCovGenPrefix) == 0 ||
839 G->getName().find(kODRGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000840}
841
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000842Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
843 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000844 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000845 if (Mapping.Offset == 0) return Shadow;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000846 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000847 if (Mapping.OrShadowOffset)
848 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
849 else
850 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000851}
852
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000853// Instrument memset/memmove/memcpy
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000854void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
855 IRBuilder<> IRB(MI);
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000856 if (isa<MemTransferInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000857 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000858 isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
David Blaikieff6409d2015-05-18 22:13:54 +0000859 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
860 IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
861 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000862 } else if (isa<MemSetInst>(MI)) {
David Blaikieff6409d2015-05-18 22:13:54 +0000863 IRB.CreateCall(
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000864 AsanMemset,
David Blaikieff6409d2015-05-18 22:13:54 +0000865 {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
866 IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
867 IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000868 }
Kostya Serebryany94c81ca2014-04-21 11:50:42 +0000869 MI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000870}
871
Anna Zaks8ed1d812015-02-27 03:12:36 +0000872/// Check if we want (and can) handle this alloca.
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000873bool AddressSanitizer::isInterestingAlloca(AllocaInst &AI) {
874 auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
875
876 if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
877 return PreviouslySeenAllocaInfo->getSecond();
878
Yury Gribov98b18592015-05-28 07:51:49 +0000879 bool IsInteresting =
880 (AI.getAllocatedType()->isSized() &&
881 // alloca() may be called with 0 size, ignore it.
882 getAllocaSizeInBytes(&AI) > 0 &&
883 // We are only interested in allocas not promotable to registers.
884 // Promotable allocas are common under -O0.
Alexey Samsonov55fda1b2015-11-05 21:18:41 +0000885 (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
886 // inalloca allocas are not treated as static, and we don't want
887 // dynamic alloca instrumentation for them as well.
888 !AI.isUsedWithInAlloca());
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000889
890 ProcessedAllocas[&AI] = IsInteresting;
891 return IsInteresting;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000892}
893
894/// If I is an interesting memory access, return the PointerOperand
895/// and set IsWrite/Alignment. Otherwise return nullptr.
896Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
897 bool *IsWrite,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000898 uint64_t *TypeSize,
Anna Zaksbf28d3a2015-03-27 18:52:01 +0000899 unsigned *Alignment) {
Alexey Samsonov535b6f92014-07-17 18:48:12 +0000900 // Skip memory accesses inserted by another instrumentation.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000901 if (I->getMetadata("nosanitize")) return nullptr;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000902
903 Value *PtrOperand = nullptr;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000904 const DataLayout &DL = I->getModule()->getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000905 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000906 if (!ClInstrumentReads) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000907 *IsWrite = false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000908 *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000909 *Alignment = LI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000910 PtrOperand = LI->getPointerOperand();
911 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000912 if (!ClInstrumentWrites) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000913 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000914 *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000915 *Alignment = SI->getAlignment();
Anna Zaks8ed1d812015-02-27 03:12:36 +0000916 PtrOperand = SI->getPointerOperand();
917 } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000918 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000919 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000920 *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000921 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000922 PtrOperand = RMW->getPointerOperand();
923 } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
Craig Topperf40110f2014-04-25 05:29:35 +0000924 if (!ClInstrumentAtomics) return nullptr;
Kostya Serebryany90241602012-05-30 09:04:06 +0000925 *IsWrite = true;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000926 *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000927 *Alignment = 0;
Anna Zaks8ed1d812015-02-27 03:12:36 +0000928 PtrOperand = XCHG->getPointerOperand();
Kostya Serebryany90241602012-05-30 09:04:06 +0000929 }
Anna Zaks8ed1d812015-02-27 03:12:36 +0000930
931 // Treat memory accesses to promotable allocas as non-interesting since they
932 // will not cause memory violations. This greatly speeds up the instrumented
933 // executable at -O0.
934 if (ClSkipPromotableAllocas)
935 if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
936 return isInterestingAlloca(*AI) ? AI : nullptr;
937
938 return PtrOperand;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000939}
940
Kostya Serebryany796f6552014-02-27 12:45:36 +0000941static bool isPointerOperand(Value *V) {
942 return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
943}
944
945// This is a rough heuristic; it may cause both false positives and
946// false negatives. The proper implementation requires cooperation with
947// the frontend.
948static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
949 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000950 if (!Cmp->isRelational()) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000951 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000952 if (BO->getOpcode() != Instruction::Sub) return false;
Kostya Serebryany796f6552014-02-27 12:45:36 +0000953 } else {
954 return false;
955 }
Alexey Samsonov145b0fd2015-10-26 18:06:40 +0000956 return isPointerOperand(I->getOperand(0)) &&
957 isPointerOperand(I->getOperand(1));
Kostya Serebryany796f6552014-02-27 12:45:36 +0000958}
959
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000960bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
961 // If a global variable does not have dynamic initialization we don't
962 // have to instrument it. However, if a global does not have initializer
963 // at all, we assume it has dynamic initializer (in other TU).
Alexey Samsonov08f022a2014-07-11 22:36:02 +0000964 return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000965}
966
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000967void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
968 Instruction *I) {
Kostya Serebryany796f6552014-02-27 12:45:36 +0000969 IRBuilder<> IRB(I);
970 Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
971 Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
972 for (int i = 0; i < 2; i++) {
973 if (Param[i]->getType()->isPointerTy())
974 Param[i] = IRB.CreatePointerCast(Param[i], IntptrTy);
975 }
David Blaikieff6409d2015-05-18 22:13:54 +0000976 IRB.CreateCall(F, Param);
Kostya Serebryany796f6552014-02-27 12:45:36 +0000977}
978
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000979void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000980 Instruction *I, bool UseCalls,
981 const DataLayout &DL) {
Axel Naumann4a127062012-09-17 14:20:57 +0000982 bool IsWrite = false;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +0000983 unsigned Alignment = 0;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000984 uint64_t TypeSize = 0;
985 Value *Addr = isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment);
Kostya Serebryany90241602012-05-30 09:04:06 +0000986 assert(Addr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +0000987
Dmitry Vyukov618d5802015-03-17 16:59:19 +0000988 // Optimization experiments.
989 // The experiments can be used to evaluate potential optimizations that remove
990 // instrumentation (assess false negatives). Instead of completely removing
991 // some instrumentation, you set Exp to a non-zero value (mask of optimization
992 // experiments that want to remove instrumentation of this instruction).
993 // If Exp is non-zero, this pass will emit special calls into runtime
994 // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
995 // make runtime terminate the program in a special way (with a different
996 // exit status). Then you run the new compiler on a buggy corpus, collect
997 // the special terminations (ideally, you don't see them at all -- no false
998 // negatives) and make the decision on the optimization.
999 uint32_t Exp = ClForceExperiment;
1000
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001001 if (ClOpt && ClOptGlobals) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001002 // If initialization order checking is disabled, a simple access to a
1003 // dynamically initialized global is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001004 GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001005 if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001006 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1007 NumOptimizedAccessesToGlobalVar++;
1008 return;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001009 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001010 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001011
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001012 if (ClOpt && ClOptStack) {
1013 // A direct inbounds access to a stack variable is always valid.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001014 if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001015 isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1016 NumOptimizedAccessesToStackVar++;
1017 return;
1018 }
1019 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001020
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +00001021 if (IsWrite)
1022 NumInstrumentedWrites++;
1023 else
1024 NumInstrumentedReads++;
1025
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001026 unsigned Granularity = 1 << Mapping.Scale;
1027 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1028 // if the data is properly aligned.
1029 if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1030 TypeSize == 128) &&
1031 (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001032 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, nullptr, UseCalls,
1033 Exp);
1034 instrumentUnusualSizeOrAlignment(I, Addr, TypeSize, IsWrite, nullptr,
1035 UseCalls, Exp);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001036}
1037
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001038Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1039 Value *Addr, bool IsWrite,
1040 size_t AccessSizeIndex,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001041 Value *SizeArgument,
1042 uint32_t Exp) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001043 IRBuilder<> IRB(InsertBefore);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001044 Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1045 CallInst *Call = nullptr;
1046 if (SizeArgument) {
1047 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001048 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1049 {Addr, SizeArgument});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001050 else
David Blaikieff6409d2015-05-18 22:13:54 +00001051 Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1052 {Addr, SizeArgument, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001053 } else {
1054 if (Exp == 0)
1055 Call =
1056 IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1057 else
David Blaikieff6409d2015-05-18 22:13:54 +00001058 Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1059 {Addr, ExpVal});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001060 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001061
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001062 // We don't do Call->setDoesNotReturn() because the BB already has
1063 // UnreachableInst at the end.
1064 // This EmptyAsm is required to avoid callback merge.
David Blaikieff6409d2015-05-18 22:13:54 +00001065 IRB.CreateCall(EmptyAsm, {});
Kostya Serebryany3411f2e2012-01-06 18:09:21 +00001066 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001067}
1068
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +00001069Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001070 Value *ShadowValue,
1071 uint32_t TypeSize) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001072 size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +00001073 // Addr & (Granularity - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001074 Value *LastAccessedByte =
1075 IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
Kostya Serebryany874dae62012-07-16 16:15:40 +00001076 // (Addr & (Granularity - 1)) + size - 1
1077 if (TypeSize / 8 > 1)
1078 LastAccessedByte = IRB.CreateAdd(
1079 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1080 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001081 LastAccessedByte =
1082 IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001083 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1084 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1085}
1086
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001087void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001088 Instruction *InsertBefore, Value *Addr,
1089 uint32_t TypeSize, bool IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001090 Value *SizeArgument, bool UseCalls,
1091 uint32_t Exp) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001092 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001093 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001094 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1095
1096 if (UseCalls) {
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001097 if (Exp == 0)
1098 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1099 AddrLong);
1100 else
David Blaikieff6409d2015-05-18 22:13:54 +00001101 IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1102 {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Kostya Serebryany0c02d262014-04-16 12:12:19 +00001103 return;
1104 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001105
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001106 Type *ShadowTy =
1107 IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001108 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1109 Value *ShadowPtr = memToShadow(AddrLong, IRB);
1110 Value *CmpVal = Constant::getNullValue(ShadowTy);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001111 Value *ShadowValue =
1112 IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001113
1114 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001115 size_t Granularity = 1ULL << Mapping.Scale;
Craig Topperf40110f2014-04-25 05:29:35 +00001116 TerminatorInst *CrashTerm = nullptr;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001117
Kostya Serebryany1e575ab2012-08-15 08:58:58 +00001118 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Kostya Serebryanyad238522014-09-02 21:46:51 +00001119 // We use branch weights for the slow path check, to indicate that the slow
1120 // path is rarely taken. This seems to be the case for SPEC benchmarks.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001121 TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1122 Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
Benjamin Kramer619c4e52015-04-10 11:24:51 +00001123 assert(cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001124 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +00001125 IRB.SetInsertPoint(CheckTerm);
1126 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Yury Gribovd7731982015-11-11 10:36:49 +00001127 if (Recover) {
1128 CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1129 } else {
1130 BasicBlock *CrashBlock =
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001131 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Yury Gribovd7731982015-11-11 10:36:49 +00001132 CrashTerm = new UnreachableInst(*C, CrashBlock);
1133 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1134 ReplaceInstWithInst(CheckTerm, NewTerm);
1135 }
Kostya Serebryany874dae62012-07-16 16:15:40 +00001136 } else {
Yury Gribovd7731982015-11-11 10:36:49 +00001137 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001138 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001139
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001140 Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001141 AccessSizeIndex, SizeArgument, Exp);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +00001142 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001143}
1144
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001145// Instrument unusual size or unusual alignment.
1146// We can not do it with a single check, so we do 1-byte check for the first
1147// and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1148// to report the actual access size.
1149void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1150 Instruction *I, Value *Addr, uint32_t TypeSize, bool IsWrite,
1151 Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1152 IRBuilder<> IRB(I);
1153 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1154 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1155 if (UseCalls) {
1156 if (Exp == 0)
David Blaikieff6409d2015-05-18 22:13:54 +00001157 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1158 {AddrLong, Size});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001159 else
David Blaikieff6409d2015-05-18 22:13:54 +00001160 IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1161 {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001162 } else {
1163 Value *LastByte = IRB.CreateIntToPtr(
1164 IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1165 Addr->getType());
1166 instrumentAddress(I, I, Addr, 8, IsWrite, Size, false, Exp);
1167 instrumentAddress(I, I, LastByte, 8, IsWrite, Size, false, Exp);
1168 }
1169}
1170
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001171void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1172 GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001173 // Set up the arguments to our poison/unpoison functions.
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001174 IRBuilder<> IRB(&GlobalInit.front(),
1175 GlobalInit.front().getFirstInsertionPt());
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001176
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001177 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001178 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1179 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001180
1181 // Add calls to unpoison all globals before each return instruction.
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001182 for (auto &BB : GlobalInit.getBasicBlockList())
1183 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001184 CallInst::Create(AsanUnpoisonGlobals, "", RI);
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001185}
1186
1187void AddressSanitizerModule::createInitializerPoisonCalls(
1188 Module &M, GlobalValue *ModuleName) {
1189 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1190
1191 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1192 for (Use &OP : CA->operands()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001193 if (isa<ConstantAggregateZero>(OP)) continue;
Alexey Samsonov96e239f2014-05-29 00:51:15 +00001194 ConstantStruct *CS = cast<ConstantStruct>(OP);
1195
1196 // Must have a function or null ptr.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001197 if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
Kostya Serebryany34ddf872014-09-24 22:41:55 +00001198 if (F->getName() == kAsanModuleCtorName) continue;
1199 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1200 // Don't instrument CTORs that will run before asan.module_ctor.
1201 if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1202 poisonOneInitializer(*F, ModuleName);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001203 }
1204 }
1205}
1206
Kostya Serebryanydfe9e792012-11-28 10:31:36 +00001207bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001208 Type *Ty = G->getValueType();
Kostya Serebryany20343352012-10-17 13:40:06 +00001209 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001210
Alexey Samsonov08f022a2014-07-11 22:36:02 +00001211 if (GlobalsMD.get(G).IsBlacklisted) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001212 if (!Ty->isSized()) return false;
1213 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +00001214 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001215 // Touch only those globals that will not be defined in other modules.
Timur Iskhodzhanove40fb372014-07-09 08:35:33 +00001216 // Don't handle ODR linkage types and COMDATs since other modules may be built
1217 // without ASan.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001218 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1219 G->getLinkage() != GlobalVariable::PrivateLinkage &&
1220 G->getLinkage() != GlobalVariable::InternalLinkage)
1221 return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001222 if (G->hasComdat()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001223 // Two problems with thread-locals:
1224 // - The address of the main thread's copy can't be computed at link-time.
1225 // - Need to poison all copies, not just the main thread's one.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001226 if (G->isThreadLocal()) return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001227 // For now, just ignore this Global if the alignment is large.
1228 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001229
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001230 if (G->hasSection()) {
1231 StringRef Section(G->getSection());
Kuba Brecka086e34b2014-12-05 21:32:46 +00001232
Anna Zaks11904602015-06-09 00:58:08 +00001233 // Globals from llvm.metadata aren't emitted, do not instrument them.
1234 if (Section == "llvm.metadata") return false;
Anna Zaks785c0752015-06-25 23:35:48 +00001235 // Do not instrument globals from special LLVM sections.
Anna Zaks40148f12016-02-24 22:12:18 +00001236 if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
Anna Zaks11904602015-06-09 00:58:08 +00001237
Alexey Samsonovc1603b62015-09-15 23:05:48 +00001238 // Do not instrument function pointers to initialization and termination
1239 // routines: dynamic linker will not properly handle redzones.
1240 if (Section.startswith(".preinit_array") ||
1241 Section.startswith(".init_array") ||
1242 Section.startswith(".fini_array")) {
1243 return false;
1244 }
1245
Anna Zaks11904602015-06-09 00:58:08 +00001246 // Callbacks put into the CRT initializer/terminator sections
1247 // should not be instrumented.
1248 // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1249 // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1250 if (Section.startswith(".CRT")) {
1251 DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1252 return false;
1253 }
1254
Kuba Brecka1001bb52014-12-05 22:19:18 +00001255 if (TargetTriple.isOSBinFormatMachO()) {
1256 StringRef ParsedSegment, ParsedSection;
1257 unsigned TAA = 0, StubSize = 0;
1258 bool TAAParsed;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001259 std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1260 Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
Davide Italianoc807f482015-11-19 21:50:08 +00001261 assert(ErrorCode.empty() && "Invalid section specifier.");
Kuba Brecka1001bb52014-12-05 22:19:18 +00001262
1263 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1264 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1265 // them.
1266 if (ParsedSegment == "__OBJC" ||
1267 (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1268 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1269 return false;
1270 }
1271 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1272 // Constant CFString instances are compiled in the following way:
1273 // -- the string buffer is emitted into
1274 // __TEXT,__cstring,cstring_literals
1275 // -- the constant NSConstantString structure referencing that buffer
1276 // is placed into __DATA,__cfstring
1277 // Therefore there's no point in placing redzones into __DATA,__cfstring.
1278 // Moreover, it causes the linker to crash on OS X 10.7
1279 if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1280 DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1281 return false;
1282 }
1283 // The linker merges the contents of cstring_literals and removes the
1284 // trailing zeroes.
1285 if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1286 DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1287 return false;
1288 }
1289 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001290 }
1291
1292 return true;
1293}
1294
Ryan Govostes653f9d02016-03-28 20:28:57 +00001295// On Mach-O platforms, we emit global metadata in a separate section of the
1296// binary in order to allow the linker to properly dead strip. This is only
1297// supported on recent versions of ld64.
1298bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1299 if (!TargetTriple.isOSBinFormatMachO())
1300 return false;
1301
1302 if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1303 return true;
1304 if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1305 return true;
1306 if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1307 return true;
1308
1309 return false;
1310}
1311
Alexey Samsonov788381b2012-12-25 12:28:20 +00001312void AddressSanitizerModule::initializeCallbacks(Module &M) {
1313 IRBuilder<> IRB(*C);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001314
Alexey Samsonov788381b2012-12-25 12:28:20 +00001315 // Declare our poisoning and unpoisoning functions.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001316 AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001317 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001318 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001319 AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001320 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001321 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001322
Alexey Samsonov788381b2012-12-25 12:28:20 +00001323 // Declare functions that register/unregister globals.
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001324 AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001325 kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001326 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001327 AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001328 M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1329 IntptrTy, IntptrTy, nullptr));
Alexey Samsonov788381b2012-12-25 12:28:20 +00001330 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
Ryan Govostes653f9d02016-03-28 20:28:57 +00001331
1332 // Declare the functions that find globals in a shared object and then invoke
1333 // the (un)register function on them.
1334 AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1335 M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1336 IRB.getVoidTy(), IntptrTy, nullptr));
1337 AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1338
1339 AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1340 M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1341 IRB.getVoidTy(), IntptrTy, nullptr));
1342 AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
Alexey Samsonov788381b2012-12-25 12:28:20 +00001343}
1344
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001345// This function replaces all global variables with new variables that have
1346// trailing redzones. It also creates a function that poisons
1347// redzones and inserts this function into llvm.global_ctors.
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001348bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001349 GlobalsMD.init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001350
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001351 SmallVector<GlobalVariable *, 16> GlobalsToChange;
1352
Alexey Samsonova02e6642014-05-29 18:40:48 +00001353 for (auto &G : M.globals()) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001354 if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001355 }
1356
1357 size_t n = GlobalsToChange.size();
1358 if (n == 0) return false;
1359
1360 // A global is described by a structure
1361 // size_t beg;
1362 // size_t size;
1363 // size_t size_with_redzone;
1364 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001365 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001366 // size_t has_dynamic_init;
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001367 // void *source_location;
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001368 // size_t odr_indicator;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001369 // We initialize an array of such structures and pass it to a run-time call.
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001370 StructType *GlobalStructTy =
1371 StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001372 IntptrTy, IntptrTy, IntptrTy, nullptr);
Rafael Espindola44fee4e2013-10-01 13:32:03 +00001373 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +00001374
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001375 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001376
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001377 // We shouldn't merge same module names, as this string serves as unique
1378 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001379 GlobalVariable *ModuleName = createPrivateGlobalForString(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001380 M, M.getModuleIdentifier(), /*AllowMerging*/ false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001381
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001382 auto &DL = M.getDataLayout();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001383 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +00001384 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001385 GlobalVariable *G = GlobalsToChange[i];
Alexey Samsonov15c96692014-07-12 00:42:52 +00001386
1387 auto MD = GlobalsMD.get(G);
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001388 StringRef NameForGlobal = G->getName();
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001389 // Create string holding the global name (use global name from metadata
1390 // if it's available, otherwise just write the name of global variable).
1391 GlobalVariable *Name = createPrivateGlobalForString(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001392 M, MD.Name.empty() ? NameForGlobal : MD.Name,
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001393 /*AllowMerging*/ true);
Alexey Samsonov15c96692014-07-12 00:42:52 +00001394
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001395 Type *Ty = G->getValueType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001396 uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001397 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +00001398 // MinRZ <= RZ <= kMaxGlobalRedzone
1399 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001400 uint64_t RZ = std::max(
1401 MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
Kostya Serebryany87191f62013-01-24 10:35:40 +00001402 uint64_t RightRedzoneSize = RZ;
1403 // Round up to MinRZ
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001404 if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001405 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001406 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1407
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001408 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001409 Constant *NewInitializer =
1410 ConstantStruct::get(NewTy, G->getInitializer(),
1411 Constant::getNullValue(RightRedZoneTy), nullptr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001412
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001413 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +00001414 GlobalValue::LinkageTypes Linkage = G->getLinkage();
1415 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1416 Linkage = GlobalValue::InternalLinkage;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001417 GlobalVariable *NewGlobal =
1418 new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1419 "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001420 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001421 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001422
1423 Value *Indices2[2];
1424 Indices2[0] = IRB.getInt32(0);
1425 Indices2[1] = IRB.getInt32(0);
1426
1427 G->replaceAllUsesWith(
David Blaikie4a2e73b2015-04-02 18:55:32 +00001428 ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001429 NewGlobal->takeName(G);
1430 G->eraseFromParent();
1431
Alexey Samsonovd9ad5ce2014-08-02 00:35:50 +00001432 Constant *SourceLoc;
1433 if (!MD.SourceLoc.empty()) {
1434 auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1435 SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1436 } else {
1437 SourceLoc = ConstantInt::get(IntptrTy, 0);
1438 }
1439
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001440 Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1441 GlobalValue *InstrumentedGlobal = NewGlobal;
1442
1443 bool CanUsePrivateAliases = TargetTriple.isOSBinFormatELF();
1444 if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1445 // Create local alias for NewGlobal to avoid crash on ODR between
1446 // instrumented and non-instrumented libraries.
1447 auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1448 NameForGlobal + M.getName(), NewGlobal);
1449
1450 // With local aliases, we need to provide another externally visible
1451 // symbol __odr_asan_XXX to detect ODR violation.
1452 auto *ODRIndicatorSym =
1453 new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1454 Constant::getNullValue(IRB.getInt8Ty()),
1455 kODRGenPrefix + NameForGlobal, nullptr,
1456 NewGlobal->getThreadLocalMode());
1457
1458 // Set meaningful attributes for indicator symbol.
1459 ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1460 ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1461 ODRIndicatorSym->setAlignment(1);
1462 ODRIndicator = ODRIndicatorSym;
1463 InstrumentedGlobal = GA;
1464 }
1465
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001466 Initializers[i] = ConstantStruct::get(
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001467 GlobalStructTy,
1468 ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001469 ConstantInt::get(IntptrTy, SizeInBytes),
1470 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1471 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001472 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Maxim Ostapenkob1e3f602016-02-08 08:30:57 +00001473 ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1474 ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001475
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001476 if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001477
Kostya Serebryany20343352012-10-17 13:40:06 +00001478 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001479 }
1480
Ryan Govostes653f9d02016-03-28 20:28:57 +00001481
1482 GlobalVariable *AllGlobals = nullptr;
1483 GlobalVariable *RegisteredFlag = nullptr;
1484
1485 // On recent Mach-O platforms, we emit the global metadata in a way that
1486 // allows the linker to properly strip dead globals.
1487 if (ShouldUseMachOGlobalsSection()) {
1488 // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1489 // to look up the loaded image that contains it. Second, we can store in it
1490 // whether registration has already occurred, to prevent duplicate
1491 // registration.
1492 //
1493 // Common linkage allows us to coalesce needles defined in each object
1494 // file so that there's only one per shared library.
1495 RegisteredFlag = new GlobalVariable(
1496 M, IntptrTy, false, GlobalVariable::CommonLinkage,
1497 ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1498
1499 // We also emit a structure which binds the liveness of the global
1500 // variable to the metadata struct.
1501 StructType *LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1502
1503 for (size_t i = 0; i < n; i++) {
1504 GlobalVariable *Metadata = new GlobalVariable(
1505 M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1506 Initializers[i], "");
1507 Metadata->setSection("__DATA,__asan_globals,regular");
1508 Metadata->setAlignment(1); // don't leave padding in between
1509
1510 auto LivenessBinder = ConstantStruct::get(LivenessTy,
1511 Initializers[i]->getAggregateElement(0u),
1512 ConstantExpr::getPointerCast(Metadata, IntptrTy),
1513 nullptr);
1514 GlobalVariable *Liveness = new GlobalVariable(
1515 M, LivenessTy, false, GlobalVariable::InternalLinkage,
1516 LivenessBinder, "");
1517 Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1518 }
1519 } else {
1520 // On all other platfoms, we just emit an array of global metadata
1521 // structures.
1522 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1523 AllGlobals = new GlobalVariable(
1524 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1525 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1526 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001527
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001528 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove595e1a2014-06-13 17:53:44 +00001529 if (HasDynamicallyInitializedGlobals)
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001530 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001531
Ryan Govostes653f9d02016-03-28 20:28:57 +00001532 // Create a call to register the globals with the runtime.
1533 if (ShouldUseMachOGlobalsSection()) {
1534 IRB.CreateCall(AsanRegisterImageGlobals,
1535 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1536 } else {
1537 IRB.CreateCall(AsanRegisterGlobals,
1538 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1539 ConstantInt::get(IntptrTy, n)});
1540 }
1541
1542 // We also need to unregister globals at the end, e.g., when a shared library
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001543 // gets closed.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001544 Function *AsanDtorFunction =
1545 Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1546 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001547 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1548 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Ryan Govostes653f9d02016-03-28 20:28:57 +00001549
1550 if (ShouldUseMachOGlobalsSection()) {
1551 IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1552 {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1553 } else {
1554 IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1555 {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1556 ConstantInt::get(IntptrTy, n)});
1557 }
1558
Alexey Samsonov1f647502014-05-29 01:10:14 +00001559 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001560
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001561 DEBUG(dbgs() << M);
1562 return true;
1563}
1564
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001565bool AddressSanitizerModule::runOnModule(Module &M) {
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001566 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001567 int LongSize = M.getDataLayout().getPointerSizeInBits();
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001568 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001569 TargetTriple = Triple(M.getTargetTriple());
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001570 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001571 initializeCallbacks(M);
1572
1573 bool Changed = false;
1574
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001575 // TODO(glider): temporarily disabled globals instrumentation for KASan.
1576 if (ClGlobals && !CompileKernel) {
1577 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1578 assert(CtorFunc);
1579 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1580 Changed |= InstrumentGlobals(IRB, M);
1581 }
Evgeniy Stepanov19f75fc2014-06-03 14:16:00 +00001582
1583 return Changed;
1584}
1585
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001586void AddressSanitizer::initializeCallbacks(Module &M) {
1587 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001588 // Create __asan_report* callbacks.
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001589 // IsWrite, TypeSize and Exp are encoded in the function name.
1590 for (int Exp = 0; Exp < 2; Exp++) {
1591 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1592 const std::string TypeStr = AccessIsWrite ? "store" : "load";
1593 const std::string ExpStr = Exp ? "exp_" : "";
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001594 const std::string SuffixStr = CompileKernel ? "N" : "_n";
Yury Gribovd7731982015-11-11 10:36:49 +00001595 const std::string EndingStr = Recover ? "_noabort" : "";
Craig Toppere3dcce92015-08-01 22:20:21 +00001596 Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001597 AsanErrorCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001598 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001599 kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001600 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1601 AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001602 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001603 ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001604 IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1605 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1606 AccessSizeIndex++) {
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00001607 const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001608 AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001609 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Yury Gribovd7731982015-11-11 10:36:49 +00001610 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001611 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001612 AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001613 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001614 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1615 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
Dmitry Vyukov618d5802015-03-17 16:59:19 +00001616 }
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001617 }
1618 }
Kostya Serebryany86332c02014-04-21 07:10:43 +00001619
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001620 const std::string MemIntrinCallbackPrefix =
1621 CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001622 AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001623 MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001624 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001625 AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001626 MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001627 IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001628 AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001629 MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001630 IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001631
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001632 AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001633 M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
Kostya Serebryany4f8f0c52014-10-27 18:13:56 +00001634
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001635 AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001636 kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001637 AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
Reid Kleckner971c3ea2014-11-13 22:55:19 +00001638 kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001639 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1640 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1641 StringRef(""), StringRef(""),
1642 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001643}
1644
1645// virtual
1646bool AddressSanitizer::doInitialization(Module &M) {
1647 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001648
Alexey Samsonov4f319cc2014-07-02 16:54:41 +00001649 GlobalsMD.init(M);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001650
1651 C = &(M.getContext());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001652 LongSize = M.getDataLayout().getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001653 IntptrTy = Type::getIntNTy(*C, LongSize);
Kuba Brecka1001bb52014-12-05 22:19:18 +00001654 TargetTriple = Triple(M.getTargetTriple());
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001655
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001656 if (!CompileKernel) {
1657 std::tie(AsanCtorFunction, AsanInitFunction) =
Kuba Brecka45dbffd2015-07-23 10:54:06 +00001658 createSanitizerCtorAndInitFunctions(
1659 M, kAsanModuleCtorName, kAsanInitName,
1660 /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001661 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1662 }
1663 Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001664 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001665}
1666
Keno Fischere03fae42015-12-05 14:42:34 +00001667bool AddressSanitizer::doFinalization(Module &M) {
1668 GlobalsMD.reset();
1669 return false;
1670}
1671
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001672bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1673 // For each NSObject descendant having a +load method, this method is invoked
1674 // by the ObjC runtime before any of the static constructors is called.
1675 // Therefore we need to instrument such methods with a call to __asan_init
1676 // at the beginning in order to initialize our runtime before any access to
1677 // the shadow memory.
1678 // We cannot just ignore these methods, because they may call other
1679 // instrumented functions.
1680 if (F.getName().find(" load]") != std::string::npos) {
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001681 IRBuilder<> IRB(&F.front(), F.front().begin());
David Blaikieff6409d2015-05-18 22:13:54 +00001682 IRB.CreateCall(AsanInitFunction, {});
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001683 return true;
1684 }
1685 return false;
1686}
1687
Reid Kleckner2f907552015-07-21 17:40:14 +00001688void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
1689 // Find the one possible call to llvm.localescape and pre-mark allocas passed
1690 // to it as uninteresting. This assumes we haven't started processing allocas
1691 // yet. This check is done up front because iterating the use list in
1692 // isInterestingAlloca would be algorithmically slower.
1693 assert(ProcessedAllocas.empty() && "must process localescape before allocas");
1694
1695 // Try to get the declaration of llvm.localescape. If it's not in the module,
1696 // we can exit early.
1697 if (!F.getParent()->getFunction("llvm.localescape")) return;
1698
1699 // Look for a call to llvm.localescape call in the entry block. It can't be in
1700 // any other block.
1701 for (Instruction &I : F.getEntryBlock()) {
1702 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
1703 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
1704 // We found a call. Mark all the allocas passed in as uninteresting.
1705 for (Value *Arg : II->arg_operands()) {
1706 AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
1707 assert(AI && AI->isStaticAlloca() &&
1708 "non-static alloca arg to localescape");
1709 ProcessedAllocas[AI] = false;
1710 }
1711 break;
1712 }
1713 }
1714}
1715
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001716bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001717 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001718 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001719 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001720 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001721
Yury Gribov3ae427d2014-12-01 08:47:58 +00001722 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1723
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001724 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001725 maybeInsertAsanInitAtFunctionEntry(F);
1726
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001727 if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001728
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001729 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName()) return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001730
Reid Kleckner2f907552015-07-21 17:40:14 +00001731 FunctionStateRAII CleanupObj(this);
1732
1733 // We can't instrument allocas used with llvm.localescape. Only static allocas
1734 // can be passed to that intrinsic.
1735 markEscapedLocalAllocas(F);
1736
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001737 // We want to instrument every address only once per basic block (unless there
1738 // are calls between uses).
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001739 SmallSet<Value *, 16> TempsToInstrument;
1740 SmallVector<Instruction *, 16> ToInstrument;
1741 SmallVector<Instruction *, 8> NoReturnCalls;
1742 SmallVector<BasicBlock *, 16> AllBlocks;
1743 SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001744 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001745 bool IsWrite;
Kostya Serebryanyc7895a82014-05-23 11:52:07 +00001746 unsigned Alignment;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001747 uint64_t TypeSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001748
1749 // Fill the set of memory operations to instrument.
Alexey Samsonova02e6642014-05-29 18:40:48 +00001750 for (auto &BB : F) {
1751 AllBlocks.push_back(&BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001752 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001753 int NumInsnsPerBB = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001754 for (auto &Inst : BB) {
1755 if (LooksLikeCodeInBug11395(&Inst)) return false;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001756 if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
1757 &Alignment)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001758 if (ClOpt && ClOptSameTemp) {
David Blaikie70573dc2014-11-19 07:49:26 +00001759 if (!TempsToInstrument.insert(Addr).second)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001760 continue; // We've seen this temp in the current BB.
1761 }
Kostya Serebryanycb3f6e12014-02-27 13:13:59 +00001762 } else if (ClInvalidPointerPairs &&
Alexey Samsonova02e6642014-05-29 18:40:48 +00001763 isInterestingPointerComparisonOrSubtraction(&Inst)) {
1764 PointerComparisonsOrSubtracts.push_back(&Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001765 continue;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001766 } else if (isa<MemIntrinsic>(Inst)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001767 // ok, take it.
1768 } else {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001769 if (isa<AllocaInst>(Inst)) NumAllocas++;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001770 CallSite CS(&Inst);
Kostya Serebryany699ac282013-02-20 12:35:15 +00001771 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001772 // A call inside BB.
1773 TempsToInstrument.clear();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001774 if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001775 }
1776 continue;
1777 }
Alexey Samsonova02e6642014-05-29 18:40:48 +00001778 ToInstrument.push_back(&Inst);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001779 NumInsnsPerBB++;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001780 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001781 }
1782 }
1783
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001784 bool UseCalls =
1785 CompileKernel ||
1786 (ClInstrumentationWithCallsThreshold >= 0 &&
1787 ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001788 const TargetLibraryInfo *TLI =
1789 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001790 const DataLayout &DL = F.getParent()->getDataLayout();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001791 ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
1792 /*RoundToAlign=*/true);
1793
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001794 // Instrument.
1795 int NumInstrumented = 0;
Alexey Samsonova02e6642014-05-29 18:40:48 +00001796 for (auto Inst : ToInstrument) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001797 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1798 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001799 if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001800 instrumentMop(ObjSizeVis, Inst, UseCalls,
1801 F.getParent()->getDataLayout());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001802 else
Kostya Serebryany94c81ca2014-04-21 11:50:42 +00001803 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001804 }
1805 NumInstrumented++;
1806 }
1807
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001808 FunctionStackPoisoner FSP(F, *this);
1809 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001810
1811 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1812 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
Alexey Samsonova02e6642014-05-29 18:40:48 +00001813 for (auto CI : NoReturnCalls) {
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001814 IRBuilder<> IRB(CI);
David Blaikieff6409d2015-05-18 22:13:54 +00001815 IRB.CreateCall(AsanHandleNoReturnFunc, {});
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001816 }
1817
Alexey Samsonova02e6642014-05-29 18:40:48 +00001818 for (auto Inst : PointerComparisonsOrSubtracts) {
1819 instrumentPointerComparisonOrSubtraction(Inst);
Kostya Serebryany796f6552014-02-27 12:45:36 +00001820 NumInstrumented++;
1821 }
1822
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001823 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001824
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001825 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1826
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001827 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001828}
1829
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001830// Workaround for bug 11395: we don't want to instrument stack in functions
1831// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1832// FIXME: remove once the bug 11395 is fixed.
1833bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1834 if (LongSize != 32) return false;
1835 CallInst *CI = dyn_cast<CallInst>(I);
1836 if (!CI || !CI->isInlineAsm()) return false;
1837 if (CI->getNumArgOperands() <= 5) return false;
1838 // We have inline assembly with quite a few arguments.
1839 return true;
1840}
1841
1842void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1843 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001844 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1845 std::string Suffix = itostr(i);
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001846 AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
1847 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1848 IntptrTy, nullptr));
1849 AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001850 M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
1851 IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Kostya Serebryany6805de52013-09-10 13:16:56 +00001852 }
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001853 AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001854 M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
1855 IntptrTy, IntptrTy, nullptr));
Ismail Pazarbasi198d6d52015-04-06 21:09:08 +00001856 AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
David Blaikiea92765c2014-11-14 00:41:42 +00001857 M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
1858 IntptrTy, IntptrTy, nullptr));
Yury Gribov98b18592015-05-28 07:51:49 +00001859 AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1860 kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1861 AsanAllocasUnpoisonFunc =
1862 checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1863 kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001864}
1865
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001866void FunctionStackPoisoner::poisonRedZones(ArrayRef<uint8_t> ShadowBytes,
1867 IRBuilder<> &IRB, Value *ShadowBase,
1868 bool DoPoison) {
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001869 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001870 size_t i = 0;
1871 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1872 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1873 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1874 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1875 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1876 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1877 uint64_t Val = 0;
1878 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001879 if (F.getParent()->getDataLayout().isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001880 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1881 else
1882 Val = (Val << 8) | ShadowBytes[i + j];
1883 }
1884 if (!Val) continue;
1885 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1886 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1887 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1888 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001889 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001890 }
1891}
1892
Kostya Serebryany6805de52013-09-10 13:16:56 +00001893// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1894// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1895static int StackMallocSizeClass(uint64_t LocalStackSize) {
1896 assert(LocalStackSize <= kMaxStackMallocSize);
1897 uint64_t MaxSize = kMinStackMallocSize;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00001898 for (int i = 0;; i++, MaxSize *= 2)
1899 if (LocalStackSize <= MaxSize) return i;
Kostya Serebryany6805de52013-09-10 13:16:56 +00001900 llvm_unreachable("impossible LocalStackSize");
1901}
1902
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001903// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1904// We can not use MemSet intrinsic because it may end up calling the actual
1905// memset. Size is a multiple of 8.
1906// Currently this generates 8-byte stores on x86_64; it may be better to
1907// generate wider stores.
1908void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1909 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1910 assert(!(Size % 8));
Gabor Horvathfee04342015-03-16 09:53:42 +00001911
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001912 // kAsanStackAfterReturnMagic is 0xf5.
1913 const uint64_t kAsanStackAfterReturnMagic64 = 0xf5f5f5f5f5f5f5f5ULL;
Gabor Horvathfee04342015-03-16 09:53:42 +00001914
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001915 for (int i = 0; i < Size; i += 8) {
1916 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
Kostya Serebryanyb1870a62015-03-17 19:13:23 +00001917 IRB.CreateStore(
1918 ConstantInt::get(IRB.getInt64Ty(), kAsanStackAfterReturnMagic64),
1919 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001920 }
1921}
1922
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00001923PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
1924 Value *ValueIfTrue,
1925 Instruction *ThenTerm,
1926 Value *ValueIfFalse) {
1927 PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
1928 BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
1929 PHI->addIncoming(ValueIfFalse, CondBlock);
1930 BasicBlock *ThenBlock = ThenTerm->getParent();
1931 PHI->addIncoming(ValueIfTrue, ThenBlock);
1932 return PHI;
1933}
1934
1935Value *FunctionStackPoisoner::createAllocaForLayout(
1936 IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
1937 AllocaInst *Alloca;
1938 if (Dynamic) {
1939 Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
1940 ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
1941 "MyAlloca");
1942 } else {
1943 Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
1944 nullptr, "MyAlloca");
1945 assert(Alloca->isStaticAlloca());
1946 }
1947 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1948 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1949 Alloca->setAlignment(FrameAlignment);
1950 return IRB.CreatePointerCast(Alloca, IntptrTy);
1951}
1952
Yury Gribov98b18592015-05-28 07:51:49 +00001953void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
1954 BasicBlock &FirstBB = *F.begin();
1955 IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
1956 DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
1957 IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
1958 DynamicAllocaLayout->setAlignment(32);
1959}
1960
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001961void FunctionStackPoisoner::poisonStack() {
Yury Gribov55441bb2014-11-21 10:29:50 +00001962 assert(AllocaVec.size() > 0 || DynamicAllocaVec.size() > 0);
1963
Alexey Samsonov8daaf8b2015-10-22 19:51:59 +00001964 // Insert poison calls for lifetime intrinsics for alloca.
1965 bool HavePoisonedAllocas = false;
1966 for (const auto &APC : AllocaPoisonCallVec) {
1967 assert(APC.InsBefore);
1968 assert(APC.AI);
1969 IRBuilder<> IRB(APC.InsBefore);
1970 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
1971 HavePoisonedAllocas |= APC.DoPoison;
1972 }
1973
Yury Gribov98b18592015-05-28 07:51:49 +00001974 if (ClInstrumentAllocas && DynamicAllocaVec.size() > 0) {
Yury Gribov55441bb2014-11-21 10:29:50 +00001975 // Handle dynamic allocas.
Yury Gribov98b18592015-05-28 07:51:49 +00001976 createDynamicAllocasInitStorage();
Alexander Potapenkof90556e2015-06-12 11:27:06 +00001977 for (auto &AI : DynamicAllocaVec) handleDynamicAllocaCall(AI);
Yury Gribov98b18592015-05-28 07:51:49 +00001978
1979 unpoisonDynamicAllocas();
Kuba Breckaf5875d32015-02-24 09:47:05 +00001980 }
Yury Gribov55441bb2014-11-21 10:29:50 +00001981
Hans Wennborg083ca9b2015-10-06 23:24:35 +00001982 if (AllocaVec.empty()) return;
Yury Gribov55441bb2014-11-21 10:29:50 +00001983
Kostya Serebryany6805de52013-09-10 13:16:56 +00001984 int StackMallocIdx = -1;
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001985 DebugLoc EntryDebugLocation;
Pete Cooperadebb932016-03-11 02:14:16 +00001986 if (auto SP = F.getSubprogram())
Alexey Samsonov773e8c32015-06-26 00:00:47 +00001987 EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001988
1989 Instruction *InsBefore = AllocaVec[0];
1990 IRBuilder<> IRB(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00001991 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001992
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00001993 // Make sure non-instrumented allocas stay in the entry block. Otherwise,
1994 // debug info is broken, because only entry-block allocas are treated as
1995 // regular stack slots.
1996 auto InsBeforeB = InsBefore->getParent();
1997 assert(InsBeforeB == &F.getEntryBlock());
Duncan P. N. Exon Smithe82c2862015-10-13 17:39:10 +00001998 for (BasicBlock::iterator I(InsBefore); I != InsBeforeB->end(); ++I)
1999 if (auto *AI = dyn_cast<AllocaInst>(I))
Kuba Brecka8ec94ea2015-07-22 10:25:38 +00002000 if (NonInstrumentedStaticAllocaVec.count(AI) > 0)
2001 AI->moveBefore(InsBefore);
Kuba Brecka37a5ffa2015-07-17 06:29:57 +00002002
Reid Kleckner2f907552015-07-21 17:40:14 +00002003 // If we have a call to llvm.localescape, keep it in the entry block.
2004 if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2005
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002006 SmallVector<ASanStackVariableDescription, 16> SVD;
2007 SVD.reserve(AllocaVec.size());
Alexey Samsonova02e6642014-05-29 18:40:48 +00002008 for (AllocaInst *AI : AllocaVec) {
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002009 ASanStackVariableDescription D = {AI->getName().data(),
2010 ASan.getAllocaSizeInBytes(AI),
2011 AI->getAlignment(), AI, 0};
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002012 SVD.push_back(D);
2013 }
2014 // Minimal header size (left redzone) is 4 pointers,
2015 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2016 size_t MinHeaderSize = ASan.LongSize / 2;
2017 ASanStackFrameLayout L;
Aaron Ballmanef0fe1e2016-03-30 21:30:00 +00002018 ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize, &L);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002019 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
2020 uint64_t LocalStackSize = L.FrameSize;
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00002021 bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2022 LocalStackSize <= kMaxStackMallocSize;
Alexey Samsonov869a5ff2015-07-29 19:36:08 +00002023 bool DoDynamicAlloca = ClDynamicAllocaStack;
2024 // Don't do dynamic alloca or stack malloc if:
2025 // 1) There is inline asm: too often it makes assumptions on which registers
2026 // are available.
2027 // 2) There is a returns_twice call (typically setjmp), which is
2028 // optimization-hostile, and doesn't play well with introduced indirect
2029 // register-relative calculation of local variable addresses.
2030 DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2031 DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002032
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002033 Value *StaticAlloca =
2034 DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2035
2036 Value *FakeStack;
2037 Value *LocalStackBase;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002038
2039 if (DoStackMalloc) {
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002040 // void *FakeStack = __asan_option_detect_stack_use_after_return
2041 // ? __asan_stack_malloc_N(LocalStackSize)
2042 // : nullptr;
2043 // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002044 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
2045 kAsanOptionDetectUAR, IRB.getInt32Ty());
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002046 Value *UARIsEnabled =
2047 IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
2048 Constant::getNullValue(IRB.getInt32Ty()));
2049 Instruction *Term =
2050 SplitBlockAndInsertIfThen(UARIsEnabled, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002051 IRBuilder<> IRBIf(Term);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002052 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002053 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2054 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2055 Value *FakeStackValue =
2056 IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2057 ConstantInt::get(IntptrTy, LocalStackSize));
Kostya Serebryanyf3223822013-09-18 14:07:14 +00002058 IRB.SetInsertPoint(InsBefore);
Evgeniy Stepanovaaf4bb22014-05-14 10:30:15 +00002059 IRB.SetCurrentDebugLocation(EntryDebugLocation);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002060 FakeStack = createPHI(IRB, UARIsEnabled, FakeStackValue, Term,
2061 ConstantInt::get(IntptrTy, 0));
2062
2063 Value *NoFakeStack =
2064 IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2065 Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2066 IRBIf.SetInsertPoint(Term);
2067 IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2068 Value *AllocaValue =
2069 DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2070 IRB.SetInsertPoint(InsBefore);
2071 IRB.SetCurrentDebugLocation(EntryDebugLocation);
2072 LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2073 } else {
2074 // void *FakeStack = nullptr;
2075 // void *LocalStackBase = alloca(LocalStackSize);
2076 FakeStack = ConstantInt::get(IntptrTy, 0);
2077 LocalStackBase =
2078 DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002079 }
2080
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002081 // Replace Alloca instructions with base+offset.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002082 for (const auto &Desc : SVD) {
2083 AllocaInst *AI = Desc.AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00002084 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Alexey Samsonova02e6642014-05-29 18:40:48 +00002085 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002086 AI->getType());
Adrian Prantl3e2659e2015-01-30 19:37:48 +00002087 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002088 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002089 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002090
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002091 // The left-most redzone has enough space for at least 4 pointers.
2092 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002093 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2094 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2095 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002096 // Write the frame description constant to redzone[1].
2097 Value *BasePlus1 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002098 IRB.CreateAdd(LocalStackBase,
2099 ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2100 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00002101 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00002102 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002103 /*AllowMerging*/ true);
2104 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002105 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002106 // Write the PC to redzone[2].
2107 Value *BasePlus2 = IRB.CreateIntToPtr(
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002108 IRB.CreateAdd(LocalStackBase,
2109 ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2110 IntptrPtrTy);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00002111 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002112
2113 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002114 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00002115 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002116
Kostya Serebryany530e2072013-12-23 14:15:08 +00002117 // (Un)poison the stack before all ret instructions.
Alexey Samsonova02e6642014-05-29 18:40:48 +00002118 for (auto Ret : RetVec) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002119 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002120 // Mark the current frame as retired.
2121 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2122 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002123 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00002124 assert(StackMallocIdx >= 0);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002125 // if FakeStack != 0 // LocalStackBase == FakeStack
Kostya Serebryany530e2072013-12-23 14:15:08 +00002126 // // In use-after-return mode, poison the whole stack frame.
2127 // if StackMallocIdx <= 4
2128 // // For small sizes inline the whole thing:
2129 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002130 // **SavedFlagPtr(FakeStack) = 0
Kostya Serebryany530e2072013-12-23 14:15:08 +00002131 // else
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002132 // __asan_stack_free_N(FakeStack, LocalStackSize)
Kostya Serebryany530e2072013-12-23 14:15:08 +00002133 // else
2134 // <This is not a fake stack; unpoison the redzones>
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002135 Value *Cmp =
2136 IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
Kostya Serebryany530e2072013-12-23 14:15:08 +00002137 TerminatorInst *ThenTerm, *ElseTerm;
2138 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2139
2140 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002141 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002142 int ClassSize = kMinStackMallocSize << StackMallocIdx;
2143 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
2144 ClassSize >> Mapping.Scale);
2145 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
Alexey Samsonov4b7f4132014-12-11 21:53:03 +00002146 FakeStack,
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002147 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2148 Value *SavedFlagPtr = IRBPoison.CreateLoad(
2149 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2150 IRBPoison.CreateStore(
2151 Constant::getNullValue(IRBPoison.getInt8Ty()),
2152 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2153 } else {
2154 // For larger frames call __asan_stack_free_*.
David Blaikieff6409d2015-05-18 22:13:54 +00002155 IRBPoison.CreateCall(
2156 AsanStackFreeFunc[StackMallocIdx],
2157 {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00002158 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00002159
2160 IRBuilder<> IRBElse(ElseTerm);
2161 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00002162 } else if (HavePoisonedAllocas) {
2163 // If we poisoned some allocas in llvm.lifetime analysis,
2164 // unpoison whole stack frame now.
Alexey Samsonov261177a2012-12-04 01:34:23 +00002165 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00002166 } else {
2167 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002168 }
2169 }
2170
Kostya Serebryany09959942012-10-19 06:20:53 +00002171 // We are done. Remove the old unused alloca instructions.
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002172 for (auto AI : AllocaVec) AI->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00002173}
Alexey Samsonov261177a2012-12-04 01:34:23 +00002174
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002175void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00002176 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00002177 // For now just insert the call to ASan runtime.
2178 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2179 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
Alexander Potapenkof90556e2015-06-12 11:27:06 +00002180 IRB.CreateCall(
2181 DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2182 {AddrArg, SizeArg});
Alexey Samsonov261177a2012-12-04 01:34:23 +00002183}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002184
2185// Handling llvm.lifetime intrinsics for a given %alloca:
2186// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2187// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2188// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2189// could be poisoned by previous llvm.lifetime.end instruction, as the
2190// variable may go in and out of scope several times, e.g. in loops).
2191// (3) if we poisoned at least one %alloca in a function,
2192// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002193
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002194AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2195 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2196 // We're intested only in allocas we can handle.
Anna Zaks8ed1d812015-02-27 03:12:36 +00002197 return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002198 // See if we've already calculated (or started to calculate) alloca for a
2199 // given value.
2200 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002201 if (I != AllocaForValue.end()) return I->second;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002202 // Store 0 while we're calculating alloca for value V to avoid
2203 // infinite recursion if the value references itself.
Craig Topperf40110f2014-04-25 05:29:35 +00002204 AllocaForValue[V] = nullptr;
2205 AllocaInst *Res = nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002206 if (CastInst *CI = dyn_cast<CastInst>(V))
2207 Res = findAllocaForValue(CI->getOperand(0));
2208 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00002209 for (Value *IncValue : PN->incoming_values()) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002210 // Allow self-referencing phi-nodes.
2211 if (IncValue == PN) continue;
2212 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2213 // AI for incoming values should exist and should all be equal.
Craig Topperf40110f2014-04-25 05:29:35 +00002214 if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2215 return nullptr;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00002216 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002217 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002218 }
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002219 if (Res) AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00002220 return Res;
2221}
Yury Gribov55441bb2014-11-21 10:29:50 +00002222
Yury Gribov98b18592015-05-28 07:51:49 +00002223void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
Yury Gribov55441bb2014-11-21 10:29:50 +00002224 IRBuilder<> IRB(AI);
2225
Yury Gribov55441bb2014-11-21 10:29:50 +00002226 const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2227 const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2228
2229 Value *Zero = Constant::getNullValue(IntptrTy);
2230 Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2231 Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
Yury Gribov55441bb2014-11-21 10:29:50 +00002232
2233 // Since we need to extend alloca with additional memory to locate
2234 // redzones, and OldSize is number of allocated blocks with
2235 // ElementSize size, get allocated memory size in bytes by
2236 // OldSize * ElementSize.
Yury Gribov98b18592015-05-28 07:51:49 +00002237 const unsigned ElementSize =
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002238 F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
Yury Gribov98b18592015-05-28 07:51:49 +00002239 Value *OldSize =
2240 IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2241 ConstantInt::get(IntptrTy, ElementSize));
Yury Gribov55441bb2014-11-21 10:29:50 +00002242
2243 // PartialSize = OldSize % 32
2244 Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2245
2246 // Misalign = kAllocaRzSize - PartialSize;
2247 Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2248
2249 // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2250 Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2251 Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2252
2253 // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2254 // Align is added to locate left redzone, PartialPadding for possible
2255 // partial redzone and kAllocaRzSize for right redzone respectively.
2256 Value *AdditionalChunkSize = IRB.CreateAdd(
2257 ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2258
2259 Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2260
2261 // Insert new alloca with new NewSize and Align params.
2262 AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2263 NewAlloca->setAlignment(Align);
2264
2265 // NewAddress = Address + Align
2266 Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2267 ConstantInt::get(IntptrTy, Align));
2268
Yury Gribov98b18592015-05-28 07:51:49 +00002269 // Insert __asan_alloca_poison call for new created alloca.
Yury Gribov781bce22015-05-28 08:03:28 +00002270 IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
Yury Gribov98b18592015-05-28 07:51:49 +00002271
2272 // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2273 // for unpoisoning stuff.
2274 IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2275
Yury Gribov55441bb2014-11-21 10:29:50 +00002276 Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2277
Yury Gribov98b18592015-05-28 07:51:49 +00002278 // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
Yury Gribov55441bb2014-11-21 10:29:50 +00002279 AI->replaceAllUsesWith(NewAddressPtr);
2280
Yury Gribov98b18592015-05-28 07:51:49 +00002281 // We are done. Erase old alloca from parent.
Yury Gribov55441bb2014-11-21 10:29:50 +00002282 AI->eraseFromParent();
2283}
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002284
2285// isSafeAccess returns true if Addr is always inbounds with respect to its
2286// base object. For example, it is a field access or an array access with
2287// constant inbounds index.
2288bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2289 Value *Addr, uint64_t TypeSize) const {
2290 SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2291 if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
Dmitry Vyukovee842382015-03-16 08:04:26 +00002292 uint64_t Size = SizeOffset.first.getZExtValue();
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002293 int64_t Offset = SizeOffset.second.getSExtValue();
2294 // Three checks are required to ensure safety:
2295 // . Offset >= 0 (since the offset is given from the base ptr)
2296 // . Size >= Offset (unsigned)
2297 // . Size - Offset >= NeededSize (unsigned)
Dmitry Vyukovee842382015-03-16 08:04:26 +00002298 return Offset >= 0 && Size >= uint64_t(Offset) &&
2299 Size - uint64_t(Offset) >= TypeSize / 8;
Dmitry Vyukovb37b95e2015-03-04 13:27:53 +00002300}