blob: 66f10a4466f01e6b763638a83327aaf12bf00464 [file] [log] [blame]
Kostya Serebryany800e03f2011-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 Carruthd04a8d42012-12-03 16:50:05 +000018#include "llvm/Transforms/Instrumentation.h"
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +000019#include "BlackList.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000020#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/OwningPtr.h"
22#include "llvm/ADT/SmallSet.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringExtras.h"
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000026#include "llvm/ADT/Triple.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000027#include "llvm/DataLayout.h"
28#include "llvm/Function.h"
29#include "llvm/IRBuilder.h"
30#include "llvm/InlineAsm.h"
31#include "llvm/IntrinsicInst.h"
32#include "llvm/LLVMContext.h"
33#include "llvm/Module.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/DataTypes.h"
36#include "llvm/Support/Debug.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000037#include "llvm/Support/raw_ostream.h"
38#include "llvm/Support/system_error.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000039#include "llvm/Target/TargetMachine.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Transforms/Utils/ModuleUtils.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000042#include "llvm/Type.h"
Kostya Serebryany800e03f2011-11-16 01:35:23 +000043#include <algorithm>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000044#include <string>
Kostya Serebryany800e03f2011-11-16 01:35:23 +000045
46using namespace llvm;
47
48static const uint64_t kDefaultShadowScale = 3;
49static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
50static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +000051static const uint64_t kDefaultShadowOffsetAndroid = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000052
53static const size_t kMaxStackMallocSize = 1 << 16; // 64K
54static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
55static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
56
57static const char *kAsanModuleCtorName = "asan.module_ctor";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000058static const char *kAsanModuleDtorName = "asan.module_dtor";
59static const int kAsanCtorAndCtorPriority = 1;
Kostya Serebryany800e03f2011-11-16 01:35:23 +000060static const char *kAsanReportErrorTemplate = "__asan_report_";
61static const char *kAsanRegisterGlobalsName = "__asan_register_globals";
Kostya Serebryany7bcfc992011-12-15 21:59:03 +000062static const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +000063static const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
64static const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000065static const char *kAsanInitName = "__asan_init";
Kostya Serebryany95e3cf42012-02-08 21:36:17 +000066static const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000067static const char *kAsanMappingOffsetName = "__asan_mapping_offset";
68static const char *kAsanMappingScaleName = "__asan_mapping_scale";
69static const char *kAsanStackMallocName = "__asan_stack_malloc";
70static const char *kAsanStackFreeName = "__asan_stack_free";
Kostya Serebryany51c7c652012-11-20 14:16:08 +000071static const char *kAsanGenPrefix = "__asan_gen_";
Kostya Serebryany800e03f2011-11-16 01:35:23 +000072
73static const int kAsanStackLeftRedzoneMagic = 0xf1;
74static const int kAsanStackMidRedzoneMagic = 0xf2;
75static const int kAsanStackRightRedzoneMagic = 0xf3;
76static const int kAsanStackPartialRedzoneMagic = 0xf4;
77
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000078// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
79static const size_t kNumberOfAccessSizes = 5;
80
Kostya Serebryany800e03f2011-11-16 01:35:23 +000081// Command-line flags.
82
83// This flag may need to be replaced with -f[no-]asan-reads.
84static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
85 cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
86static cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
87 cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +000088static cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
89 cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
90 cl::Hidden, cl::init(true));
Kostya Serebryany6e2d5062012-08-15 08:58:58 +000091static cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
92 cl::desc("use instrumentation with slow path for all accesses"),
93 cl::Hidden, cl::init(false));
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +000094// This flag limits the number of instructions to be instrumented
Kostya Serebryany324cbb82012-06-28 09:34:41 +000095// in any given BB. Normally, this should be set to unlimited (INT_MAX),
96// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
97// set it to 10000.
98static cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
99 cl::init(10000),
100 cl::desc("maximal number of instructions to instrument in any given BB"),
101 cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000102// This flag may need to be replaced with -f[no]asan-stack.
103static cl::opt<bool> ClStack("asan-stack",
104 cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
105// This flag may need to be replaced with -f[no]asan-use-after-return.
106static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
107 cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
108// This flag may need to be replaced with -f[no]asan-globals.
109static cl::opt<bool> ClGlobals("asan-globals",
110 cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000111static cl::opt<bool> ClInitializers("asan-initialization-order",
112 cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000113static cl::opt<bool> ClMemIntrin("asan-memintrin",
114 cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000115static cl::opt<std::string> ClBlacklistFile("asan-blacklist",
116 cl::desc("File containing the list of objects to ignore "
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000117 "during instrumentation"), cl::Hidden);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000118
119// These flags allow to change the shadow mapping.
120// The shadow mapping looks like
121// Shadow = (Mem >> scale) + (1 << offset_log)
122static cl::opt<int> ClMappingScale("asan-mapping-scale",
123 cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
124static cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
125 cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
126
127// Optimization flags. Not user visible, used mostly for testing
128// and benchmarking the tool.
129static cl::opt<bool> ClOpt("asan-opt",
130 cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
131static cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
132 cl::desc("Instrument the same temp just once"), cl::Hidden,
133 cl::init(true));
134static cl::opt<bool> ClOptGlobals("asan-opt-globals",
135 cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
136
Alexey Samsonovee548272012-11-29 18:14:24 +0000137static cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
138 cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
139 cl::Hidden, cl::init(false));
140
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000141// Debug flags.
142static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
143 cl::init(0));
144static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
145 cl::Hidden, cl::init(0));
146static cl::opt<std::string> ClDebugFunc("asan-debug-func",
147 cl::Hidden, cl::desc("Debug func"));
148static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
149 cl::Hidden, cl::init(-1));
150static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
151 cl::Hidden, cl::init(-1));
152
153namespace {
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000154/// A set of dynamically initialized globals extracted from metadata.
155class SetOfDynamicallyInitializedGlobals {
156 public:
157 void Init(Module& M) {
158 // Clang generates metadata identifying all dynamically initialized globals.
159 NamedMDNode *DynamicGlobals =
160 M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
161 if (!DynamicGlobals)
162 return;
163 for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
164 MDNode *MDN = DynamicGlobals->getOperand(i);
165 assert(MDN->getNumOperands() == 1);
166 Value *VG = MDN->getOperand(0);
167 // The optimizer may optimize away a global entirely, in which case we
168 // cannot instrument access to it.
169 if (!VG)
170 continue;
171 DynInitGlobals.insert(cast<GlobalVariable>(VG));
172 }
173 }
174 bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
175 private:
176 SmallSet<GlobalValue*, 32> DynInitGlobals;
177};
178
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000179static int MappingScale() {
180 return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
181}
182
183static size_t RedzoneSize() {
184 // Redzone used for stack and globals is at least 32 bytes.
185 // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
186 return std::max(32U, 1U << MappingScale());
187}
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000188
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000189/// AddressSanitizer: instrument the code in module to find memory bugs.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000190struct AddressSanitizer : public FunctionPass {
Alexey Samsonovee548272012-11-29 18:14:24 +0000191 AddressSanitizer(bool CheckInitOrder = false,
192 bool CheckUseAfterReturn = false,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000193 bool CheckLifetime = false,
194 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000195 : FunctionPass(ID),
196 CheckInitOrder(CheckInitOrder || ClInitializers),
197 CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000198 CheckLifetime(CheckLifetime || ClCheckLifetime),
199 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
200 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000201 virtual const char *getPassName() const {
202 return "AddressSanitizerFunctionPass";
203 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000204 void instrumentMop(Instruction *I);
205 void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000206 Value *Addr, uint32_t TypeSize, bool IsWrite);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000207 Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
208 Value *ShadowValue, uint32_t TypeSize);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000209 Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000210 bool IsWrite, size_t AccessSizeIndex);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000211 bool instrumentMemIntrinsic(MemIntrinsic *MI);
212 void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000213 Value *Size,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000214 Instruction *InsertBefore, bool IsWrite);
215 Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000216 bool runOnFunction(Function &F);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000217 void createInitializerPoisonCalls(Module &M,
218 Value *FirstAddr, Value *LastAddr);
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000219 bool maybeInsertAsanInitAtFunctionEntry(Function &F);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000220 bool poisonStackInFunction(Function &F);
221 virtual bool doInitialization(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000222 static char ID; // Pass identification, replacement for typeid
223
224 private:
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000225 void initializeCallbacks(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000226 uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
227 Type *Ty = AI->getAllocatedType();
Evgeniy Stepanovd8313be2012-03-02 10:41:08 +0000228 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000229 return SizeInBytes;
230 }
231 uint64_t getAlignedSize(uint64_t SizeInBytes) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000232 size_t RZ = RedzoneSize();
233 return ((SizeInBytes + RZ - 1) / RZ) * RZ;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000234 }
235 uint64_t getAlignedAllocaSize(AllocaInst *AI) {
236 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
237 return getAlignedSize(SizeInBytes);
238 }
239
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000240 bool ShouldInstrumentGlobal(GlobalVariable *G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000241 void PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
242 Value *ShadowBase, bool DoPoison);
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +0000243 bool LooksLikeCodeInBug11395(Instruction *I);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000244 void FindDynamicInitializers(Module &M);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000245
Alexey Samsonovee548272012-11-29 18:14:24 +0000246 bool CheckInitOrder;
247 bool CheckUseAfterReturn;
248 bool CheckLifetime;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000249 LLVMContext *C;
Micah Villmow3574eca2012-10-08 16:38:25 +0000250 DataLayout *TD;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000251 uint64_t MappingOffset;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000252 int LongSize;
253 Type *IntptrTy;
254 Type *IntptrPtrTy;
255 Function *AsanCtorFunction;
256 Function *AsanInitFunction;
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000257 Function *AsanStackMallocFunc, *AsanStackFreeFunc;
258 Function *AsanHandleNoReturnFunc;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000259 SmallString<64> BlacklistFile;
Kostya Serebryanyb5b86d22012-08-24 16:44:47 +0000260 OwningPtr<BlackList> BL;
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000261 // This array is indexed by AccessIsWrite and log2(AccessSize).
262 Function *AsanErrorCallback[2][kNumberOfAccessSizes];
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000263 InlineAsm *EmptyAsm;
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000264 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000265};
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000266
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000267class AddressSanitizerModule : public ModulePass {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000268 public:
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000269 AddressSanitizerModule(bool CheckInitOrder = false,
270 StringRef BlacklistFile = StringRef())
Alexey Samsonovee548272012-11-29 18:14:24 +0000271 : ModulePass(ID),
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000272 CheckInitOrder(CheckInitOrder || ClInitializers),
273 BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
274 : BlacklistFile) {}
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000275 bool runOnModule(Module &M);
276 static char ID; // Pass identification, replacement for typeid
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000277 virtual const char *getPassName() const {
278 return "AddressSanitizerModule";
279 }
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000280 private:
281 bool ShouldInstrumentGlobal(GlobalVariable *G);
282 void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
283 Value *LastAddr);
284
Alexey Samsonovee548272012-11-29 18:14:24 +0000285 bool CheckInitOrder;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000286 SmallString<64> BlacklistFile;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000287 OwningPtr<BlackList> BL;
288 SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
289 Type *IntptrTy;
290 LLVMContext *C;
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000291 DataLayout *TD;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000292};
293
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000294} // namespace
295
296char AddressSanitizer::ID = 0;
297INITIALIZE_PASS(AddressSanitizer, "asan",
298 "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
299 false, false)
Alexey Samsonovee548272012-11-29 18:14:24 +0000300FunctionPass *llvm::createAddressSanitizerFunctionPass(
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000301 bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
302 StringRef BlacklistFile) {
Alexey Samsonovee548272012-11-29 18:14:24 +0000303 return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000304 CheckLifetime, BlacklistFile);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000305}
306
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000307char AddressSanitizerModule::ID = 0;
308INITIALIZE_PASS(AddressSanitizerModule, "asan-module",
309 "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
310 "ModulePass", false, false)
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000311ModulePass *llvm::createAddressSanitizerModulePass(
312 bool CheckInitOrder, StringRef BlacklistFile) {
313 return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
Alexander Potapenko25878042012-01-23 11:22:43 +0000314}
315
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000316static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
317 size_t Res = CountTrailingZeros_32(TypeSize / 8);
318 assert(Res < kNumberOfAccessSizes);
319 return Res;
320}
321
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000322// Create a constant for Str so that we can pass it to the run-time lib.
323static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
Chris Lattner18c7f802012-02-05 02:29:43 +0000324 Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000325 return new GlobalVariable(M, StrConst->getType(), true,
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000326 GlobalValue::PrivateLinkage, StrConst,
327 kAsanGenPrefix);
328}
329
330static bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
331 return G->getName().find(kAsanGenPrefix) == 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000332}
333
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000334Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
335 // Shadow >> scale
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000336 Shadow = IRB.CreateLShr(Shadow, MappingScale());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000337 if (MappingOffset == 0)
338 return Shadow;
339 // (Shadow >> scale) | offset
340 return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
341 MappingOffset));
342}
343
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000344void AddressSanitizer::instrumentMemIntrinsicParam(
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000345 Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000346 Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
347 // Check the first byte.
348 {
349 IRBuilder<> IRB(InsertBefore);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000350 instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000351 }
352 // Check the last byte.
353 {
354 IRBuilder<> IRB(InsertBefore);
355 Value *SizeMinusOne = IRB.CreateSub(
356 Size, ConstantInt::get(Size->getType(), 1));
357 SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
358 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
359 Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000360 instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000361 }
362}
363
364// Instrument memset/memmove/memcpy
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000365bool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000366 Value *Dst = MI->getDest();
367 MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000368 Value *Src = MemTran ? MemTran->getSource() : 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000369 Value *Length = MI->getLength();
370
371 Constant *ConstLength = dyn_cast<Constant>(Length);
372 Instruction *InsertBefore = MI;
373 if (ConstLength) {
374 if (ConstLength->isNullValue()) return false;
375 } else {
376 // The size is not a constant so it could be zero -- check at run-time.
377 IRBuilder<> IRB(InsertBefore);
378
379 Value *Cmp = IRB.CreateICmpNE(Length,
Kostya Serebryany56139bc2012-07-02 11:42:29 +0000380 Constant::getNullValue(Length->getType()));
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000381 InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000382 }
383
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000384 instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000385 if (Src)
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000386 instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000387 return true;
388}
389
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000390// If I is an interesting memory access, return the PointerOperand
391// and set IsWrite. Otherwise return NULL.
392static Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000393 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000394 if (!ClInstrumentReads) return NULL;
395 *IsWrite = false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000396 return LI->getPointerOperand();
397 }
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000398 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
399 if (!ClInstrumentWrites) return NULL;
400 *IsWrite = true;
401 return SI->getPointerOperand();
402 }
403 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
404 if (!ClInstrumentAtomics) return NULL;
405 *IsWrite = true;
406 return RMW->getPointerOperand();
407 }
408 if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
409 if (!ClInstrumentAtomics) return NULL;
410 *IsWrite = true;
411 return XCHG->getPointerOperand();
412 }
413 return NULL;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000414}
415
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000416void AddressSanitizer::instrumentMop(Instruction *I) {
Axel Naumann3780ad82012-09-17 14:20:57 +0000417 bool IsWrite = false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000418 Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
419 assert(Addr);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000420 if (ClOpt && ClOptGlobals) {
421 if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
422 // If initialization order checking is disabled, a simple access to a
423 // dynamically initialized global is always valid.
Alexey Samsonovee548272012-11-29 18:14:24 +0000424 if (!CheckInitOrder)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000425 return;
426 // If a global variable does not have dynamic initialization we don't
Kostya Serebryany40779062012-11-20 13:11:32 +0000427 // have to instrument it. However, if a global does not have initailizer
428 // at all, we assume it has dynamic initializer (in other TU).
429 if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000430 return;
431 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000432 }
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000433
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000434 Type *OrigPtrTy = Addr->getType();
435 Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
436
437 assert(OrigTy->isSized());
438 uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
439
440 if (TypeSize != 8 && TypeSize != 16 &&
441 TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
442 // Ignore all unusual sizes.
443 return;
444 }
445
446 IRBuilder<> IRB(I);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000447 instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000448}
449
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000450// Validate the result of Module::getOrInsertFunction called for an interface
451// function of AddressSanitizer. If the instrumented module defines a function
452// with the same name, their prototypes must match, otherwise
453// getOrInsertFunction returns a bitcast.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000454static Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000455 if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
456 FuncOrBitcast->dump();
457 report_fatal_error("trying to redefine an AddressSanitizer "
458 "interface function");
459}
460
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000461Instruction *AddressSanitizer::generateCrashCode(
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000462 Instruction *InsertBefore, Value *Addr,
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000463 bool IsWrite, size_t AccessSizeIndex) {
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000464 IRBuilder<> IRB(InsertBefore);
465 CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
466 Addr);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000467 // We don't do Call->setDoesNotReturn() because the BB already has
468 // UnreachableInst at the end.
469 // This EmptyAsm is required to avoid callback merge.
470 IRB.CreateCall(EmptyAsm);
Kostya Serebryany3c7faae2012-01-06 18:09:21 +0000471 return Call;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000472}
473
Kostya Serebryany2735cf42012-07-16 17:12:07 +0000474Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000475 Value *ShadowValue,
476 uint32_t TypeSize) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000477 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000478 // Addr & (Granularity - 1)
479 Value *LastAccessedByte = IRB.CreateAnd(
480 AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
481 // (Addr & (Granularity - 1)) + size - 1
482 if (TypeSize / 8 > 1)
483 LastAccessedByte = IRB.CreateAdd(
484 LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
485 // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
486 LastAccessedByte = IRB.CreateIntCast(
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000487 LastAccessedByte, ShadowValue->getType(), false);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000488 // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
489 return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
490}
491
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000492void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000493 IRBuilder<> &IRB, Value *Addr,
494 uint32_t TypeSize, bool IsWrite) {
495 Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
496
497 Type *ShadowTy = IntegerType::get(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000498 *C, std::max(8U, TypeSize >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000499 Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
500 Value *ShadowPtr = memToShadow(AddrLong, IRB);
501 Value *CmpVal = Constant::getNullValue(ShadowTy);
502 Value *ShadowValue = IRB.CreateLoad(
503 IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
504
505 Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
Kostya Serebryany11c2a472012-08-13 14:08:46 +0000506 size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000507 size_t Granularity = 1 << MappingScale();
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000508 TerminatorInst *CrashTerm = 0;
509
Kostya Serebryany6e2d5062012-08-15 08:58:58 +0000510 if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000511 TerminatorInst *CheckTerm =
512 SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000513 assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000514 BasicBlock *NextBB = CheckTerm->getSuccessor(0);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000515 IRB.SetInsertPoint(CheckTerm);
516 Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000517 BasicBlock *CrashBlock =
518 BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000519 CrashTerm = new UnreachableInst(*C, CrashBlock);
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000520 BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
521 ReplaceInstWithInst(CheckTerm, NewTerm);
Kostya Serebryanyc0ed3e52012-07-16 16:15:40 +0000522 } else {
Evgeniy Stepanov4a2dec02012-10-19 10:48:31 +0000523 CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000524 }
Kostya Serebryanyebd64542012-08-14 14:04:51 +0000525
526 Instruction *Crash =
527 generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
528 Crash->setDebugLoc(OrigIns->getDebugLoc());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000529}
530
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000531void AddressSanitizerModule::createInitializerPoisonCalls(
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000532 Module &M, Value *FirstAddr, Value *LastAddr) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000533 // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
534 Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
535 // If that function is not present, this TU contains no globals, or they have
536 // all been optimized away
537 if (!GlobalInit)
538 return;
539
540 // Set up the arguments to our poison/unpoison functions.
541 IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
542
543 // Declare our poisoning and unpoisoning functions.
544 Function *AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
545 kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
546 AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
547 Function *AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
548 kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
549 AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
550
551 // Add a call to poison all external globals before the given function starts.
552 IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
553
554 // Add calls to unpoison all globals before each return instruction.
555 for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
556 I != E; ++I) {
557 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
558 CallInst::Create(AsanUnpoisonGlobals, "", RI);
559 }
560 }
561}
562
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000563bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000564 Type *Ty = cast<PointerType>(G->getType())->getElementType();
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000565 DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000566
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000567 if (BL->isIn(*G)) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000568 if (!Ty->isSized()) return false;
569 if (!G->hasInitializer()) return false;
Kostya Serebryany51c7c652012-11-20 14:16:08 +0000570 if (GlobalWasGeneratedByAsan(G)) return false; // Our own global.
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000571 // Touch only those globals that will not be defined in other modules.
572 // Don't handle ODR type linkages since other modules may be built w/o asan.
573 if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
574 G->getLinkage() != GlobalVariable::PrivateLinkage &&
575 G->getLinkage() != GlobalVariable::InternalLinkage)
576 return false;
577 // Two problems with thread-locals:
578 // - The address of the main thread's copy can't be computed at link-time.
579 // - Need to poison all copies, not just the main thread's one.
580 if (G->isThreadLocal())
581 return false;
582 // For now, just ignore this Alloca if the alignment is large.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000583 if (G->getAlignment() > RedzoneSize()) return false;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000584
585 // Ignore all the globals with the names starting with "\01L_OBJC_".
586 // Many of those are put into the .cstring section. The linker compresses
587 // that section by removing the spare \0s after the string terminator, so
588 // our redzones get broken.
589 if ((G->getName().find("\01L_OBJC_") == 0) ||
590 (G->getName().find("\01l_OBJC_") == 0)) {
591 DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
592 return false;
593 }
594
595 if (G->hasSection()) {
596 StringRef Section(G->getSection());
597 // Ignore the globals from the __OBJC section. The ObjC runtime assumes
598 // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
599 // them.
600 if ((Section.find("__OBJC,") == 0) ||
601 (Section.find("__DATA, __objc_") == 0)) {
602 DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
603 return false;
604 }
605 // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
606 // Constant CFString instances are compiled in the following way:
607 // -- the string buffer is emitted into
608 // __TEXT,__cstring,cstring_literals
609 // -- the constant NSConstantString structure referencing that buffer
610 // is placed into __DATA,__cfstring
611 // Therefore there's no point in placing redzones into __DATA,__cfstring.
612 // Moreover, it causes the linker to crash on OS X 10.7
613 if (Section.find("__DATA,__cfstring") == 0) {
614 DEBUG(dbgs() << "Ignoring CFString: " << *G);
615 return false;
616 }
617 }
618
619 return true;
620}
621
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000622// This function replaces all global variables with new variables that have
623// trailing redzones. It also creates a function that poisons
624// redzones and inserts this function into llvm.global_ctors.
Kostya Serebryany1416edc2012-11-28 10:31:36 +0000625bool AddressSanitizerModule::runOnModule(Module &M) {
626 if (!ClGlobals) return false;
627 TD = getAnalysisIfAvailable<DataLayout>();
628 if (!TD)
629 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000630 BL.reset(new BlackList(BlacklistFile));
Alexey Samsonovd6f62c82012-11-29 18:27:01 +0000631 if (BL->isIn(M)) return false;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000632 DynamicallyInitializedGlobals.Init(M);
633 C = &(M.getContext());
634 IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
635
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000636 SmallVector<GlobalVariable *, 16> GlobalsToChange;
637
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000638 for (Module::GlobalListType::iterator G = M.global_begin(),
639 E = M.global_end(); G != E; ++G) {
640 if (ShouldInstrumentGlobal(G))
641 GlobalsToChange.push_back(G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000642 }
643
644 size_t n = GlobalsToChange.size();
645 if (n == 0) return false;
646
647 // A global is described by a structure
648 // size_t beg;
649 // size_t size;
650 // size_t size_with_redzone;
651 // const char *name;
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000652 // size_t has_dynamic_init;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000653 // We initialize an array of such structures and pass it to a run-time call.
654 StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000655 IntptrTy, IntptrTy,
656 IntptrTy, NULL);
657 SmallVector<Constant *, 16> Initializers(n), DynamicInit;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000658
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000659
660 Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
661 assert(CtorFunc);
662 IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000663
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000664 // The addresses of the first and last dynamically initialized globals in
665 // this TU. Used in initialization order checking.
666 Value *FirstDynamic = 0, *LastDynamic = 0;
667
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000668 for (size_t i = 0; i < n; i++) {
669 GlobalVariable *G = GlobalsToChange[i];
670 PointerType *PtrTy = cast<PointerType>(G->getType());
671 Type *Ty = PtrTy->getElementType();
Kostya Serebryany208a4ff2012-03-21 15:28:50 +0000672 uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000673 size_t RZ = RedzoneSize();
674 uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000675 Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000676 // Determine whether this global should be poisoned in initialization.
Kostya Serebryanyca23d432012-11-20 13:00:01 +0000677 bool GlobalHasDynamicInitializer =
678 DynamicallyInitializedGlobals.Contains(G);
Kostya Serebryany59a4a472012-09-05 07:29:56 +0000679 // Don't check initialization order if this global is blacklisted.
Kostya Serebryany7dadac62012-09-05 09:00:18 +0000680 GlobalHasDynamicInitializer &= !BL->isInInit(*G);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000681
682 StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
683 Constant *NewInitializer = ConstantStruct::get(
684 NewTy, G->getInitializer(),
685 Constant::getNullValue(RightRedZoneTy), NULL);
686
Kostya Serebryanya4b2b1d2011-12-15 22:55:55 +0000687 SmallString<2048> DescriptionOfGlobal = G->getName();
688 DescriptionOfGlobal += " (";
689 DescriptionOfGlobal += M.getModuleIdentifier();
690 DescriptionOfGlobal += ")";
691 GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000692
693 // Create a new global variable with enough space for a redzone.
694 GlobalVariable *NewGlobal = new GlobalVariable(
695 M, NewTy, G->isConstant(), G->getLinkage(),
Hans Wennborgce718ff2012-06-23 11:37:03 +0000696 NewInitializer, "", G, G->getThreadLocalMode());
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000697 NewGlobal->copyAttributesFrom(G);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000698 NewGlobal->setAlignment(RZ);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000699
700 Value *Indices2[2];
701 Indices2[0] = IRB.getInt32(0);
702 Indices2[1] = IRB.getInt32(0);
703
704 G->replaceAllUsesWith(
Kostya Serebryanyf1639ab2012-01-28 04:27:16 +0000705 ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000706 NewGlobal->takeName(G);
707 G->eraseFromParent();
708
709 Initializers[i] = ConstantStruct::get(
710 GlobalStructTy,
711 ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
712 ConstantInt::get(IntptrTy, SizeInBytes),
713 ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
714 ConstantExpr::getPointerCast(Name, IntptrTy),
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000715 ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000716 NULL);
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000717
718 // Populate the first and last globals declared in this TU.
Alexey Samsonovee548272012-11-29 18:14:24 +0000719 if (CheckInitOrder && GlobalHasDynamicInitializer) {
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000720 LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
721 if (FirstDynamic == 0)
722 FirstDynamic = LastDynamic;
723 }
724
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000725 DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000726 }
727
728 ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
729 GlobalVariable *AllGlobals = new GlobalVariable(
730 M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
731 ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
732
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000733 // Create calls for poisoning before initializers run and unpoisoning after.
Alexey Samsonovee548272012-11-29 18:14:24 +0000734 if (CheckInitOrder && FirstDynamic && LastDynamic)
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000735 createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
736
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000737 Function *AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
Kostya Serebryany9b9f87a2012-08-21 08:24:25 +0000738 kAsanRegisterGlobalsName, IRB.getVoidTy(),
739 IntptrTy, IntptrTy, NULL));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000740 AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
741
742 IRB.CreateCall2(AsanRegisterGlobals,
743 IRB.CreatePointerCast(AllGlobals, IntptrTy),
744 ConstantInt::get(IntptrTy, n));
745
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000746 // We also need to unregister globals at the end, e.g. when a shared library
747 // gets closed.
748 Function *AsanDtorFunction = Function::Create(
749 FunctionType::get(Type::getVoidTy(*C), false),
750 GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
751 BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
752 IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
Alexander Potapenko55cabae2012-04-23 10:47:31 +0000753 Function *AsanUnregisterGlobals =
754 checkInterfaceFunction(M.getOrInsertFunction(
755 kAsanUnregisterGlobalsName,
756 IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000757 AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
758
759 IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
760 IRB.CreatePointerCast(AllGlobals, IntptrTy),
761 ConstantInt::get(IntptrTy, n));
762 appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
763
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000764 DEBUG(dbgs() << M);
765 return true;
766}
767
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000768void AddressSanitizer::initializeCallbacks(Module &M) {
769 IRBuilder<> IRB(*C);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000770 // Create __asan_report* callbacks.
771 for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
772 for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
773 AccessSizeIndex++) {
774 // IsWrite and TypeSize are encoded in the function name.
775 std::string FunctionName = std::string(kAsanReportErrorTemplate) +
776 (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
Kostya Serebryany4f0c6962012-07-17 11:04:12 +0000777 // If we are merging crash callbacks, they have two parameters.
Kostya Serebryany7846c1c2012-11-07 12:42:18 +0000778 AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
779 checkInterfaceFunction(M.getOrInsertFunction(
780 FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000781 }
782 }
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000783
784 AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
785 kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
786 AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
787 kAsanStackFreeName, IRB.getVoidTy(),
788 IntptrTy, IntptrTy, IntptrTy, NULL));
789 AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
790 kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
791
Kostya Serebryanyf7b08222012-07-20 09:54:50 +0000792 // We insert an empty inline asm after __asan_report* to avoid callback merge.
793 EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
794 StringRef(""), StringRef(""),
795 /*hasSideEffects=*/true);
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000796}
797
798// virtual
799bool AddressSanitizer::doInitialization(Module &M) {
800 // Initialize the private fields. No one has accessed them before.
801 TD = getAnalysisIfAvailable<DataLayout>();
802
803 if (!TD)
804 return false;
Alexey Samsonovb0dcf612012-12-03 19:09:26 +0000805 BL.reset(new BlackList(BlacklistFile));
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000806 DynamicallyInitializedGlobals.Init(M);
807
808 C = &(M.getContext());
809 LongSize = TD->getPointerSizeInBits();
810 IntptrTy = Type::getIntNTy(*C, LongSize);
811 IntptrPtrTy = PointerType::get(IntptrTy, 0);
812
813 AsanCtorFunction = Function::Create(
814 FunctionType::get(Type::getVoidTy(*C), false),
815 GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
816 BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
817 // call __asan_init in the module ctor.
818 IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
819 AsanInitFunction = checkInterfaceFunction(
820 M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
821 AsanInitFunction->setLinkage(Function::ExternalLinkage);
822 IRB.CreateCall(AsanInitFunction);
Kostya Serebryany9db5b5f2012-07-16 14:09:42 +0000823
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000824 llvm::Triple targetTriple(M.getTargetTriple());
Logan Chien43bf7092012-09-02 09:29:46 +0000825 bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
Evgeniy Stepanov06fdbaa2012-05-23 11:52:12 +0000826
827 MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
828 (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000829 if (ClMappingOffsetLog >= 0) {
830 if (ClMappingOffsetLog == 0) {
831 // special case
832 MappingOffset = 0;
833 } else {
834 MappingOffset = 1ULL << ClMappingOffsetLog;
835 }
836 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000837
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000838
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000839 if (ClMappingOffsetLog >= 0) {
840 // Tell the run-time the current values of mapping offset and scale.
841 GlobalValue *asan_mapping_offset =
842 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
843 ConstantInt::get(IntptrTy, MappingOffset),
844 kAsanMappingOffsetName);
845 // Read the global, otherwise it may be optimized away.
846 IRB.CreateLoad(asan_mapping_offset, true);
847 }
848 if (ClMappingScale) {
849 GlobalValue *asan_mapping_scale =
850 new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000851 ConstantInt::get(IntptrTy, MappingScale()),
Kostya Serebryany8c0134a2012-03-19 16:40:35 +0000852 kAsanMappingScaleName);
853 // Read the global, otherwise it may be optimized away.
854 IRB.CreateLoad(asan_mapping_scale, true);
855 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000856
Kostya Serebryany7bcfc992011-12-15 21:59:03 +0000857 appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
Kostya Serebryany9b027412011-12-12 18:01:46 +0000858
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000859 return true;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000860}
861
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000862bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
863 // For each NSObject descendant having a +load method, this method is invoked
864 // by the ObjC runtime before any of the static constructors is called.
865 // Therefore we need to instrument such methods with a call to __asan_init
866 // at the beginning in order to initialize our runtime before any access to
867 // the shadow memory.
868 // We cannot just ignore these methods, because they may call other
869 // instrumented functions.
870 if (F.getName().find(" load]") != std::string::npos) {
871 IRBuilder<> IRB(F.begin()->begin());
872 IRB.CreateCall(AsanInitFunction);
873 return true;
874 }
875 return false;
876}
877
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000878bool AddressSanitizer::runOnFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000879 if (BL->isIn(F)) return false;
880 if (&F == AsanCtorFunction) return false;
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000881 DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
Kostya Serebryany8b390ff2012-11-29 09:54:21 +0000882 initializeCallbacks(*F.getParent());
Kostya Serebryanya1a8a322012-01-30 23:50:10 +0000883
884 // If needed, insert __asan_init before checking for AddressSafety attr.
885 maybeInsertAsanInitAtFunctionEntry(F);
886
Bill Wendling67658342012-10-09 07:45:08 +0000887 if (!F.getFnAttributes().hasAttribute(Attributes::AddressSafety))
888 return false;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000889
890 if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
891 return false;
Bill Wendling67658342012-10-09 07:45:08 +0000892
893 // We want to instrument every address only once per basic block (unless there
894 // are calls between uses).
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000895 SmallSet<Value*, 16> TempsToInstrument;
896 SmallVector<Instruction*, 16> ToInstrument;
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000897 SmallVector<Instruction*, 8> NoReturnCalls;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000898 bool IsWrite;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000899
900 // Fill the set of memory operations to instrument.
901 for (Function::iterator FI = F.begin(), FE = F.end();
902 FI != FE; ++FI) {
903 TempsToInstrument.clear();
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000904 int NumInsnsPerBB = 0;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000905 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
906 BI != BE; ++BI) {
Kostya Serebryanybcb55ce2012-01-11 18:15:23 +0000907 if (LooksLikeCodeInBug11395(BI)) return false;
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000908 if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000909 if (ClOpt && ClOptSameTemp) {
910 if (!TempsToInstrument.insert(Addr))
911 continue; // We've seen this temp in the current BB.
912 }
913 } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
914 // ok, take it.
915 } else {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000916 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000917 // A call inside BB.
918 TempsToInstrument.clear();
Kostya Serebryanya17babb2012-11-30 11:08:59 +0000919 if (CI->doesNotReturn()) {
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000920 NoReturnCalls.push_back(CI);
921 }
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000922 }
923 continue;
924 }
925 ToInstrument.push_back(BI);
Kostya Serebryany324cbb82012-06-28 09:34:41 +0000926 NumInsnsPerBB++;
927 if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
928 break;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000929 }
930 }
931
932 // Instrument.
933 int NumInstrumented = 0;
934 for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
935 Instruction *Inst = ToInstrument[i];
936 if (ClDebugMin < 0 || ClDebugMax < 0 ||
937 (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
Kostya Serebryanye6cf2e02012-05-30 09:04:06 +0000938 if (isInterestingMemoryAccess(Inst, &IsWrite))
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000939 instrumentMop(Inst);
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000940 else
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000941 instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000942 }
943 NumInstrumented++;
944 }
945
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000946 bool ChangedStack = poisonStackInFunction(F);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000947
948 // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
949 // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
950 for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
951 Instruction *CI = NoReturnCalls[i];
952 IRBuilder<> IRB(CI);
Kostya Serebryanyee4edec2012-10-15 14:20:06 +0000953 IRB.CreateCall(AsanHandleNoReturnFunc);
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000954 }
Kostya Serebryany324d96b2012-10-17 13:40:06 +0000955 DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
Kostya Serebryany95e3cf42012-02-08 21:36:17 +0000956
957 return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000958}
959
960static uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
961 if (ShadowRedzoneSize == 1) return PoisonByte;
962 if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
963 if (ShadowRedzoneSize == 4)
964 return (PoisonByte << 24) + (PoisonByte << 16) +
965 (PoisonByte << 8) + (PoisonByte);
Craig Topper85814382012-02-07 05:05:23 +0000966 llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000967}
968
969static void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
970 size_t Size,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000971 size_t RZSize,
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000972 size_t ShadowGranularity,
973 uint8_t Magic) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000974 for (size_t i = 0; i < RZSize;
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000975 i+= ShadowGranularity, Shadow++) {
976 if (i + ShadowGranularity <= Size) {
977 *Shadow = 0; // fully addressable
978 } else if (i >= Size) {
979 *Shadow = Magic; // unaddressable
980 } else {
981 *Shadow = Size - i; // first Size-i bytes are addressable
982 }
983 }
984}
985
986void AddressSanitizer::PoisonStack(const ArrayRef<AllocaInst*> &AllocaVec,
987 IRBuilder<> IRB,
988 Value *ShadowBase, bool DoPoison) {
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +0000989 size_t ShadowRZSize = RedzoneSize() >> MappingScale();
Kostya Serebryany800e03f2011-11-16 01:35:23 +0000990 assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
991 Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
992 Type *RZPtrTy = PointerType::get(RZTy, 0);
993
994 Value *PoisonLeft = ConstantInt::get(RZTy,
995 ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
996 Value *PoisonMid = ConstantInt::get(RZTy,
997 ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
998 Value *PoisonRight = ConstantInt::get(RZTy,
999 ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1000
1001 // poison the first red zone.
1002 IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1003
1004 // poison all other red zones.
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001005 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001006 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1007 AllocaInst *AI = AllocaVec[i];
1008 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1009 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001010 assert(AlignedSize - SizeInBytes < RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001011 Value *Ptr = NULL;
1012
1013 Pos += AlignedSize;
1014
1015 assert(ShadowBase->getType() == IntptrTy);
1016 if (SizeInBytes < AlignedSize) {
1017 // Poison the partial redzone at right
1018 Ptr = IRB.CreateAdd(
1019 ShadowBase, ConstantInt::get(IntptrTy,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001020 (Pos >> MappingScale()) - ShadowRZSize));
1021 size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001022 uint32_t Poison = 0;
1023 if (DoPoison) {
1024 PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001025 RedzoneSize(),
1026 1ULL << MappingScale(),
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001027 kAsanStackPartialRedzoneMagic);
1028 }
1029 Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1030 IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1031 }
1032
1033 // Poison the full redzone at right.
1034 Ptr = IRB.CreateAdd(ShadowBase,
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001035 ConstantInt::get(IntptrTy, Pos >> MappingScale()));
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001036 Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1037 IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1038
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001039 Pos += RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001040 }
1041}
1042
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001043// Workaround for bug 11395: we don't want to instrument stack in functions
1044// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
Kostya Serebryanyd2703de2011-11-23 02:10:54 +00001045// FIXME: remove once the bug 11395 is fixed.
Kostya Serebryany5a3a9c92011-11-18 01:41:06 +00001046bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
1047 if (LongSize != 32) return false;
1048 CallInst *CI = dyn_cast<CallInst>(I);
1049 if (!CI || !CI->isInlineAsm()) return false;
1050 if (CI->getNumArgOperands() <= 5) return false;
1051 // We have inline assembly with quite a few arguments.
1052 return true;
1053}
1054
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001055// Find all static Alloca instructions and put
1056// poisoned red zones around all of them.
1057// Then unpoison everything back before the function returns.
1058//
1059// Stack poisoning does not play well with exception handling.
1060// When an exception is thrown, we essentially bypass the code
1061// that unpoisones the stack. This is why the run-time library has
1062// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
1063// stack in the interceptor. This however does not work inside the
1064// actual function which catches the exception. Most likely because the
1065// compiler hoists the load of the shadow value somewhere too high.
1066// This causes asan to report a non-existing bug on 453.povray.
1067// It sounds like an LLVM bug.
Kostya Serebryanyee4edec2012-10-15 14:20:06 +00001068bool AddressSanitizer::poisonStackInFunction(Function &F) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001069 if (!ClStack) return false;
1070 SmallVector<AllocaInst*, 16> AllocaVec;
1071 SmallVector<Instruction*, 8> RetVec;
1072 uint64_t TotalSize = 0;
1073
1074 // Filter out Alloca instructions we want (and can) handle.
1075 // Collect Ret instructions.
1076 for (Function::iterator FI = F.begin(), FE = F.end();
1077 FI != FE; ++FI) {
1078 BasicBlock &BB = *FI;
1079 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end();
1080 BI != BE; ++BI) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001081 if (isa<ReturnInst>(BI)) {
1082 RetVec.push_back(BI);
1083 continue;
1084 }
1085
1086 AllocaInst *AI = dyn_cast<AllocaInst>(BI);
1087 if (!AI) continue;
1088 if (AI->isArrayAllocation()) continue;
1089 if (!AI->isStaticAlloca()) continue;
1090 if (!AI->getAllocatedType()->isSized()) continue;
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001091 if (AI->getAlignment() > RedzoneSize()) continue;
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001092 AllocaVec.push_back(AI);
1093 uint64_t AlignedSize = getAlignedAllocaSize(AI);
1094 TotalSize += AlignedSize;
1095 }
1096 }
1097
1098 if (AllocaVec.empty()) return false;
1099
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001100 uint64_t LocalStackSize = TotalSize + (AllocaVec.size() + 1) * RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001101
Alexey Samsonovee548272012-11-29 18:14:24 +00001102 bool DoStackMalloc = CheckUseAfterReturn
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001103 && LocalStackSize <= kMaxStackMallocSize;
1104
1105 Instruction *InsBefore = AllocaVec[0];
1106 IRBuilder<> IRB(InsBefore);
1107
1108
1109 Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1110 AllocaInst *MyAlloca =
1111 new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001112 MyAlloca->setAlignment(RedzoneSize());
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001113 assert(MyAlloca->isStaticAlloca());
1114 Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1115 Value *LocalStackBase = OrigStackBase;
1116
1117 if (DoStackMalloc) {
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001118 LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1119 ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1120 }
1121
1122 // This string will be parsed by the run-time (DescribeStackAddress).
1123 SmallString<2048> StackDescriptionStorage;
1124 raw_svector_ostream StackDescription(StackDescriptionStorage);
1125 StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1126
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001127 uint64_t Pos = RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001128 // Replace Alloca instructions with base+offset.
1129 for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1130 AllocaInst *AI = AllocaVec[i];
1131 uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1132 StringRef Name = AI->getName();
1133 StackDescription << Pos << " " << SizeInBytes << " "
1134 << Name.size() << " " << Name << " ";
1135 uint64_t AlignedSize = getAlignedAllocaSize(AI);
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001136 assert((AlignedSize % RedzoneSize()) == 0);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001137 AI->replaceAllUsesWith(
1138 IRB.CreateIntToPtr(
1139 IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1140 AI->getType()));
Kostya Serebryanyb9a12ea2012-11-22 03:18:50 +00001141 Pos += AlignedSize + RedzoneSize();
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001142 }
1143 assert(Pos == LocalStackSize);
1144
1145 // Write the Magic value and the frame description constant to the redzone.
1146 Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1147 IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1148 BasePlus0);
1149 Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
1150 ConstantInt::get(IntptrTy, LongSize/8));
1151 BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
Alexey Samsonov9ce84c12012-11-02 12:20:34 +00001152 GlobalVariable *StackDescriptionGlobal =
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001153 createPrivateGlobalForString(*F.getParent(), StackDescription.str());
Kostya Serebryanya5f54f12012-11-01 13:42:40 +00001154 Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001155 IRB.CreateStore(Description, BasePlus1);
1156
1157 // Poison the stack redzones at the entry.
1158 Value *ShadowBase = memToShadow(LocalStackBase, IRB);
1159 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRB, ShadowBase, true);
1160
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001161 // Unpoison the stack before all ret instructions.
1162 for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1163 Instruction *Ret = RetVec[i];
1164 IRBuilder<> IRBRet(Ret);
1165
1166 // Mark the current frame as retired.
1167 IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1168 BasePlus0);
1169 // Unpoison the stack.
1170 PoisonStack(ArrayRef<AllocaInst*>(AllocaVec), IRBRet, ShadowBase, false);
1171
1172 if (DoStackMalloc) {
1173 IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1174 ConstantInt::get(IntptrTy, LocalStackSize),
1175 OrigStackBase);
1176 }
1177 }
1178
Kostya Serebryanybd0052a2012-10-19 06:20:53 +00001179 // We are done. Remove the old unused alloca instructions.
1180 for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1181 AllocaVec[i]->eraseFromParent();
1182
Kostya Serebryany800e03f2011-11-16 01:35:23 +00001183 if (ClDebugStack) {
1184 DEBUG(dbgs() << F);
1185 }
1186
1187 return true;
1188}