blob: 224387fd914924aed5ffe00f38c83a77fe8bd51e [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
16#define DEBUG_TYPE "asan"
17
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000019#include "llvm/ADT/ArrayRef.h"
Alexey Samsonov29dd7f22012-12-27 08:50:58 +000020#include "llvm/ADT/DenseMap.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000021#include "llvm/ADT/DepthFirstIterator.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000022#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallSet.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/ADT/SmallVector.h"
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +000026#include "llvm/ADT/Statistic.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000027#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov617232f2012-05-23 11:52:12 +000028#include "llvm/ADT/Triple.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000029#include "llvm/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/IRBuilder.h"
33#include "llvm/IR/InlineAsm.h"
34#include "llvm/IR/IntrinsicInst.h"
35#include "llvm/IR/LLVMContext.h"
Kostya Serebryany714c67c2014-01-17 11:00:30 +000036#include "llvm/IR/MDBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Module.h"
38#include "llvm/IR/Type.h"
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +000039#include "llvm/InstVisitor.h"
Kostya Serebryany699ac282013-02-20 12:35:15 +000040#include "llvm/Support/CallSite.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000041#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/DataTypes.h"
43#include "llvm/Support/Debug.h"
Kostya Serebryany9e62b302013-06-03 14:46:56 +000044#include "llvm/Support/Endian.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000045#include "llvm/Support/system_error.h"
Kostya Serebryany4fb78012013-12-06 09:00:17 +000046#include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000047#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Kostya Serebryany9f5213f2013-06-26 09:18:17 +000048#include "llvm/Transforms/Utils/Cloning.h"
Alexey Samsonov3d43b632012-12-12 14:31:53 +000049#include "llvm/Transforms/Utils/Local.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000050#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne015370e2013-07-09 22:02:49 +000051#include "llvm/Transforms/Utils/SpecialCaseList.h"
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000052#include <algorithm>
Chandler Carruthed0881b2012-12-03 16:50:05 +000053#include <string>
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000054
55using namespace llvm;
56
57static const uint64_t kDefaultShadowScale = 3;
58static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
59static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Kostya Serebryanycc92c792014-02-24 13:40:24 +000060static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000; // < 2G.
Kostya Serebryany4766fe62013-01-23 12:54:55 +000061static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
Kostya Serebryany9e62b302013-06-03 14:46:56 +000062static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
Kostya Serebryany8baa3862014-02-10 07:37:04 +000063static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
64static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000065
Kostya Serebryany6805de52013-09-10 13:16:56 +000066static const size_t kMinStackMallocSize = 1 << 6; // 64B
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000067static const size_t kMaxStackMallocSize = 1 << 16; // 64K
68static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
69static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
70
Craig Topperd3a34f82013-07-16 01:17:10 +000071static const char *const kAsanModuleCtorName = "asan.module_ctor";
72static const char *const kAsanModuleDtorName = "asan.module_dtor";
73static const int kAsanCtorAndCtorPriority = 1;
74static const char *const kAsanReportErrorTemplate = "__asan_report_";
75static const char *const kAsanReportLoadN = "__asan_report_load_n";
76static const char *const kAsanReportStoreN = "__asan_report_store_n";
77static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
Alexey Samsonovf52b7172013-08-05 13:19:49 +000078static const char *const kAsanUnregisterGlobalsName =
79 "__asan_unregister_globals";
Craig Topperd3a34f82013-07-16 01:17:10 +000080static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
81static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
82static const char *const kAsanInitName = "__asan_init_v3";
Bob Wilsonda4147c2013-11-15 07:16:09 +000083static const char *const kAsanCovName = "__sanitizer_cov";
Craig Topperd3a34f82013-07-16 01:17:10 +000084static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany6805de52013-09-10 13:16:56 +000085static const int kMaxAsanStackMallocSizeClass = 10;
86static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
87static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
Craig Topperd3a34f82013-07-16 01:17:10 +000088static const char *const kAsanGenPrefix = "__asan_gen_";
89static const char *const kAsanPoisonStackMemoryName =
90 "__asan_poison_stack_memory";
91static const char *const kAsanUnpoisonStackMemoryName =
Alexey Samsonov261177a2012-12-04 01:34:23 +000092 "__asan_unpoison_stack_memory";
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +000093
Kostya Serebryanyf3223822013-09-18 14:07:14 +000094static const char *const kAsanOptionDetectUAR =
95 "__asan_option_detect_stack_use_after_return";
96
David Blaikieeacc2872013-09-18 00:11:27 +000097#ifndef NDEBUG
Kostya Serebryanybc86efb2013-09-17 12:14:50 +000098static const int kAsanStackAfterReturnMagic = 0xf5;
David Blaikieeacc2872013-09-18 00:11:27 +000099#endif
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000100
Kostya Serebryany874dae62012-07-16 16:15:40 +0000101// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
102static const size_t kNumberOfAccessSizes = 5;
103
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000104// Command-line flags.
105
106// This flag may need to be replaced with -f[no-]asan-reads.
107static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
108 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
109static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
110 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryany90241602012-05-30 09:04:06 +0000111static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
112 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
113 cl::Hidden, cl::init(true));
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000114static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
115 cl::desc("use instrumentation with slow path for all accesses"),
116 cl::Hidden, cl::init(false));
Kostya Serebryany874dae62012-07-16 16:15:40 +0000117// This flag limits the number of instructions to be instrumented
Kostya Serebryanyc387ca72012-06-28 09:34:41 +0000118// in any given BB. Normally, this should be set to unlimited (INT_MAX),
119// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
120// set it to 10000.
121static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
122 cl::init(10000),
123 cl::desc("maximal number of instructions to instrument in any given BB"),
124 cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000125// This flag may need to be replaced with -f[no]asan-stack.
126static cl::opt<bool> ClStack("asan-stack",
127 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
128// This flag may need to be replaced with -f[no]asan-use-after-return.
129static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
130 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
131// This flag may need to be replaced with -f[no]asan-globals.
132static cl::opt<bool> ClGlobals("asan-globals",
133 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000134static cl::opt<int> ClCoverage("asan-coverage",
135 cl::desc("ASan coverage. 0: none, 1: entry block, 2: all blocks"),
136 cl::Hidden, cl::init(false));
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000137static cl::opt<bool> ClInitializers("asan-initialization-order",
138 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000139static cl::opt<bool> ClMemIntrin("asan-memintrin",
140 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000141static cl::opt<unsigned> ClRealignStack("asan-realign-stack",
142 cl::desc("Realign stack to the value of this flag (power of two)"),
143 cl::Hidden, cl::init(32));
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000144static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
145 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000146 "during instrumentation"), cl::Hidden);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000147
Kostya Serebryany9f5213f2013-06-26 09:18:17 +0000148// This is an experimental feature that will allow to choose between
149// instrumented and non-instrumented code at link-time.
150// If this option is on, just before instrumenting a function we create its
151// clone; if the function is not changed by asan the clone is deleted.
152// If we end up with a clone, we put the instrumented function into a section
153// called "ASAN" and the uninstrumented function into a section called "NOASAN".
154//
155// This is still a prototype, we need to figure out a way to keep two copies of
156// a function so that the linker can easily choose one of them.
157static cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
158 cl::desc("Keep uninstrumented copies of functions"),
159 cl::Hidden, cl::init(false));
160
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000161// These flags allow to change the shadow mapping.
162// The shadow mapping looks like
163// Shadow = (Mem >> scale) + (1 << offset_log)
164static cl::opt<int> ClMappingScale("asan-mapping-scale",
165 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000166
167// Optimization flags. Not user visible, used mostly for testing
168// and benchmarking the tool.
169static cl::opt<bool> ClOpt("asan-opt",
170 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
171static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
172 cl::desc("Instrument the same temp just once"), cl::Hidden,
173 cl::init(true));
174static cl::opt<bool> ClOptGlobals("asan-opt-globals",
175 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
176
Alexey Samsonovdf624522012-11-29 18:14:24 +0000177static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
178 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
179 cl::Hidden, cl::init(false));
180
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000181// Debug flags.
182static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
183 cl::init(0));
184static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
185 cl::Hidden, cl::init(0));
186static cl::opt<std::string> ClDebugFunc("asan-debug-func",
187 cl::Hidden, cl::desc("Debug func"));
188static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
189 cl::Hidden, cl::init(-1));
190static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
191 cl::Hidden, cl::init(-1));
192
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000193STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
194STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
195STATISTIC(NumOptimizedAccessesToGlobalArray,
196 "Number of optimized accesses to global arrays");
197STATISTIC(NumOptimizedAccessesToGlobalVar,
198 "Number of optimized accesses to global vars");
199
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000200namespace {
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000201/// A set of dynamically initialized globals extracted from metadata.
202class SetOfDynamicallyInitializedGlobals {
203 public:
204 void Init(Module& M) {
205 // Clang generates metadata identifying all dynamically initialized globals.
206 NamedMDNode *DynamicGlobals =
207 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
208 if (!DynamicGlobals)
209 return;
210 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
211 MDNode *MDN = DynamicGlobals->getOperand(i);
212 assert(MDN->getNumOperands() == 1);
213 Value *VG = MDN->getOperand(0);
214 // The optimizer may optimize away a global entirely, in which case we
215 // cannot instrument access to it.
216 if (!VG)
217 continue;
218 DynInitGlobals.insert(cast<GlobalVariable>(VG));
219 }
220 }
221 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
222 private:
223 SmallSet<GlobalValue*, 32> DynInitGlobals;
224};
225
Alexey Samsonov1345d352013-01-16 13:23:28 +0000226/// This struct defines the shadow mapping using the rule:
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000227/// shadow = (mem >> Scale) ADD-or-OR Offset.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000228struct ShadowMapping {
229 int Scale;
230 uint64_t Offset;
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000231 bool OrShadowOffset;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000232};
233
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000234static ShadowMapping getShadowMapping(const Module &M, int LongSize) {
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000235 llvm::Triple TargetTriple(M.getTargetTriple());
236 bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000237 // bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
Kostya Serebryany8baa3862014-02-10 07:37:04 +0000238 bool IsFreeBSD = TargetTriple.getOS() == llvm::Triple::FreeBSD;
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000239 bool IsLinux = TargetTriple.getOS() == llvm::Triple::Linux;
Bill Schmidt0a9170d2013-07-26 01:35:43 +0000240 bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
241 TargetTriple.getArch() == llvm::Triple::ppc64le;
Kostya Serebryanybe733372013-02-12 11:11:02 +0000242 bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
Kostya Serebryany9e62b302013-06-03 14:46:56 +0000243 bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
244 TargetTriple.getArch() == llvm::Triple::mipsel;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000245
246 ShadowMapping Mapping;
247
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000248 if (LongSize == 32) {
249 if (IsAndroid)
250 Mapping.Offset = 0;
251 else if (IsMIPS32)
252 Mapping.Offset = kMIPS32_ShadowOffset32;
253 else if (IsFreeBSD)
254 Mapping.Offset = kFreeBSD_ShadowOffset32;
255 else
256 Mapping.Offset = kDefaultShadowOffset32;
257 } else { // LongSize == 64
258 if (IsPPC64)
259 Mapping.Offset = kPPC64_ShadowOffset64;
260 else if (IsFreeBSD)
261 Mapping.Offset = kFreeBSD_ShadowOffset64;
262 else if (IsLinux && IsX86_64)
263 Mapping.Offset = kSmallX86_64ShadowOffset;
264 else
265 Mapping.Offset = kDefaultShadowOffset64;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000266 }
267
268 Mapping.Scale = kDefaultShadowScale;
269 if (ClMappingScale) {
270 Mapping.Scale = ClMappingScale;
271 }
272
Kostya Serebryanycc92c792014-02-24 13:40:24 +0000273 // OR-ing shadow offset if more efficient (at least on x86) if the offset
274 // is a power of two, but on ppc64 we have to use add since the shadow
275 // offset is not necessary 1/8-th of the address space.
276 Mapping.OrShadowOffset = !IsPPC64 && !(Mapping.Offset & (Mapping.Offset - 1));
277
Alexey Samsonov1345d352013-01-16 13:23:28 +0000278 return Mapping;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000279}
280
Alexey Samsonov1345d352013-01-16 13:23:28 +0000281static size_t RedzoneSizeForScale(int MappingScale) {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000282 // Redzone used for stack and globals is at least 32 bytes.
283 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
Alexey Samsonov1345d352013-01-16 13:23:28 +0000284 return std::max(32U, 1U << MappingScale);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000285}
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000286
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000287/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000288struct AddressSanitizer : public FunctionPass {
Alexey Samsonov819eddc2013-03-14 12:38:58 +0000289 AddressSanitizer(bool CheckInitOrder = true,
Alexey Samsonovdf624522012-11-29 18:14:24 +0000290 bool CheckUseAfterReturn = false,
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000291 bool CheckLifetime = false,
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000292 StringRef BlacklistFile = StringRef())
Alexey Samsonovdf624522012-11-29 18:14:24 +0000293 : FunctionPass(ID),
294 CheckInitOrder(CheckInitOrder || ClInitializers),
295 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000296 CheckLifetime(CheckLifetime || ClCheckLifetime),
297 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000298 : BlacklistFile) {}
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000299 virtual const char *getPassName() const {
300 return "AddressSanitizerFunctionPass";
301 }
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000302 void instrumentMop(Instruction *I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000303 void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
304 Value *Addr, uint32_t TypeSize, bool IsWrite,
305 Value *SizeArgument);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000306 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
307 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000308 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000309 bool IsWrite, size_t AccessSizeIndex,
310 Value *SizeArgument);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000311 bool instrumentMemIntrinsic(MemIntrinsic *MI);
312 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000313 Value *Size,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000314 Instruction *InsertBefore, bool IsWrite);
315 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000316 bool runOnFunction(Function &F);
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +0000317 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000318 virtual bool doInitialization(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000319 static char ID; // Pass identification, replacement for typeid
320
321 private:
Kostya Serebryany4b929da2012-11-29 09:54:21 +0000322 void initializeCallbacks(Module &M);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000323
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000324 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany1cdc6e92011-11-18 01:41:06 +0000325 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000326 void FindDynamicInitializers(Module &M);
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000327 bool GlobalIsLinkerInitialized(GlobalVariable *G);
Kostya Serebryany714c67c2014-01-17 11:00:30 +0000328 bool InjectCoverage(Function &F, const ArrayRef<BasicBlock*> AllBlocks);
329 void InjectCoverageAtBlock(Function &F, BasicBlock &BB);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000330
Alexey Samsonovdf624522012-11-29 18:14:24 +0000331 bool CheckInitOrder;
332 bool CheckUseAfterReturn;
333 bool CheckLifetime;
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000334 SmallString<64> BlacklistFile;
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000335
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000336 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000337 const DataLayout *DL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000338 int LongSize;
339 Type *IntptrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000340 ShadowMapping Mapping;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000341 Function *AsanCtorFunction;
342 Function *AsanInitFunction;
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000343 Function *AsanHandleNoReturnFunc;
Bob Wilsonda4147c2013-11-15 07:16:09 +0000344 Function *AsanCovFunction;
Peter Collingbourne015370e2013-07-09 22:02:49 +0000345 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany4273bb02012-07-16 14:09:42 +0000346 // This array is indexed by AccessIsWrite and log2(AccessSize).
347 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000348 // This array is indexed by AccessIsWrite.
349 Function *AsanErrorCallbackSized[2];
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000350 InlineAsm *EmptyAsm;
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000351 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000352
353 friend struct FunctionStackPoisoner;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000354};
Kostya Serebryany874dae62012-07-16 16:15:40 +0000355
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000356class AddressSanitizerModule : public ModulePass {
Kostya Serebryany20a79972012-11-22 03:18:50 +0000357 public:
Alexey Samsonov819eddc2013-03-14 12:38:58 +0000358 AddressSanitizerModule(bool CheckInitOrder = true,
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000359 StringRef BlacklistFile = StringRef())
Alexey Samsonovdf624522012-11-29 18:14:24 +0000360 : ModulePass(ID),
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000361 CheckInitOrder(CheckInitOrder || ClInitializers),
362 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000363 : BlacklistFile) {}
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000364 bool runOnModule(Module &M);
365 static char ID; // Pass identification, replacement for typeid
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000366 virtual const char *getPassName() const {
367 return "AddressSanitizerModule";
368 }
Alexey Samsonov261177a2012-12-04 01:34:23 +0000369
Kostya Serebryany20a79972012-11-22 03:18:50 +0000370 private:
Alexey Samsonov788381b2012-12-25 12:28:20 +0000371 void initializeCallbacks(Module &M);
372
Kostya Serebryany20a79972012-11-22 03:18:50 +0000373 bool ShouldInstrumentGlobal(GlobalVariable *G);
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000374 void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000375 size_t MinRedzoneSizeForGlobal() const {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000376 return RedzoneSizeForScale(Mapping.Scale);
377 }
Kostya Serebryany20a79972012-11-22 03:18:50 +0000378
Alexey Samsonovdf624522012-11-29 18:14:24 +0000379 bool CheckInitOrder;
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000380 SmallString<64> BlacklistFile;
Alexey Samsonov347bcd32013-01-17 11:12:32 +0000381
Peter Collingbourne015370e2013-07-09 22:02:49 +0000382 OwningPtr<SpecialCaseList> BL;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000383 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
384 Type *IntptrTy;
385 LLVMContext *C;
Rafael Espindolaaeff8a92014-02-24 23:12:18 +0000386 const DataLayout *DL;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000387 ShadowMapping Mapping;
Alexey Samsonov788381b2012-12-25 12:28:20 +0000388 Function *AsanPoisonGlobals;
389 Function *AsanUnpoisonGlobals;
390 Function *AsanRegisterGlobals;
391 Function *AsanUnregisterGlobals;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000392};
393
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000394// Stack poisoning does not play well with exception handling.
395// When an exception is thrown, we essentially bypass the code
396// that unpoisones the stack. This is why the run-time library has
397// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
398// stack in the interceptor. This however does not work inside the
399// actual function which catches the exception. Most likely because the
400// compiler hoists the load of the shadow value somewhere too high.
401// This causes asan to report a non-existing bug on 453.povray.
402// It sounds like an LLVM bug.
403struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
404 Function &F;
405 AddressSanitizer &ASan;
406 DIBuilder DIB;
407 LLVMContext *C;
408 Type *IntptrTy;
409 Type *IntptrPtrTy;
Alexey Samsonov1345d352013-01-16 13:23:28 +0000410 ShadowMapping Mapping;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000411
412 SmallVector<AllocaInst*, 16> AllocaVec;
413 SmallVector<Instruction*, 8> RetVec;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000414 unsigned StackAlignment;
415
Kostya Serebryany6805de52013-09-10 13:16:56 +0000416 Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
417 *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000418 Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
419
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000420 // Stores a place and arguments of poisoning/unpoisoning call for alloca.
421 struct AllocaPoisonCall {
422 IntrinsicInst *InsBefore;
Alexey Samsonova788b942013-11-18 14:53:55 +0000423 AllocaInst *AI;
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000424 uint64_t Size;
425 bool DoPoison;
426 };
427 SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
428
429 // Maps Value to an AllocaInst from which the Value is originated.
430 typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
431 AllocaForValueMapTy AllocaForValue;
432
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000433 FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
434 : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
435 IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
Alexey Samsonov1345d352013-01-16 13:23:28 +0000436 Mapping(ASan.Mapping),
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000437 StackAlignment(1 << Mapping.Scale) {}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000438
439 bool runOnFunction() {
440 if (!ClStack) return false;
441 // Collect alloca, ret, lifetime instructions etc.
442 for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
443 DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
444 BasicBlock *BB = *DI;
445 visit(*BB);
446 }
447 if (AllocaVec.empty()) return false;
448
449 initializeCallbacks(*F.getParent());
450
451 poisonStack();
452
453 if (ClDebugStack) {
454 DEBUG(dbgs() << F);
455 }
456 return true;
457 }
458
459 // Finds all static Alloca instructions and puts
460 // poisoned red zones around all of them.
461 // Then unpoison everything back before the function returns.
462 void poisonStack();
463
464 // ----------------------- Visitors.
465 /// \brief Collect all Ret instructions.
466 void visitReturnInst(ReturnInst &RI) {
467 RetVec.push_back(&RI);
468 }
469
470 /// \brief Collect Alloca instructions we want (and can) handle.
471 void visitAllocaInst(AllocaInst &AI) {
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000472 if (!isInterestingAlloca(AI)) return;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000473
474 StackAlignment = std::max(StackAlignment, AI.getAlignment());
475 AllocaVec.push_back(&AI);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000476 }
477
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000478 /// \brief Collect lifetime intrinsic calls to check for use-after-scope
479 /// errors.
480 void visitIntrinsicInst(IntrinsicInst &II) {
481 if (!ASan.CheckLifetime) return;
482 Intrinsic::ID ID = II.getIntrinsicID();
483 if (ID != Intrinsic::lifetime_start &&
484 ID != Intrinsic::lifetime_end)
485 return;
486 // Found lifetime intrinsic, add ASan instrumentation if necessary.
487 ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
488 // If size argument is undefined, don't do anything.
489 if (Size->isMinusOne()) return;
490 // Check that size doesn't saturate uint64_t and can
491 // be stored in IntptrTy.
492 const uint64_t SizeValue = Size->getValue().getLimitedValue();
493 if (SizeValue == ~0ULL ||
494 !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
495 return;
496 // Find alloca instruction that corresponds to llvm.lifetime argument.
497 AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
498 if (!AI) return;
499 bool DoPoison = (ID == Intrinsic::lifetime_end);
Alexey Samsonova788b942013-11-18 14:53:55 +0000500 AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000501 AllocaPoisonCallVec.push_back(APC);
502 }
503
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000504 // ---------------------- Helpers.
505 void initializeCallbacks(Module &M);
506
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000507 // Check if we want (and can) handle this alloca.
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000508 bool isInterestingAlloca(AllocaInst &AI) const {
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000509 return (!AI.isArrayAllocation() && AI.isStaticAlloca() &&
510 AI.getAllocatedType()->isSized() &&
511 // alloca() may be called with 0 size, ignore it.
512 getAllocaSizeInBytes(&AI) > 0);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000513 }
514
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000515 uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000516 Type *Ty = AI->getAllocatedType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000517 uint64_t SizeInBytes = ASan.DL->getTypeAllocSize(Ty);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000518 return SizeInBytes;
519 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +0000520 /// Finds alloca where the value comes from.
521 AllocaInst *findAllocaForValue(Value *V);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000522 void poisonRedZones(const ArrayRef<uint8_t> ShadowBytes, IRBuilder<> &IRB,
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000523 Value *ShadowBase, bool DoPoison);
Jakub Staszak23ec6a92013-08-09 20:53:48 +0000524 void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +0000525
526 void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
527 int Size);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +0000528};
529
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000530} // namespace
531
532char AddressSanitizer::ID = 0;
533INITIALIZE_PASS(AddressSanitizer, "asan",
534 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
535 false, false)
Alexey Samsonovdf624522012-11-29 18:14:24 +0000536FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000537 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000538 StringRef BlacklistFile) {
Alexey Samsonovdf624522012-11-29 18:14:24 +0000539 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000540 CheckLifetime, BlacklistFile);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000541}
542
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000543char AddressSanitizerModule::ID = 0;
544INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
545 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
546 "ModulePass", false, false)
Alexey Samsonovef51c3f2012-12-03 19:09:26 +0000547ModulePass *llvm::createAddressSanitizerModulePass(
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000548 bool CheckInitOrder, StringRef BlacklistFile) {
549 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenkoc94cf8f2012-01-23 11:22:43 +0000550}
551
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000552static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
Michael J. Spencerdf1ecbd72013-05-24 22:23:49 +0000553 size_t Res = countTrailingZeros(TypeSize / 8);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000554 assert(Res < kNumberOfAccessSizes);
555 return Res;
556}
557
Bill Wendling58f8cef2013-08-06 22:52:42 +0000558// \brief Create a constant for Str so that we can pass it to the run-time lib.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000559static GlobalVariable *createPrivateGlobalForString(
560 Module &M, StringRef Str, bool AllowMerging) {
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000561 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000562 // We use private linkage for module-local strings. If they can be merged
563 // with another one, we set the unnamed_addr attribute.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000564 GlobalVariable *GV =
565 new GlobalVariable(M, StrConst->getType(), true,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000566 GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
567 if (AllowMerging)
568 GV->setUnnamedAddr(true);
Kostya Serebryany10cc12f2013-03-18 09:38:39 +0000569 GV->setAlignment(1); // Strings may not be merged w/o setting align 1.
570 return GV;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000571}
572
573static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
574 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000575}
576
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000577Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
578 // Shadow >> scale
Alexey Samsonov1345d352013-01-16 13:23:28 +0000579 Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
580 if (Mapping.Offset == 0)
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000581 return Shadow;
582 // (Shadow >> scale) | offset
Kostya Serebryany4766fe62013-01-23 12:54:55 +0000583 if (Mapping.OrShadowOffset)
584 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
585 else
586 return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000587}
588
Kostya Serebryany874dae62012-07-16 16:15:40 +0000589void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000590 Instruction *OrigIns,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000591 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000592 IRBuilder<> IRB(InsertBefore);
593 if (Size->getType() != IntptrTy)
594 Size = IRB.CreateIntCast(Size, IntptrTy, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000595 // Check the first byte.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000596 instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000597 // Check the last byte.
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000598 IRB.SetInsertPoint(InsertBefore);
599 Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
600 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
601 Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
602 instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000603}
604
605// Instrument memset/memmove/memcpy
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000606bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000607 Value *Dst = MI->getDest();
608 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000609 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000610 Value *Length = MI->getLength();
611
612 Constant *ConstLength = dyn_cast<Constant>(Length);
613 Instruction *InsertBefore = MI;
614 if (ConstLength) {
615 if (ConstLength->isNullValue()) return false;
616 } else {
617 // The size is not a constant so it could be zero -- check at run-time.
618 IRBuilder<> IRB(InsertBefore);
619
620 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryanyeeaf6882012-07-02 11:42:29 +0000621 Constant::getNullValue(Length->getType()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000622 InsertBefore = SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000623 }
624
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000625 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000626 if (Src)
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000627 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000628 return true;
629}
630
Kostya Serebryany90241602012-05-30 09:04:06 +0000631// If I is an interesting memory access, return the PointerOperand
632// and set IsWrite. Otherwise return NULL.
633static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000634 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryany90241602012-05-30 09:04:06 +0000635 if (!ClInstrumentReads) return NULL;
636 *IsWrite = false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000637 return LI->getPointerOperand();
638 }
Kostya Serebryany90241602012-05-30 09:04:06 +0000639 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
640 if (!ClInstrumentWrites) return NULL;
641 *IsWrite = true;
642 return SI->getPointerOperand();
643 }
644 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
645 if (!ClInstrumentAtomics) return NULL;
646 *IsWrite = true;
647 return RMW->getPointerOperand();
648 }
649 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
650 if (!ClInstrumentAtomics) return NULL;
651 *IsWrite = true;
652 return XCHG->getPointerOperand();
653 }
654 return NULL;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000655}
656
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000657bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
658 // If a global variable does not have dynamic initialization we don't
659 // have to instrument it. However, if a global does not have initializer
660 // at all, we assume it has dynamic initializer (in other TU).
661 return G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G);
662}
663
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000664void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann4a127062012-09-17 14:20:57 +0000665 bool IsWrite = false;
Kostya Serebryany90241602012-05-30 09:04:06 +0000666 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
667 assert(Addr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000668 if (ClOpt && ClOptGlobals) {
669 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
670 // If initialization order checking is disabled, a simple access to a
671 // dynamically initialized global is always valid.
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000672 if (!CheckInitOrder || GlobalIsLinkerInitialized(G)) {
673 NumOptimizedAccessesToGlobalVar++;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000674 return;
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000675 }
676 }
677 ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr);
678 if (CE && CE->isGEPWithNoNotionalOverIndexing()) {
679 if (GlobalVariable *G = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
680 if (CE->getOperand(1)->isNullValue() && GlobalIsLinkerInitialized(G)) {
681 NumOptimizedAccessesToGlobalArray++;
682 return;
683 }
684 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000685 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000686 }
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000687
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000688 Type *OrigPtrTy = Addr->getType();
689 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
690
691 assert(OrigTy->isSized());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000692 uint32_t TypeSize = DL->getTypeStoreSizeInBits(OrigTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000693
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000694 assert((TypeSize % 8) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000695
Kostya Serebryanyd3d23be2013-10-16 14:06:14 +0000696 if (IsWrite)
697 NumInstrumentedWrites++;
698 else
699 NumInstrumentedReads++;
700
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000701 // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
702 if (TypeSize == 8 || TypeSize == 16 ||
703 TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
704 return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
705 // Instrument unusual size (but still multiple of 8).
706 // We can not do it with a single check, so we do 1-byte check for the first
707 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
708 // to report the actual access size.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000709 IRBuilder<> IRB(I);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000710 Value *LastByte = IRB.CreateIntToPtr(
711 IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
712 ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
713 OrigPtrTy);
714 Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
715 instrumentAddress(I, I, Addr, 8, IsWrite, Size);
716 instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000717}
718
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000719// Validate the result of Module::getOrInsertFunction called for an interface
720// function of AddressSanitizer. If the instrumented module defines a function
721// with the same name, their prototypes must match, otherwise
722// getOrInsertFunction returns a bitcast.
Kostya Serebryany20a79972012-11-22 03:18:50 +0000723static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko056e27e2012-04-23 10:47:31 +0000724 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
725 FuncOrBitcast->dump();
726 report_fatal_error("trying to redefine an AddressSanitizer "
727 "interface function");
728}
729
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000730Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000731 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000732 bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000733 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000734 CallInst *Call = SizeArgument
735 ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
736 : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
737
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000738 // We don't do Call->setDoesNotReturn() because the BB already has
739 // UnreachableInst at the end.
740 // This EmptyAsm is required to avoid callback merge.
741 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3411f2e2012-01-06 18:09:21 +0000742 return Call;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000743}
744
Kostya Serebryanyc4ce5df2012-07-16 17:12:07 +0000745Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryany874dae62012-07-16 16:15:40 +0000746 Value *ShadowValue,
747 uint32_t TypeSize) {
Alexey Samsonov1345d352013-01-16 13:23:28 +0000748 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryany874dae62012-07-16 16:15:40 +0000749 // Addr & (Granularity - 1)
750 Value *LastAccessedByte = IRB.CreateAnd(
751 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
752 // (Addr & (Granularity - 1)) + size - 1
753 if (TypeSize / 8 > 1)
754 LastAccessedByte = IRB.CreateAdd(
755 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
756 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
757 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000758 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000759 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
760 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
761}
762
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000763void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000764 Instruction *InsertBefore,
765 Value *Addr, uint32_t TypeSize,
766 bool IsWrite, Value *SizeArgument) {
767 IRBuilder<> IRB(InsertBefore);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000768 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
769
770 Type *ShadowTy = IntegerType::get(
Alexey Samsonov1345d352013-01-16 13:23:28 +0000771 *C, std::max(8U, TypeSize >> Mapping.Scale));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000772 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
773 Value *ShadowPtr = memToShadow(AddrLong, IRB);
774 Value *CmpVal = Constant::getNullValue(ShadowTy);
775 Value *ShadowValue = IRB.CreateLoad(
776 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
777
778 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany0f7a80d2012-08-13 14:08:46 +0000779 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Alexey Samsonov1345d352013-01-16 13:23:28 +0000780 size_t Granularity = 1 << Mapping.Scale;
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000781 TerminatorInst *CrashTerm = 0;
782
Kostya Serebryany1e575ab2012-08-15 08:58:58 +0000783 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov8eb77d82012-10-19 10:48:31 +0000784 TerminatorInst *CheckTerm =
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000785 SplitBlockAndInsertIfThen(Cmp, InsertBefore, false);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000786 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000787 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000788 IRB.SetInsertPoint(CheckTerm);
789 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +0000790 BasicBlock *CrashBlock =
791 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000792 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf02c6062012-07-20 09:54:50 +0000793 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
794 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryany874dae62012-07-16 16:15:40 +0000795 } else {
Evgeniy Stepanova9164e92013-12-19 13:29:56 +0000796 CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000797 }
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000798
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +0000799 Instruction *Crash = generateCrashCode(
800 CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
Kostya Serebryanyfda7a132012-08-14 14:04:51 +0000801 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000802}
803
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000804void AddressSanitizerModule::createInitializerPoisonCalls(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000805 Module &M, GlobalValue *ModuleName) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000806 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
807 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
808 // If that function is not present, this TU contains no globals, or they have
809 // all been optimized away
810 if (!GlobalInit)
811 return;
812
813 // Set up the arguments to our poison/unpoison functions.
814 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
815
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000816 // Add a call to poison all external globals before the given function starts.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000817 Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
818 IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000819
820 // Add calls to unpoison all globals before each return instruction.
821 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
822 I != E; ++I) {
823 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
824 CallInst::Create(AsanUnpoisonGlobals, "", RI);
825 }
826 }
827}
828
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000829bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000830 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany20343352012-10-17 13:40:06 +0000831 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000832
Kostya Serebryany2fa38f82012-09-05 07:29:56 +0000833 if (BL->isIn(*G)) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000834 if (!Ty->isSized()) return false;
835 if (!G->hasInitializer()) return false;
Kostya Serebryany139a9372012-11-20 14:16:08 +0000836 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000837 // Touch only those globals that will not be defined in other modules.
838 // Don't handle ODR type linkages since other modules may be built w/o asan.
839 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
840 G->getLinkage() != GlobalVariable::PrivateLinkage &&
841 G->getLinkage() != GlobalVariable::InternalLinkage)
842 return false;
843 // Two problems with thread-locals:
844 // - The address of the main thread's copy can't be computed at link-time.
845 // - Need to poison all copies, not just the main thread's one.
846 if (G->isThreadLocal())
847 return false;
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000848 // For now, just ignore this Global if the alignment is large.
849 if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000850
851 // Ignore all the globals with the names starting with "\01L_OBJC_".
852 // Many of those are put into the .cstring section. The linker compresses
853 // that section by removing the spare \0s after the string terminator, so
854 // our redzones get broken.
855 if ((G->getName().find("\01L_OBJC_") == 0) ||
856 (G->getName().find("\01l_OBJC_") == 0)) {
857 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
858 return false;
859 }
860
861 if (G->hasSection()) {
862 StringRef Section(G->getSection());
863 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
864 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
865 // them.
866 if ((Section.find("__OBJC,") == 0) ||
867 (Section.find("__DATA, __objc_") == 0)) {
868 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
869 return false;
870 }
871 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
872 // Constant CFString instances are compiled in the following way:
873 // -- the string buffer is emitted into
874 // __TEXT,__cstring,cstring_literals
875 // -- the constant NSConstantString structure referencing that buffer
876 // is placed into __DATA,__cfstring
877 // Therefore there's no point in placing redzones into __DATA,__cfstring.
878 // Moreover, it causes the linker to crash on OS X 10.7
879 if (Section.find("__DATA,__cfstring") == 0) {
880 DEBUG(dbgs() << "Ignoring CFString: " << *G);
881 return false;
882 }
883 }
884
885 return true;
886}
887
Alexey Samsonov788381b2012-12-25 12:28:20 +0000888void AddressSanitizerModule::initializeCallbacks(Module &M) {
889 IRBuilder<> IRB(*C);
890 // Declare our poisoning and unpoisoning functions.
891 AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000892 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
Alexey Samsonov788381b2012-12-25 12:28:20 +0000893 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
894 AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
895 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
896 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
897 // Declare functions that register/unregister globals.
898 AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
899 kAsanRegisterGlobalsName, IRB.getVoidTy(),
900 IntptrTy, IntptrTy, NULL));
901 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
902 AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
903 kAsanUnregisterGlobalsName,
904 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
905 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
906}
907
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000908// This function replaces all global variables with new variables that have
909// trailing redzones. It also creates a function that poisons
910// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000911bool AddressSanitizerModule::runOnModule(Module &M) {
912 if (!ClGlobals) return false;
Rafael Espindola93512512014-02-25 17:30:31 +0000913
914 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
915 if (!DLP)
Kostya Serebryanydfe9e792012-11-28 10:31:36 +0000916 return false;
Rafael Espindola93512512014-02-25 17:30:31 +0000917 DL = &DLP->getDataLayout();
918
Alexey Samsonove4b5fb82013-08-12 11:46:09 +0000919 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Alexey Samsonov9a956e82012-11-29 18:27:01 +0000920 if (BL->isIn(M)) return false;
Kostya Serebryany20a79972012-11-22 03:18:50 +0000921 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000922 int LongSize = DL->getPointerSizeInBits();
Alexey Samsonov1345d352013-01-16 13:23:28 +0000923 IntptrTy = Type::getIntNTy(*C, LongSize);
Evgeniy Stepanov13665362014-01-16 10:19:12 +0000924 Mapping = getShadowMapping(M, LongSize);
Alexey Samsonov788381b2012-12-25 12:28:20 +0000925 initializeCallbacks(M);
926 DynamicallyInitializedGlobals.Init(M);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000927
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000928 SmallVector<GlobalVariable *, 16> GlobalsToChange;
929
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000930 for (Module::GlobalListType::iterator G = M.global_begin(),
931 E = M.global_end(); G != E; ++G) {
932 if (ShouldInstrumentGlobal(G))
933 GlobalsToChange.push_back(G);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000934 }
935
936 size_t n = GlobalsToChange.size();
937 if (n == 0) return false;
938
939 // A global is described by a structure
940 // size_t beg;
941 // size_t size;
942 // size_t size_with_redzone;
943 // const char *name;
Kostya Serebryanybd016bb2013-03-18 08:05:29 +0000944 // const char *module_name;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000945 // size_t has_dynamic_init;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000946 // We initialize an array of such structures and pass it to a run-time call.
947 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000948 IntptrTy, IntptrTy,
Kostya Serebryanybd016bb2013-03-18 08:05:29 +0000949 IntptrTy, IntptrTy, NULL);
Rafael Espindola44fee4e2013-10-01 13:32:03 +0000950 SmallVector<Constant *, 16> Initializers(n);
Kostya Serebryany20a79972012-11-22 03:18:50 +0000951
952 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
953 assert(CtorFunc);
954 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000955
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000956 bool HasDynamicallyInitializedGlobals = false;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000957
Alexey Samsonove1e26bf2013-03-26 13:05:41 +0000958 // We shouldn't merge same module names, as this string serves as unique
959 // module ID in runtime.
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000960 GlobalVariable *ModuleName = createPrivateGlobalForString(
961 M, M.getModuleIdentifier(), /*AllowMerging*/false);
Kostya Serebryanybd016bb2013-03-18 08:05:29 +0000962
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000963 for (size_t i = 0; i < n; i++) {
Kostya Serebryanye35d59a2013-01-24 10:43:50 +0000964 static const uint64_t kMaxGlobalRedzone = 1 << 18;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000965 GlobalVariable *G = GlobalsToChange[i];
966 PointerType *PtrTy = cast<PointerType>(G->getType());
967 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000968 uint64_t SizeInBytes = DL->getTypeAllocSize(Ty);
Kostya Serebryany4fb78012013-12-06 09:00:17 +0000969 uint64_t MinRZ = MinRedzoneSizeForGlobal();
Kostya Serebryany87191f62013-01-24 10:35:40 +0000970 // MinRZ <= RZ <= kMaxGlobalRedzone
971 // and trying to make RZ to be ~ 1/4 of SizeInBytes.
Kostya Serebryanye35d59a2013-01-24 10:43:50 +0000972 uint64_t RZ = std::max(MinRZ,
Kostya Serebryany87191f62013-01-24 10:35:40 +0000973 std::min(kMaxGlobalRedzone,
974 (SizeInBytes / MinRZ / 4) * MinRZ));
975 uint64_t RightRedzoneSize = RZ;
976 // Round up to MinRZ
977 if (SizeInBytes % MinRZ)
978 RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
979 assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000980 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +0000981 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyb3bd6052012-11-20 13:00:01 +0000982 bool GlobalHasDynamicInitializer =
983 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany2fa38f82012-09-05 07:29:56 +0000984 // Don't check initialization order if this global is blacklisted.
Peter Collingbourne49062a92013-07-09 22:03:17 +0000985 GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000986
987 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
988 Constant *NewInitializer = ConstantStruct::get(
989 NewTy, G->getInitializer(),
990 Constant::getNullValue(RightRedZoneTy), NULL);
991
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +0000992 GlobalVariable *Name =
993 createPrivateGlobalForString(M, G->getName(), /*AllowMerging*/true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000994
995 // Create a new global variable with enough space for a redzone.
Bill Wendling58f8cef2013-08-06 22:52:42 +0000996 GlobalValue::LinkageTypes Linkage = G->getLinkage();
997 if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
998 Linkage = GlobalValue::InternalLinkage;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +0000999 GlobalVariable *NewGlobal = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001000 M, NewTy, G->isConstant(), Linkage,
Hans Wennborgcbe34b42012-06-23 11:37:03 +00001001 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001002 NewGlobal->copyAttributesFrom(G);
Kostya Serebryany87191f62013-01-24 10:35:40 +00001003 NewGlobal->setAlignment(MinRZ);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001004
1005 Value *Indices2[2];
1006 Indices2[0] = IRB.getInt32(0);
1007 Indices2[1] = IRB.getInt32(0);
1008
1009 G->replaceAllUsesWith(
Kostya Serebryany7471d132012-01-28 04:27:16 +00001010 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001011 NewGlobal->takeName(G);
1012 G->eraseFromParent();
1013
1014 Initializers[i] = ConstantStruct::get(
1015 GlobalStructTy,
1016 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
1017 ConstantInt::get(IntptrTy, SizeInBytes),
1018 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1019 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryanybd016bb2013-03-18 08:05:29 +00001020 ConstantExpr::getPointerCast(ModuleName, IntptrTy),
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001021 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001022 NULL);
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001023
1024 // Populate the first and last globals declared in this TU.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001025 if (CheckInitOrder && GlobalHasDynamicInitializer)
1026 HasDynamicallyInitializedGlobals = true;
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001027
Kostya Serebryany20343352012-10-17 13:40:06 +00001028 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001029 }
1030
1031 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1032 GlobalVariable *AllGlobals = new GlobalVariable(
Bill Wendling58f8cef2013-08-06 22:52:42 +00001033 M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001034 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1035
Kostya Serebryanyf4be0192012-08-21 08:24:25 +00001036 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonove1e26bf2013-03-26 13:05:41 +00001037 if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1038 createInitializerPoisonCalls(M, ModuleName);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001039 IRB.CreateCall2(AsanRegisterGlobals,
1040 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1041 ConstantInt::get(IntptrTy, n));
1042
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001043 // We also need to unregister globals at the end, e.g. when a shared library
1044 // gets closed.
1045 Function *AsanDtorFunction = Function::Create(
1046 FunctionType::get(Type::getVoidTy(*C), false),
1047 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1048 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1049 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001050 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
1051 IRB.CreatePointerCast(AllGlobals, IntptrTy),
1052 ConstantInt::get(IntptrTy, n));
1053 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
1054
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001055 DEBUG(dbgs() << M);
1056 return true;
1057}
1058
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001059void AddressSanitizer::initializeCallbacks(Module &M) {
1060 IRBuilder<> IRB(*C);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001061 // Create __asan_report* callbacks.
1062 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1063 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1064 AccessSizeIndex++) {
1065 // IsWrite and TypeSize are encoded in the function name.
1066 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
1067 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany986b8da2012-07-17 11:04:12 +00001068 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany157a5152012-11-07 12:42:18 +00001069 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
1070 checkInterfaceFunction(M.getOrInsertFunction(
1071 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001072 }
1073 }
Kostya Serebryany3ece9bea2013-02-19 11:29:21 +00001074 AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
1075 kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1076 AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
1077 kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001078
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001079 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1080 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001081 AsanCovFunction = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001082 kAsanCovName, IRB.getVoidTy(), NULL));
Kostya Serebryanyf02c6062012-07-20 09:54:50 +00001083 // We insert an empty inline asm after __asan_report* to avoid callback merge.
1084 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1085 StringRef(""), StringRef(""),
1086 /*hasSideEffects=*/true);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001087}
1088
1089// virtual
1090bool AddressSanitizer::doInitialization(Module &M) {
1091 // Initialize the private fields. No one has accessed them before.
Rafael Espindola93512512014-02-25 17:30:31 +00001092 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
1093 if (!DLP)
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001094 return false;
Rafael Espindola93512512014-02-25 17:30:31 +00001095 DL = &DLP->getDataLayout();
1096
Alexey Samsonove4b5fb82013-08-12 11:46:09 +00001097 BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001098 DynamicallyInitializedGlobals.Init(M);
1099
1100 C = &(M.getContext());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001101 LongSize = DL->getPointerSizeInBits();
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001102 IntptrTy = Type::getIntNTy(*C, LongSize);
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001103
1104 AsanCtorFunction = Function::Create(
1105 FunctionType::get(Type::getVoidTy(*C), false),
1106 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
1107 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
1108 // call __asan_init in the module ctor.
1109 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
1110 AsanInitFunction = checkInterfaceFunction(
1111 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
1112 AsanInitFunction->setLinkage(Function::ExternalLinkage);
1113 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany4273bb02012-07-16 14:09:42 +00001114
Evgeniy Stepanov13665362014-01-16 10:19:12 +00001115 Mapping = getShadowMapping(M, LongSize);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001116
Kostya Serebryanycd1aba82011-12-15 21:59:03 +00001117 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001118 return true;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001119}
1120
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001121bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1122 // For each NSObject descendant having a +load method, this method is invoked
1123 // by the ObjC runtime before any of the static constructors is called.
1124 // Therefore we need to instrument such methods with a call to __asan_init
1125 // at the beginning in order to initialize our runtime before any access to
1126 // the shadow memory.
1127 // We cannot just ignore these methods, because they may call other
1128 // instrumented functions.
1129 if (F.getName().find(" load]") != std::string::npos) {
1130 IRBuilder<> IRB(F.begin()->begin());
1131 IRB.CreateCall(AsanInitFunction);
1132 return true;
1133 }
1134 return false;
1135}
1136
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001137void AddressSanitizer::InjectCoverageAtBlock(Function &F, BasicBlock &BB) {
1138 BasicBlock::iterator IP = BB.getFirstInsertionPt(), BE = BB.end();
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001139 // Skip static allocas at the top of the entry block so they don't become
1140 // dynamic when we split the block. If we used our optimized stack layout,
1141 // then there will only be one alloca and it will come first.
Reid Kleckner30b2a9a2013-12-10 21:49:28 +00001142 for (; IP != BE; ++IP) {
1143 AllocaInst *AI = dyn_cast<AllocaInst>(IP);
1144 if (!AI || !AI->isStaticAlloca())
1145 break;
1146 }
1147
1148 IRBuilder<> IRB(IP);
Bob Wilsonda4147c2013-11-15 07:16:09 +00001149 Type *Int8Ty = IRB.getInt8Ty();
1150 GlobalVariable *Guard = new GlobalVariable(
Kostya Serebryany0604c622013-11-15 09:52:05 +00001151 *F.getParent(), Int8Ty, false, GlobalValue::PrivateLinkage,
Bob Wilsonda4147c2013-11-15 07:16:09 +00001152 Constant::getNullValue(Int8Ty), "__asan_gen_cov_" + F.getName());
1153 LoadInst *Load = IRB.CreateLoad(Guard);
1154 Load->setAtomic(Monotonic);
1155 Load->setAlignment(1);
1156 Value *Cmp = IRB.CreateICmpEQ(Constant::getNullValue(Int8Ty), Load);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001157 Instruction *Ins = SplitBlockAndInsertIfThen(
1158 Cmp, IP, false, MDBuilder(*C).createBranchWeights(1, 100000));
Bob Wilsonda4147c2013-11-15 07:16:09 +00001159 IRB.SetInsertPoint(Ins);
1160 // We pass &F to __sanitizer_cov. We could avoid this and rely on
1161 // GET_CALLER_PC, but having the PC of the first instruction is just nice.
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001162 Instruction *Call = IRB.CreateCall(AsanCovFunction);
1163 Call->setDebugLoc(IP->getDebugLoc());
Bob Wilsonda4147c2013-11-15 07:16:09 +00001164 StoreInst *Store = IRB.CreateStore(ConstantInt::get(Int8Ty, 1), Guard);
1165 Store->setAtomic(Monotonic);
1166 Store->setAlignment(1);
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001167}
1168
1169// Poor man's coverage that works with ASan.
1170// We create a Guard boolean variable with the same linkage
1171// as the function and inject this code into the entry block (-asan-coverage=1)
1172// or all blocks (-asan-coverage=2):
1173// if (*Guard) {
1174// __sanitizer_cov(&F);
1175// *Guard = 1;
1176// }
1177// The accesses to Guard are atomic. The rest of the logic is
1178// in __sanitizer_cov (it's fine to call it more than once).
1179//
1180// This coverage implementation provides very limited data:
1181// it only tells if a given function (block) was ever executed.
1182// No counters, no per-edge data.
1183// But for many use cases this is what we need and the added slowdown
1184// is negligible. This simple implementation will probably be obsoleted
1185// by the upcoming Clang-based coverage implementation.
1186// By having it here and now we hope to
1187// a) get the functionality to users earlier and
1188// b) collect usage statistics to help improve Clang coverage design.
1189bool AddressSanitizer::InjectCoverage(Function &F,
1190 const ArrayRef<BasicBlock *> AllBlocks) {
1191 if (!ClCoverage) return false;
1192
1193 if (ClCoverage == 1) {
1194 InjectCoverageAtBlock(F, F.getEntryBlock());
1195 } else {
1196 for (size_t i = 0, n = AllBlocks.size(); i < n; i++)
1197 InjectCoverageAtBlock(F, *AllBlocks[i]);
1198 }
Bob Wilsonda4147c2013-11-15 07:16:09 +00001199 return true;
1200}
1201
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001202bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001203 if (BL->isIn(F)) return false;
1204 if (&F == AsanCtorFunction) return false;
Kostya Serebryany6b5b58d2013-03-18 07:33:49 +00001205 if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
Kostya Serebryany20343352012-10-17 13:40:06 +00001206 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany4b929da2012-11-29 09:54:21 +00001207 initializeCallbacks(*F.getParent());
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001208
Kostya Serebryanycf880b92013-02-26 06:58:09 +00001209 // If needed, insert __asan_init before checking for SanitizeAddress attr.
Kostya Serebryany22ddcfd2012-01-30 23:50:10 +00001210 maybeInsertAsanInitAtFunctionEntry(F);
1211
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001212 if (!F.hasFnAttribute(Attribute::SanitizeAddress))
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001213 return false;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001214
1215 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1216 return false;
Bill Wendlingc9b22d72012-10-09 07:45:08 +00001217
1218 // We want to instrument every address only once per basic block (unless there
1219 // are calls between uses).
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001220 SmallSet<Value*, 16> TempsToInstrument;
1221 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001222 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001223 SmallVector<BasicBlock*, 16> AllBlocks;
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001224 int NumAllocas = 0;
Kostya Serebryany90241602012-05-30 09:04:06 +00001225 bool IsWrite;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001226
1227 // Fill the set of memory operations to instrument.
1228 for (Function::iterator FI = F.begin(), FE = F.end();
1229 FI != FE; ++FI) {
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001230 AllBlocks.push_back(FI);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001231 TempsToInstrument.clear();
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001232 int NumInsnsPerBB = 0;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001233 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1234 BI != BE; ++BI) {
Kostya Serebryany687d0782012-01-11 18:15:23 +00001235 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryany90241602012-05-30 09:04:06 +00001236 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001237 if (ClOpt && ClOptSameTemp) {
1238 if (!TempsToInstrument.insert(Addr))
1239 continue; // We've seen this temp in the current BB.
1240 }
1241 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1242 // ok, take it.
1243 } else {
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001244 if (isa<AllocaInst>(BI))
1245 NumAllocas++;
Kostya Serebryany699ac282013-02-20 12:35:15 +00001246 CallSite CS(BI);
1247 if (CS) {
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001248 // A call inside BB.
1249 TempsToInstrument.clear();
Kostya Serebryany699ac282013-02-20 12:35:15 +00001250 if (CS.doesNotReturn())
1251 NoReturnCalls.push_back(CS.getInstruction());
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001252 }
1253 continue;
1254 }
1255 ToInstrument.push_back(BI);
Kostya Serebryanyc387ca72012-06-28 09:34:41 +00001256 NumInsnsPerBB++;
1257 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1258 break;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001259 }
1260 }
1261
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001262 Function *UninstrumentedDuplicate = 0;
1263 bool LikelyToInstrument =
1264 !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
1265 if (ClKeepUninstrumented && LikelyToInstrument) {
1266 ValueToValueMapTy VMap;
1267 UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
1268 UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
1269 UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
1270 F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
1271 }
1272
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001273 // Instrument.
1274 int NumInstrumented = 0;
1275 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1276 Instruction *Inst = ToInstrument[i];
1277 if (ClDebugMin < 0 || ClDebugMax < 0 ||
1278 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryany90241602012-05-30 09:04:06 +00001279 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001280 instrumentMop(Inst);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001281 else
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001282 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001283 }
1284 NumInstrumented++;
1285 }
1286
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001287 FunctionStackPoisoner FSP(F, *this);
1288 bool ChangedStack = FSP.runOnFunction();
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001289
1290 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
1291 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
1292 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
1293 Instruction *CI = NoReturnCalls[i];
1294 IRBuilder<> IRB(CI);
Kostya Serebryanyb0e25062012-10-15 14:20:06 +00001295 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany154a54d2012-02-08 21:36:17 +00001296 }
1297
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001298 bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Bob Wilsonda4147c2013-11-15 07:16:09 +00001299
Kostya Serebryany714c67c2014-01-17 11:00:30 +00001300 if (InjectCoverage(F, AllBlocks))
Bob Wilsonda4147c2013-11-15 07:16:09 +00001301 res = true;
1302
Kostya Serebryany9f5213f2013-06-26 09:18:17 +00001303 DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
1304
1305 if (ClKeepUninstrumented) {
1306 if (!res) {
1307 // No instrumentation is done, no need for the duplicate.
1308 if (UninstrumentedDuplicate)
1309 UninstrumentedDuplicate->eraseFromParent();
1310 } else {
1311 // The function was instrumented. We must have the duplicate.
1312 assert(UninstrumentedDuplicate);
1313 UninstrumentedDuplicate->setSection("NOASAN");
1314 assert(!F.hasSection());
1315 F.setSection("ASAN");
1316 }
1317 }
1318
1319 return res;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001320}
1321
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001322// Workaround for bug 11395: we don't want to instrument stack in functions
1323// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
1324// FIXME: remove once the bug 11395 is fixed.
1325bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1326 if (LongSize != 32) return false;
1327 CallInst *CI = dyn_cast<CallInst>(I);
1328 if (!CI || !CI->isInlineAsm()) return false;
1329 if (CI->getNumArgOperands() <= 5) return false;
1330 // We have inline assembly with quite a few arguments.
1331 return true;
1332}
1333
1334void FunctionStackPoisoner::initializeCallbacks(Module &M) {
1335 IRBuilder<> IRB(*C);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001336 for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1337 std::string Suffix = itostr(i);
1338 AsanStackMallocFunc[i] = checkInterfaceFunction(
1339 M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1340 IntptrTy, IntptrTy, NULL));
1341 AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1342 kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1343 IntptrTy, IntptrTy, NULL));
1344 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001345 AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1346 kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1347 AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
1348 kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1349}
1350
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001351void
1352FunctionStackPoisoner::poisonRedZones(const ArrayRef<uint8_t> ShadowBytes,
1353 IRBuilder<> &IRB, Value *ShadowBase,
1354 bool DoPoison) {
1355 size_t n = ShadowBytes.size();
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001356 size_t i = 0;
1357 // We need to (un)poison n bytes of stack shadow. Poison as many as we can
1358 // using 64-bit stores (if we are on 64-bit arch), then poison the rest
1359 // with 32-bit stores, then with 16-byte stores, then with 8-byte stores.
1360 for (size_t LargeStoreSizeInBytes = ASan.LongSize / 8;
1361 LargeStoreSizeInBytes != 0; LargeStoreSizeInBytes /= 2) {
1362 for (; i + LargeStoreSizeInBytes - 1 < n; i += LargeStoreSizeInBytes) {
1363 uint64_t Val = 0;
1364 for (size_t j = 0; j < LargeStoreSizeInBytes; j++) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001365 if (ASan.DL->isLittleEndian())
Kostya Serebryanyff7bde12013-12-23 09:24:36 +00001366 Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
1367 else
1368 Val = (Val << 8) | ShadowBytes[i + j];
1369 }
1370 if (!Val) continue;
1371 Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1372 Type *StoreTy = Type::getIntNTy(*C, LargeStoreSizeInBytes * 8);
1373 Value *Poison = ConstantInt::get(StoreTy, DoPoison ? Val : 0);
1374 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, StoreTy->getPointerTo()));
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001375 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001376 }
1377}
1378
Kostya Serebryany6805de52013-09-10 13:16:56 +00001379// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1380// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1381static int StackMallocSizeClass(uint64_t LocalStackSize) {
1382 assert(LocalStackSize <= kMaxStackMallocSize);
1383 uint64_t MaxSize = kMinStackMallocSize;
1384 for (int i = 0; ; i++, MaxSize *= 2)
1385 if (LocalStackSize <= MaxSize)
1386 return i;
1387 llvm_unreachable("impossible LocalStackSize");
1388}
1389
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001390// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1391// We can not use MemSet intrinsic because it may end up calling the actual
1392// memset. Size is a multiple of 8.
1393// Currently this generates 8-byte stores on x86_64; it may be better to
1394// generate wider stores.
1395void FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1396 IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1397 assert(!(Size % 8));
1398 assert(kAsanStackAfterReturnMagic == 0xf5);
1399 for (int i = 0; i < Size; i += 8) {
1400 Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1401 IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1402 IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1403 }
1404}
1405
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001406void FunctionStackPoisoner::poisonStack() {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001407 int StackMallocIdx = -1;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001408
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001409 assert(AllocaVec.size() > 0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001410 Instruction *InsBefore = AllocaVec[0];
1411 IRBuilder<> IRB(InsBefore);
1412
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001413 SmallVector<ASanStackVariableDescription, 16> SVD;
1414 SVD.reserve(AllocaVec.size());
1415 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1416 AllocaInst *AI = AllocaVec[i];
1417 ASanStackVariableDescription D = { AI->getName().data(),
1418 getAllocaSizeInBytes(AI),
1419 AI->getAlignment(), AI, 0};
1420 SVD.push_back(D);
1421 }
1422 // Minimal header size (left redzone) is 4 pointers,
1423 // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
1424 size_t MinHeaderSize = ASan.LongSize / 2;
1425 ASanStackFrameLayout L;
1426 ComputeASanStackFrameLayout(SVD, 1UL << Mapping.Scale, MinHeaderSize, &L);
1427 DEBUG(dbgs() << L.DescriptionString << " --- " << L.FrameSize << "\n");
1428 uint64_t LocalStackSize = L.FrameSize;
1429 bool DoStackMalloc =
1430 ASan.CheckUseAfterReturn && LocalStackSize <= kMaxStackMallocSize;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001431
1432 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1433 AllocaInst *MyAlloca =
1434 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001435 assert((ClRealignStack & (ClRealignStack - 1)) == 0);
1436 size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
1437 MyAlloca->setAlignment(FrameAlignment);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001438 assert(MyAlloca->isStaticAlloca());
1439 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1440 Value *LocalStackBase = OrigStackBase;
1441
1442 if (DoStackMalloc) {
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001443 // LocalStackBase = OrigStackBase
1444 // if (__asan_option_detect_stack_use_after_return)
1445 // LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
Kostya Serebryany6805de52013-09-10 13:16:56 +00001446 StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1447 assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001448 Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1449 kAsanOptionDetectUAR, IRB.getInt32Ty());
1450 Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1451 Constant::getNullValue(IRB.getInt32Ty()));
Evgeniy Stepanova9164e92013-12-19 13:29:56 +00001452 Instruction *Term = SplitBlockAndInsertIfThen(Cmp, InsBefore, false);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001453 BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1454 IRBuilder<> IRBIf(Term);
1455 LocalStackBase = IRBIf.CreateCall2(
1456 AsanStackMallocFunc[StackMallocIdx],
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001457 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
Kostya Serebryanyf3223822013-09-18 14:07:14 +00001458 BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1459 IRB.SetInsertPoint(InsBefore);
1460 PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1461 Phi->addIncoming(OrigStackBase, CmpBlock);
1462 Phi->addIncoming(LocalStackBase, SetBlock);
1463 LocalStackBase = Phi;
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001464 }
1465
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001466 // Insert poison calls for lifetime intrinsics for alloca.
1467 bool HavePoisonedAllocas = false;
1468 for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
1469 const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
Alexey Samsonova788b942013-11-18 14:53:55 +00001470 assert(APC.InsBefore);
1471 assert(APC.AI);
1472 IRBuilder<> IRB(APC.InsBefore);
1473 poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001474 HavePoisonedAllocas |= APC.DoPoison;
1475 }
1476
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001477 // Replace Alloca instructions with base+offset.
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001478 for (size_t i = 0, n = SVD.size(); i < n; i++) {
1479 AllocaInst *AI = SVD[i].AI;
Alexey Samsonov261177a2012-12-04 01:34:23 +00001480 Value *NewAllocaPtr = IRB.CreateIntToPtr(
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001481 IRB.CreateAdd(LocalStackBase,
1482 ConstantInt::get(IntptrTy, SVD[i].Offset)),
1483 AI->getType());
Alexey Samsonov3d43b632012-12-12 14:31:53 +00001484 replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001485 AI->replaceAllUsesWith(NewAllocaPtr);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001486 }
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001487
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001488 // The left-most redzone has enough space for at least 4 pointers.
1489 // Write the Magic value to redzone[0].
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001490 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1491 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1492 BasePlus0);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001493 // Write the frame description constant to redzone[1].
1494 Value *BasePlus1 = IRB.CreateIntToPtr(
1495 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
1496 IntptrPtrTy);
Alexey Samsonov9bdb63a2012-11-02 12:20:34 +00001497 GlobalVariable *StackDescriptionGlobal =
Alexander Potapenkodaf96ae2013-12-25 14:22:15 +00001498 createPrivateGlobalForString(*F.getParent(), L.DescriptionString,
1499 /*AllowMerging*/true);
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001500 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
1501 IntptrTy);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001502 IRB.CreateStore(Description, BasePlus1);
Kostya Serebryanycdd35a92013-03-22 10:37:20 +00001503 // Write the PC to redzone[2].
1504 Value *BasePlus2 = IRB.CreateIntToPtr(
1505 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
1506 2 * ASan.LongSize/8)),
1507 IntptrPtrTy);
1508 IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001509
1510 // Poison the stack redzones at the entry.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001511 Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
Kostya Serebryany4fb78012013-12-06 09:00:17 +00001512 poisonRedZones(L.ShadowBytes, IRB, ShadowBase, true);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001513
Kostya Serebryany530e2072013-12-23 14:15:08 +00001514 // (Un)poison the stack before all ret instructions.
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001515 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1516 Instruction *Ret = RetVec[i];
1517 IRBuilder<> IRBRet(Ret);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001518 // Mark the current frame as retired.
1519 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1520 BasePlus0);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001521 if (DoStackMalloc) {
Kostya Serebryany6805de52013-09-10 13:16:56 +00001522 assert(StackMallocIdx >= 0);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001523 // if LocalStackBase != OrigStackBase:
1524 // // In use-after-return mode, poison the whole stack frame.
1525 // if StackMallocIdx <= 4
1526 // // For small sizes inline the whole thing:
1527 // memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1528 // **SavedFlagPtr(LocalStackBase) = 0
1529 // else
1530 // __asan_stack_free_N(LocalStackBase, OrigStackBase)
1531 // else
1532 // <This is not a fake stack; unpoison the redzones>
1533 Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1534 TerminatorInst *ThenTerm, *ElseTerm;
1535 SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
1536
1537 IRBuilder<> IRBPoison(ThenTerm);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001538 if (StackMallocIdx <= 4) {
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001539 int ClassSize = kMinStackMallocSize << StackMallocIdx;
1540 SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1541 ClassSize >> Mapping.Scale);
1542 Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1543 LocalStackBase,
1544 ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1545 Value *SavedFlagPtr = IRBPoison.CreateLoad(
1546 IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1547 IRBPoison.CreateStore(
1548 Constant::getNullValue(IRBPoison.getInt8Ty()),
1549 IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1550 } else {
1551 // For larger frames call __asan_stack_free_*.
Kostya Serebryany530e2072013-12-23 14:15:08 +00001552 IRBPoison.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1553 ConstantInt::get(IntptrTy, LocalStackSize),
1554 OrigStackBase);
Kostya Serebryanybc86efb2013-09-17 12:14:50 +00001555 }
Kostya Serebryany530e2072013-12-23 14:15:08 +00001556
1557 IRBuilder<> IRBElse(ElseTerm);
1558 poisonRedZones(L.ShadowBytes, IRBElse, ShadowBase, false);
Alexey Samsonov261177a2012-12-04 01:34:23 +00001559 } else if (HavePoisonedAllocas) {
1560 // If we poisoned some allocas in llvm.lifetime analysis,
1561 // unpoison whole stack frame now.
1562 assert(LocalStackBase == OrigStackBase);
1563 poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
Kostya Serebryany530e2072013-12-23 14:15:08 +00001564 } else {
1565 poisonRedZones(L.ShadowBytes, IRBRet, ShadowBase, false);
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001566 }
1567 }
1568
Kostya Serebryany09959942012-10-19 06:20:53 +00001569 // We are done. Remove the old unused alloca instructions.
1570 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1571 AllocaVec[i]->eraseFromParent();
Kostya Serebryany6e6b03e2011-11-16 01:35:23 +00001572}
Alexey Samsonov261177a2012-12-04 01:34:23 +00001573
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001574void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
Jakub Staszak23ec6a92013-08-09 20:53:48 +00001575 IRBuilder<> &IRB, bool DoPoison) {
Alexey Samsonov261177a2012-12-04 01:34:23 +00001576 // For now just insert the call to ASan runtime.
1577 Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1578 Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1579 IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1580 : AsanUnpoisonStackMemoryFunc,
1581 AddrArg, SizeArg);
1582}
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001583
1584// Handling llvm.lifetime intrinsics for a given %alloca:
1585// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
1586// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
1587// invalid accesses) and unpoison it for llvm.lifetime.start (the memory
1588// could be poisoned by previous llvm.lifetime.end instruction, as the
1589// variable may go in and out of scope several times, e.g. in loops).
1590// (3) if we poisoned at least one %alloca in a function,
1591// unpoison the whole stack frame at function exit.
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001592
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001593AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
1594 if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
1595 // We're intested only in allocas we can handle.
1596 return isInterestingAlloca(*AI) ? AI : 0;
1597 // See if we've already calculated (or started to calculate) alloca for a
1598 // given value.
1599 AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
1600 if (I != AllocaForValue.end())
1601 return I->second;
1602 // Store 0 while we're calculating alloca for value V to avoid
1603 // infinite recursion if the value references itself.
1604 AllocaForValue[V] = 0;
1605 AllocaInst *Res = 0;
1606 if (CastInst *CI = dyn_cast<CastInst>(V))
1607 Res = findAllocaForValue(CI->getOperand(0));
1608 else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1609 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1610 Value *IncValue = PN->getIncomingValue(i);
1611 // Allow self-referencing phi-nodes.
1612 if (IncValue == PN) continue;
1613 AllocaInst *IncValueAI = findAllocaForValue(IncValue);
1614 // AI for incoming values should exist and should all be equal.
1615 if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
1616 return 0;
1617 Res = IncValueAI;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001618 }
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001619 }
Alexey Samsonov29dd7f22012-12-27 08:50:58 +00001620 if (Res != 0)
1621 AllocaForValue[V] = Res;
Alexey Samsonov1e3f7ba2012-12-25 12:04:36 +00001622 return Res;
1623}