AddressSanitizer.cpp revision 20985711c76b8799d689a9c0e416b68896333c23
1800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
3800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//                     The LLVM Compiler Infrastructure
4800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
5800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is distributed under the University of Illinois Open Source
6800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// License. See LICENSE.TXT for details.
7800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
8800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
9800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
10800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is a part of AddressSanitizer, an address sanity checker.
11800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Details of the algorithm:
12800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
14800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
15800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
16800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#define DEBUG_TYPE "asan"
17800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
18d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Transforms/Instrumentation.h"
19800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
201c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov#include "llvm/ADT/DenseMap.h"
2159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov#include "llvm/ADT/DepthFirstIterator.h"
22800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
23800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
24800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
25800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
2706fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
281afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/DIBuilder.h"
290b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
300b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Function.h"
310b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
320b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/InlineAsm.h"
330b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
340b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/LLVMContext.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Module.h"
360b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Type.h"
3759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov#include "llvm/InstVisitor.h"
381479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany#include "llvm/Support/CallSite.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
423e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany#include "llvm/Support/Endian.h"
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
4690230c84668269fbd53d163e398cd16486d5d414Chandler Carruth#include "llvm/Transforms/Utils/BlackList.h"
4720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany#include "llvm/Transforms/Utils/Cloning.h"
481afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/Transforms/Utils/Local.h"
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
51d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include <string>
52800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryanystatic const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
5948a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryanystatic const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
603e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryanystatic const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
62800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
63800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
64800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
65800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
677bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
687bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
706ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryanystatic const char *kAsanReportLoadN = "__asan_report_load_n";
716ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryanystatic const char *kAsanReportStoreN = "__asan_report_store_n";
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
737bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
763016056769639878b4f152838f0cf16d2e482339Kostya Serebryanystatic const char *kAsanInitName = "__asan_init_v3";
7795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
78800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
79800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
80800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
8251c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryanystatic const char *kAsanGenPrefix = "__asan_gen_";
83f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonovstatic const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
84f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonovstatic const char *kAsanUnpoisonStackMemoryName =
85f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    "__asan_unpoison_stack_memory";
86800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
87800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
88800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
89800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
90800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
91800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
92c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
93c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
94c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
95800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
96800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
97800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
98800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
99800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
100800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
101800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
102e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
103e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
104e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
1056e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryanystatic cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
1066e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::desc("use instrumentation with slow path for all accesses"),
1076e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::Hidden, cl::init(false));
108c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
109324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
110324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
111324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
112324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
113324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
114324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
115324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
1259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic cl::opt<bool> ClInitializers("asan-initialization-order",
1269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
1296c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryanystatic cl::opt<bool> ClRealignStack("asan-realign-stack",
1306c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryany       cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
131b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonovstatic cl::opt<std::string> ClBlacklistFile("asan-blacklist",
132b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov       cl::desc("File containing the list of objects to ignore "
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
13520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// This is an experimental feature that will allow to choose between
13620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// instrumented and non-instrumented code at link-time.
13720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// If this option is on, just before instrumenting a function we create its
13820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// clone; if the function is not changed by asan the clone is deleted.
13920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// If we end up with a clone, we put the instrumented function into a section
14020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// called "ASAN" and the uninstrumented function into a section called "NOASAN".
14120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany//
14220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// This is still a prototype, we need to figure out a way to keep two copies of
14320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// a function so that the linker can easily choose one of them.
14420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryanystatic cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
14520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany       cl::desc("Keep uninstrumented copies of functions"),
14620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany       cl::Hidden, cl::init(false));
14720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
155117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryanystatic cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
156117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany       cl::desc("Use short immediate constant as the mapping offset for 64bit"),
1570bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany       cl::Hidden, cl::init(true));
158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
165800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
166800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
167800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
169ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonovstatic cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
170ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
171ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::Hidden, cl::init(false));
172ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov
173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
178800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
180800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
181800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
186ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany/// A set of dynamically initialized globals extracted from metadata.
187ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryanyclass SetOfDynamicallyInitializedGlobals {
188ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany public:
189ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  void Init(Module& M) {
190ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    // Clang generates metadata identifying all dynamically initialized globals.
191ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    NamedMDNode *DynamicGlobals =
192ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
193ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    if (!DynamicGlobals)
194ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      return;
195ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
196ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      MDNode *MDN = DynamicGlobals->getOperand(i);
197ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      assert(MDN->getNumOperands() == 1);
198ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      Value *VG = MDN->getOperand(0);
199ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // The optimizer may optimize away a global entirely, in which case we
200ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // cannot instrument access to it.
201ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      if (!VG)
202ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        continue;
203ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      DynInitGlobals.insert(cast<GlobalVariable>(VG));
204ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    }
205ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  }
206ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
207ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany private:
208ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SmallSet<GlobalValue*, 32> DynInitGlobals;
209ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany};
210ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
21119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov/// This struct defines the shadow mapping using the rule:
21248a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany///   shadow = (mem >> Scale) ADD-or-OR Offset.
21319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovstruct ShadowMapping {
21419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  int Scale;
21519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  uint64_t Offset;
21648a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  bool OrShadowOffset;
21719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov};
21819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
21911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonovstatic ShadowMapping getShadowMapping(const Module &M, int LongSize,
22011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                      bool ZeroBaseShadow) {
22111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  llvm::Triple TargetTriple(M.getTargetTriple());
22211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
223c8a196ae8fad3cba7a777e2e7916fd36ebf70fe6Alexander Potapenko  bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
22448a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64;
2250bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany  bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
2263e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany  bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
2273e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                  TargetTriple.getArch() == llvm::Triple::mipsel;
22819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
22919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
23019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
23148a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // OR-ing shadow offset if more efficient (at least on x86),
23248a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // but on ppc64 we have to use add since the shadow offset is not neccesary
23348a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // 1/8-th of the address space.
234117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany  Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
23548a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany
23611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
2373e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany      (LongSize == 32 ?
2383e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany       (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
23948a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany       IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
240c8a196ae8fad3cba7a777e2e7916fd36ebf70fe6Alexander Potapenko  if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
2410bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany    assert(LongSize == 64);
242117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany    Mapping.Offset = kDefaultShort64bitShadowOffset;
24339f02940ba085af79011f7e9095bf9902cd0fa6fKostya Serebryany  }
24439f02940ba085af79011f7e9095bf9902cd0fa6fKostya Serebryany  if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
24519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    // Zero offset log is the special case.
24619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
24719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
24819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
24919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  Mapping.Scale = kDefaultShadowScale;
25019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  if (ClMappingScale) {
25119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    Mapping.Scale = ClMappingScale;
25219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
25319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
25419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  return Mapping;
255b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
256b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
25719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovstatic size_t RedzoneSizeForScale(int MappingScale) {
258b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
259b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
26019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  return std::max(32U, 1U << MappingScale);
261b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
262ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
263800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
264ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanystruct AddressSanitizer : public FunctionPass {
265b4ba5e68e1ac00bfb93572a1f271673deefd7ea9Alexey Samsonov  AddressSanitizer(bool CheckInitOrder = true,
266ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov                   bool CheckUseAfterReturn = false,
267b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                   bool CheckLifetime = false,
26811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                   StringRef BlacklistFile = StringRef(),
26911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                   bool ZeroBaseShadow = false)
270ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : FunctionPass(ID),
271ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
272ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
273b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckLifetime(CheckLifetime || ClCheckLifetime),
274b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
27511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                            : BlacklistFile),
27611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov        ZeroBaseShadow(ZeroBaseShadow) {}
2771416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
2781416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerFunctionPass";
2791416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
280ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMop(Instruction *I);
2816ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
2826ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite,
2836ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                         Value *SizeArgument);
284c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
285c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
286ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
2876ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex,
2886ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                 Value *SizeArgument);
289ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool instrumentMemIntrinsic(MemIntrinsic *MI);
290ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
291c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
294ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool runOnFunction(Function &F);
295a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
29619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
297ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  virtual bool doInitialization(Module &M);
298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
3018b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  void initializeCallbacks(Module &M);
302800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
3039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
3045a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
3059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void FindDynamicInitializers(Module &M);
306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
307ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
308ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckUseAfterReturn;
309ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckLifetime;
31011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  SmallString<64> BlacklistFile;
31111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool ZeroBaseShadow;
31211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
313800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
3143574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  DataLayout *TD;
315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
31719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
320ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  Function *AsanHandleNoReturnFunc;
321b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  OwningPtr<BlackList> BL;
3229db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
3239db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
3246ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // This array is indexed by AccessIsWrite.
3256ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Function *AsanErrorCallbackSized[2];
326f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
327ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
32859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
32959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  friend struct FunctionStackPoisoner;
330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
331c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
3321416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyclass AddressSanitizerModule : public ModulePass {
333b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany public:
334b4ba5e68e1ac00bfb93572a1f271673deefd7ea9Alexey Samsonov  AddressSanitizerModule(bool CheckInitOrder = true,
33511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         StringRef BlacklistFile = StringRef(),
33611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         bool ZeroBaseShadow = false)
337ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : ModulePass(ID),
338b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
339b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
34011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                            : BlacklistFile),
34111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov        ZeroBaseShadow(ZeroBaseShadow) {}
3421416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  bool runOnModule(Module &M);
3431416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  static char ID;  // Pass identification, replacement for typeid
3441416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
3451416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerModule";
3461416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
347f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
348b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany private:
3494684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  void initializeCallbacks(Module &M);
3504684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
351b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
352ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
35319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t RedzoneSize() const {
35419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    return RedzoneSizeForScale(Mapping.Scale);
35519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
356b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
357ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
358b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  SmallString<64> BlacklistFile;
35911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool ZeroBaseShadow;
36011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
361b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  OwningPtr<BlackList> BL;
362b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
363b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Type *IntptrTy;
364b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  LLVMContext *C;
3651416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  DataLayout *TD;
36619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
3674684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanPoisonGlobals;
3684684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnpoisonGlobals;
3694684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanRegisterGlobals;
3704684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnregisterGlobals;
371b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany};
372b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
37359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Stack poisoning does not play well with exception handling.
37459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// When an exception is thrown, we essentially bypass the code
37559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// that unpoisones the stack. This is why the run-time library has
37659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
37759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// stack in the interceptor. This however does not work inside the
37859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// actual function which catches the exception. Most likely because the
37959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// compiler hoists the load of the shadow value somewhere too high.
38059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// This causes asan to report a non-existing bug on 453.povray.
38159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// It sounds like an LLVM bug.
38259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovstruct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
38359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function &F;
38459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AddressSanitizer &ASan;
38559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  DIBuilder DIB;
38659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  LLVMContext *C;
38759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrTy;
38859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrPtrTy;
38919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
39059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
39159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<AllocaInst*, 16> AllocaVec;
39259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<Instruction*, 8> RetVec;
39359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t TotalStackSize;
39459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  unsigned StackAlignment;
39559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
39659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function *AsanStackMallocFunc, *AsanStackFreeFunc;
39759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
39859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
3991c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Stores a place and arguments of poisoning/unpoisoning call for alloca.
4001c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  struct AllocaPoisonCall {
4011c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IntrinsicInst *InsBefore;
4021c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    uint64_t Size;
4031c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool DoPoison;
4041c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  };
4051c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
4061c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
4071c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Maps Value to an AllocaInst from which the Value is originated.
4081c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
4091c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValueMapTy AllocaForValue;
4101c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
41159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
41259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
41359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
41419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov        Mapping(ASan.Mapping),
41519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov        TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
41659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
41759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool runOnFunction() {
41859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!ClStack) return false;
41959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // Collect alloca, ret, lifetime instructions etc.
42059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
42159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov         DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
42259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      BasicBlock *BB = *DI;
42359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      visit(*BB);
42459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
42559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (AllocaVec.empty()) return false;
42659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
42759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    initializeCallbacks(*F.getParent());
42859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
42959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonStack();
43059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
43159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (ClDebugStack) {
43259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      DEBUG(dbgs() << F);
43359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
43459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return true;
43559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
43659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
43759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Finds all static Alloca instructions and puts
43859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // poisoned red zones around all of them.
43959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Then unpoison everything back before the function returns.
44059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonStack();
44159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
44259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ----------------------- Visitors.
44359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect all Ret instructions.
44459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitReturnInst(ReturnInst &RI) {
44559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    RetVec.push_back(&RI);
44659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
44759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
44859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect Alloca instructions we want (and can) handle.
44959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitAllocaInst(AllocaInst &AI) {
4501c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!isInterestingAlloca(AI)) return;
45159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
45259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = std::max(StackAlignment, AI.getAlignment());
45359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    AllocaVec.push_back(&AI);
45459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t AlignedSize =  getAlignedAllocaSize(&AI);
45559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    TotalStackSize += AlignedSize;
45659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
45759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
4581c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// \brief Collect lifetime intrinsic calls to check for use-after-scope
4591c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// errors.
4601c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  void visitIntrinsicInst(IntrinsicInst &II) {
4611c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!ASan.CheckLifetime) return;
4621c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Intrinsic::ID ID = II.getIntrinsicID();
4631c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (ID != Intrinsic::lifetime_start &&
4641c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        ID != Intrinsic::lifetime_end)
4651c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      return;
4661c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Found lifetime intrinsic, add ASan instrumentation if necessary.
4671c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
4681c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // If size argument is undefined, don't do anything.
4691c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (Size->isMinusOne()) return;
4701c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Check that size doesn't saturate uint64_t and can
4711c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // be stored in IntptrTy.
4721c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    const uint64_t SizeValue = Size->getValue().getLimitedValue();
4731c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (SizeValue == ~0ULL ||
4741c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
4751c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      return;
4761c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Find alloca instruction that corresponds to llvm.lifetime argument.
4771c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
4781c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!AI) return;
4791c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool DoPoison = (ID == Intrinsic::lifetime_end);
4801c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
4811c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaPoisonCallVec.push_back(APC);
4821c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
4831c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
48459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ---------------------- Helpers.
48559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void initializeCallbacks(Module &M);
48659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
4871c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Check if we want (and can) handle this alloca.
4881c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  bool isInterestingAlloca(AllocaInst &AI) {
4891c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return (!AI.isArrayAllocation() &&
4901c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov            AI.isStaticAlloca() &&
4911c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov            AI.getAllocatedType()->isSized());
4921c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
4931c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
49419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t RedzoneSize() const {
49519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    return RedzoneSizeForScale(Mapping.Scale);
49619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
49759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
49859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Type *Ty = AI->getAllocatedType();
49959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
50059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return SizeInBytes;
50159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
50259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAlignedSize(uint64_t SizeInBytes) {
50359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    size_t RZ = RedzoneSize();
50459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return ((SizeInBytes + RZ - 1) / RZ) * RZ;
50559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
50659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
50759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
50859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return getAlignedSize(SizeInBytes);
50959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
5101c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// Finds alloca where the value comes from.
5111c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaInst *findAllocaForValue(Value *V);
51259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
51359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                      Value *ShadowBase, bool DoPoison);
51459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
51559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov};
51659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
517800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
518800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
519800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
520800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
521800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
522800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
523ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey SamsonovFunctionPass *llvm::createAddressSanitizerFunctionPass(
524b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov    bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
52511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov    StringRef BlacklistFile, bool ZeroBaseShadow) {
526ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
52711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                              CheckLifetime, BlacklistFile, ZeroBaseShadow);
528800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
529800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5301416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanychar AddressSanitizerModule::ID = 0;
5311416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya SerebryanyINITIALIZE_PASS(AddressSanitizerModule, "asan-module",
5321416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
5331416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "ModulePass", false, false)
534b0dcf61252e58715a3bea79f4c112572df361c30Alexey SamsonovModulePass *llvm::createAddressSanitizerModulePass(
53511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov    bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
53611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
53711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                    ZeroBaseShadow);
53825878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
53925878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
5402735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
541c6af2432c802d241c8fffbe0371c023e6c58844eMichael J. Spencer  size_t Res = countTrailingZeros(TypeSize / 8);
5422735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
5432735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
5442735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
5452735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
54818c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
5495111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
55051c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst,
55151c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany                            kAsanGenPrefix);
5525111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GV->setUnnamedAddr(true);  // Ok to merge these.
5535111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
5545111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  return GV;
55551c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany}
55651c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany
55751c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryanystatic bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
55851c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  return G->getName().find(kAsanGenPrefix) == 0;
559800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
560800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
561800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
562800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
56319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
56419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  if (Mapping.Offset == 0)
565800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
566800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
56748a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  if (Mapping.OrShadowOffset)
56848a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany    return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
56948a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  else
57048a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany    return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
571800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
572800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
573c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
574ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    Instruction *OrigIns,
575800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
5766ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRBuilder<> IRB(InsertBefore);
5776ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  if (Size->getType() != IntptrTy)
5786ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    Size = IRB.CreateIntCast(Size, IntptrTy, false);
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
5806ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
581800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
5826ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRB.SetInsertPoint(InsertBefore);
5836ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
5846ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
5856ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
5866ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
587800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
590ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
591800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
592800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
5932735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
595800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
599800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
600800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
603800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
604800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
60556139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
6064a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
607800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
608800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
609ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
610800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
611ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
612800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
613800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
614800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
615e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
616e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
617e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
618800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
619e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
620e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
622800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
623e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
624e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
625e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
626e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
627e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
628e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
629e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
630e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
631e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
632e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
633e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
634e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
635e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
636e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
637e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
638e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
640800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
641ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentMop(Instruction *I) {
6423780ad8b998d93d7db406919c06137cdb786ef05Axel Naumann  bool IsWrite = false;
643e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
644e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
6459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClOpt && ClOptGlobals) {
6469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
6479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If initialization order checking is disabled, a simple access to a
6489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // dynamically initialized global is always valid.
649ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      if (!CheckInitOrder)
6509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
6519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If a global variable does not have dynamic initialization we don't
652407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // have to instrument it.  However, if a global does not have initailizer
653407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // at all, we assume it has dynamic initializer (in other TU).
654407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
6559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
6569b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
657800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
6589b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
659800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
660800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
661800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
662800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
663605ff6655b31033dde21e61416751847bd0ee201Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
664800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6656ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  assert((TypeSize % 8) == 0);
666800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6676ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
6686ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  if (TypeSize == 8  || TypeSize == 16 ||
6696ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
6706ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
6716ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // Instrument unusual size (but still multiple of 8).
6726ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // We can not do it with a single check, so we do 1-byte check for the first
6736ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
6746ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // to report the actual access size.
675800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
6766ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *LastByte =  IRB.CreateIntToPtr(
6776ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
6786ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                    ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
6796ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      OrigPtrTy);
6806ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
6816ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(I, I, Addr, 8, IsWrite, Size);
6826ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
683800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
684800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
68555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
68655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
68755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
68855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
689b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryanystatic Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
69055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
69155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
69255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
69355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
69455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
69555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
696800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
697ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
6986ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
699ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
7006ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  CallInst *Call = SizeArgument
7016ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
7026ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
7036ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany
704f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
705f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
706f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
707f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
7083c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
709800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
710800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7112735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
712c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
713c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
71419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t Granularity = 1 << Mapping.Scale;
715c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
716c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
717c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
718c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
719c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
720c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
721c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
722c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
723c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
7246e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany      LastAccessedByte, ShadowValue->getType(), false);
725c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
726c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
727c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
728c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
729ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
7306ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         Instruction *InsertBefore,
7316ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         Value *Addr, uint32_t TypeSize,
7326ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         bool IsWrite, Value *SizeArgument) {
7336ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRBuilder<> IRB(InsertBefore);
734800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
735800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
736800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
73719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov      *C, std::max(8U, TypeSize >> Mapping.Scale));
738800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
739800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
740800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
741800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
742800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
743800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
744800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
74511c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
74619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t Granularity = 1 << Mapping.Scale;
747ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
748ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
7496e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
7504a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    TerminatorInst *CheckTerm =
7514a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
752ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
753f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
754c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
755c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
756ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    BasicBlock *CrashBlock =
757ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
758ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
759f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
760f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
761c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
7624a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
764ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
7656ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Instruction *Crash = generateCrashCode(
7666ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
767ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
769800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7701416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyvoid AddressSanitizerModule::createInitializerPoisonCalls(
771ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    Module &M, GlobalValue *ModuleName) {
7729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
7739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
7749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // If that function is not present, this TU contains no globals, or they have
7759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // all been optimized away
7769b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!GlobalInit)
7779b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
7789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Set up the arguments to our poison/unpoison functions.
7809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
7819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add a call to poison all external globals before the given function starts.
783ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
784ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
7859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add calls to unpoison all globals before each return instruction.
7879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
7889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      I != E; ++I) {
7899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
7909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      CallInst::Create(AsanUnpoisonGlobals, "", RI);
7919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
7929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
7939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
7949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7951416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
7969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Type *Ty = cast<PointerType>(G->getType())->getElementType();
797324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
7989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
79959a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany  if (BL->isIn(*G)) return false;
8009b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!Ty->isSized()) return false;
8019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!G->hasInitializer()) return false;
80251c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
8039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Touch only those globals that will not be defined in other modules.
8049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Don't handle ODR type linkages since other modules may be built w/o asan.
8059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
8069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::PrivateLinkage &&
8079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::InternalLinkage)
8089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Two problems with thread-locals:
8109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - The address of the main thread's copy can't be computed at link-time.
8119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - Need to poison all copies, not just the main thread's one.
8129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->isThreadLocal())
8139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8149b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // For now, just ignore this Alloca if the alignment is large.
815b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  if (G->getAlignment() > RedzoneSize()) return false;
8169b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8179b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Ignore all the globals with the names starting with "\01L_OBJC_".
8189b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Many of those are put into the .cstring section. The linker compresses
8199b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // that section by removing the spare \0s after the string terminator, so
8209b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // our redzones get broken.
8219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if ((G->getName().find("\01L_OBJC_") == 0) ||
8229b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      (G->getName().find("\01l_OBJC_") == 0)) {
8239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
8249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
8269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->hasSection()) {
8289b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    StringRef Section(G->getSection());
8299b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
8309b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
8319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // them.
8329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if ((Section.find("__OBJC,") == 0) ||
8339b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        (Section.find("__DATA, __objc_") == 0)) {
8349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
8359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
8369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
8389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Constant CFString instances are compiled in the following way:
8399b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the string buffer is emitted into
8409b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     __TEXT,__cstring,cstring_literals
8419b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the constant NSConstantString structure referencing that buffer
8429b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     is placed into __DATA,__cfstring
8439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Therefore there's no point in placing redzones into __DATA,__cfstring.
8449b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Moreover, it causes the linker to crash on OS X 10.7
8459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (Section.find("__DATA,__cfstring") == 0) {
8469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring CFString: " << *G);
8479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
8489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
8509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return true;
8529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
8539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8544684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonovvoid AddressSanitizerModule::initializeCallbacks(Module &M) {
8554684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  IRBuilder<> IRB(*C);
8564684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare our poisoning and unpoisoning functions.
8574684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
858ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
8594684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
8604684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8614684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
8624684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
8634684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare functions that register/unregister globals.
8644684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8654684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanRegisterGlobalsName, IRB.getVoidTy(),
8664684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IntptrTy, IntptrTy, NULL));
8674684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
8684684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8694684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnregisterGlobalsName,
8704684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
8714684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
8724684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov}
8734684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
874800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
875800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
876800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
8771416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::runOnModule(Module &M) {
8781416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!ClGlobals) return false;
8791416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
8801416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!TD)
8811416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return false;
882b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  BL.reset(new BlackList(BlacklistFile));
883d6f62c8da5aa4f3388cec1542309ffa623cac601Alexey Samsonov  if (BL->isIn(M)) return false;
884b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  C = &(M.getContext());
88519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  int LongSize = TD->getPointerSizeInBits();
88619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  IntptrTy = Type::getIntNTy(*C, LongSize);
88711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
8884684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  initializeCallbacks(M);
8894684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  DynamicallyInitializedGlobals.Init(M);
890b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Module::GlobalListType::iterator G = M.global_begin(),
8949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       E = M.global_end(); G != E; ++G) {
8959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ShouldInstrumentGlobal(G))
8969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      GlobalsToChange.push_back(G);
897800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
898800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
899800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
900800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
901800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
902800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
903800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
904800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
905800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
906800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
907086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany  //   const char *module_name;
9089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   size_t has_dynamic_init;
909800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
910800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
9119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, IntptrTy,
912086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
9139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  SmallVector<Constant *, 16> Initializers(n), DynamicInit;
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
915b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
916b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
917b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  assert(CtorFunc);
918b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
920ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  bool HasDynamicallyInitializedGlobals = false;
9219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
922086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany  GlobalVariable *ModuleName = createPrivateGlobalForString(
923086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany      M, M.getModuleIdentifier());
924ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  // We shouldn't merge same module names, as this string serves as unique
925ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  // module ID in runtime.
926ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  ModuleName->setUnnamedAddr(false);
927086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
92929f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    static const uint64_t kMaxGlobalRedzone = 1 << 18;
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
933208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
93429f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    uint64_t MinRZ = RedzoneSize();
93563f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // MinRZ <= RZ <= kMaxGlobalRedzone
93663f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // and trying to make RZ to be ~ 1/4 of SizeInBytes.
93729f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    uint64_t RZ = std::max(MinRZ,
93863f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany                         std::min(kMaxGlobalRedzone,
93963f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany                                  (SizeInBytes / MinRZ / 4) * MinRZ));
94063f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    uint64_t RightRedzoneSize = RZ;
94163f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // Round up to MinRZ
94263f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    if (SizeInBytes % MinRZ)
94363f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany      RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
94463f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
945800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
9469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Determine whether this global should be poisoned in initialization.
947ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    bool GlobalHasDynamicInitializer =
948ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        DynamicallyInitializedGlobals.Contains(G);
94959a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany    // Don't check initialization order if this global is blacklisted.
9507dadac65d375ff21b7a36bfb7642578d2f467525Kostya Serebryany    GlobalHasDynamicInitializer &= !BL->isInInit(*G);
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
952800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
953800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
954800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
955800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
956800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
957086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
958800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
959800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
960800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
962ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
963800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
96463f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    NewGlobal->setAlignment(MinRZ);
965800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
966800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
971f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
973800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
976800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
977800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
978800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
980800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
981086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany        ConstantExpr::getPointerCast(ModuleName, IntptrTy),
9829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
983800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
9849b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
9859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Populate the first and last globals declared in this TU.
986ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    if (CheckInitOrder && GlobalHasDynamicInitializer)
987ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov      HasDynamicallyInitializedGlobals = true;
9889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
989324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9979b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Create calls for poisoning before initializers run and unpoisoning after.
998ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  if (CheckInitOrder && HasDynamicallyInitializedGlobals)
999ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    createInitializerPoisonCalls(M, ModuleName);
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
1003800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10047bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
10057bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
10067bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
10077bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
10087bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
10097bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
10107bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
10117bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
10127bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
10137bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
10147bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
10157bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
1016800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10208b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanyvoid AddressSanitizer::initializeCallbacks(Module &M) {
10218b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(*C);
10229db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
10239db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
10249db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
10259db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
10269db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
10279db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
10289db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
10294f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
10307846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
10317846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany          checkInterfaceFunction(M.getOrInsertFunction(
10327846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
10339db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
10349db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
10356ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
10366ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany              kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
10376ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
10386ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany              kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1039ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
1040ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1041ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1042f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
1043f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1044f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
1045f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
10468b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany}
10478b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
104819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovvoid AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
104911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Tell the values of mapping offset and scale to the run-time.
105011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  GlobalValue *asan_mapping_offset =
105111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
105211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                     ConstantInt::get(IntptrTy, Mapping.Offset),
105311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                     kAsanMappingOffsetName);
105411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Read the global, otherwise it may be optimized away.
105511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  IRB.CreateLoad(asan_mapping_offset, true);
105611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
105711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  GlobalValue *asan_mapping_scale =
105811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
105911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         ConstantInt::get(IntptrTy, Mapping.Scale),
106011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         kAsanMappingScaleName);
106111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Read the global, otherwise it may be optimized away.
106211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  IRB.CreateLoad(asan_mapping_scale, true);
106319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov}
106419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
10658b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany// virtual
10668b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanybool AddressSanitizer::doInitialization(Module &M) {
10678b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // Initialize the private fields. No one has accessed them before.
10688b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
10698b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10708b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  if (!TD)
10718b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany    return false;
1072b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  BL.reset(new BlackList(BlacklistFile));
10738b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  DynamicallyInitializedGlobals.Init(M);
10748b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10758b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  C = &(M.getContext());
10768b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  LongSize = TD->getPointerSizeInBits();
10778b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
10788b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10798b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanCtorFunction = Function::Create(
10808b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
10818b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
10828b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
10838b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // call __asan_init in the module ctor.
10848b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
10858b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction = checkInterfaceFunction(
10868b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
10878b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
10888b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRB.CreateCall(AsanInitFunction);
10899db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
109011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
109119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  emitShadowMapping(M, IRB);
1092800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10937bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1094ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  return true;
1095ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany}
1096ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
1097a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1098a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
1099a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
1100a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
1101a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
1102a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
1103a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
1104a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
1105a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
1106a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
1107a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
1108a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
1109a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
1110a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
1111a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
1112a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
1113ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::runOnFunction(Function &F) {
1114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
1115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
11163797adb94fdc6b747cb0e97a64b15b931f2533b8Kostya Serebryany  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1117324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
11188b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  initializeCallbacks(*F.getParent());
1119a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
11208eec41fc778e99d42172a7f6de76faa43a6d8847Kostya Serebryany  // If needed, insert __asan_init before checking for SanitizeAddress attr.
1121a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
1122a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
112320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (!F.hasFnAttribute(Attribute::SanitizeAddress))
11246765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling    return false;
1125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
11286765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling
11296765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // We want to instrument every address only once per basic block (unless there
11306765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // are calls between uses).
1131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
1132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
113395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
113420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  int NumAllocas = 0;
1135e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
1136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
1138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
1139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
1140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
1141324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
1142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
1144bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
1145e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
1147800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
1148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
1149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
1152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
115320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany        if (isa<AllocaInst>(BI))
115420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany          NumAllocas++;
11551479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany        CallSite CS(BI);
11561479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany        if (CS) {
1157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
1158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
11591479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany          if (CS.doesNotReturn())
11601479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany            NoReturnCalls.push_back(CS.getInstruction());
1161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
1163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
1165324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
1166324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1167324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
1168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1169800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
117120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  Function *UninstrumentedDuplicate = 0;
117220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  bool LikelyToInstrument =
117320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
117420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (ClKeepUninstrumented && LikelyToInstrument) {
117520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    ValueToValueMapTy VMap;
117620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
117720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
117820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
117920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
118020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  }
118120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
1182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
1183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
1184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
1186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
1187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1188e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
1189ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMop(Inst);
1190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
1191ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
1194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
119659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner FSP(F, *this);
119759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool ChangedStack = FSP.runOnFunction();
119895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
119995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
120095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
120195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
120295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
120395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
1204ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    IRB.CreateCall(AsanHandleNoReturnFunc);
120595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
120695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
120720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
120820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
120920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
121020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (ClKeepUninstrumented) {
121120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    if (!res) {
121220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      // No instrumentation is done, no need for the duplicate.
121320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      if (UninstrumentedDuplicate)
121420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany        UninstrumentedDuplicate->eraseFromParent();
121520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    } else {
121620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      // The function was instrumented. We must have the duplicate.
121720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      assert(UninstrumentedDuplicate);
121820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      UninstrumentedDuplicate->setSection("NOASAN");
121920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      assert(!F.hasSection());
122020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      F.setSection("ASAN");
122120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    }
122220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  }
122320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
122420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  return res;
1225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1226800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1227800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1228800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
1229800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1230800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
1231800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
1232800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
1233858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1234800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1235800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1236800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1237800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
1238b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                            size_t RZSize,
1239800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
1240800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
1241b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  for (size_t i = 0; i < RZSize;
1242800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
1243800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
1244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
1245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
1246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
1247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
1248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
1249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1250800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1252800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
125359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Workaround for bug 11395: we don't want to instrument stack in functions
125459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
125559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// FIXME: remove once the bug 11395 is fixed.
125659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovbool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
125759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (LongSize != 32) return false;
125859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  CallInst *CI = dyn_cast<CallInst>(I);
125959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (!CI || !CI->isInlineAsm()) return false;
126059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (CI->getNumArgOperands() <= 5) return false;
126159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // We have inline assembly with quite a few arguments.
126259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return true;
126359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
126459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
126559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::initializeCallbacks(Module &M) {
126659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  IRBuilder<> IRB(*C);
126759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
126859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
126959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
127059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanStackFreeName, IRB.getVoidTy(),
127159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      IntptrTy, IntptrTy, IntptrTy, NULL));
127259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
127359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
127459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
127559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
127659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
127759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
127859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonRedZones(
127959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
128059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoPoison) {
128119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1282800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1283800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1284800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
1285800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1286800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
1287800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1288800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
1289800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1290800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
1291800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1292800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1293800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
1294800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1295800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1296800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
1297b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1298800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1299800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1300800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1301800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1302b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize());
1303800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
1304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1305800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
1306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
1308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
1309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
1310800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
1311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
131219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                                       (Pos >> Mapping.Scale) - ShadowRZSize));
1313b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany      size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
1315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
1316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1317b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                        RedzoneSize(),
131819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                                        1ULL << Mapping.Scale,
1319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
13203e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany        Poison =
13213e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany            ASan.TD->isLittleEndian()
13223e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                ? support::endian::byte_swap<uint32_t, support::little>(Poison)
13233e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                : support::endian::byte_swap<uint32_t, support::big>(Poison);
1324800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1326800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
1330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
133119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                        ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
13321c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool LastAlloca = (i == AllocaVec.size() - 1);
13331c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1334800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1335800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1336b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += RedzoneSize();
1337800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1338800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
134059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonStack() {
134159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t LocalStackSize = TotalStackSize +
134259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                            (AllocaVec.size() + 1) * RedzoneSize();
1343800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
134459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoStackMalloc = ASan.CheckUseAfterReturn
1345800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
1346800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
13471c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  assert(AllocaVec.size() > 0);
1348800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
1349800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
1350800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1351800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1352800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1353800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
1354800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
135559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (ClRealignStack && StackAlignment < RedzoneSize())
135659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = RedzoneSize();
135759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  MyAlloca->setAlignment(StackAlignment);
1358800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
1359800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1360800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
1361800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1362800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1363800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1364800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1365800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1366800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
13673016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // This string will be parsed by the run-time (DescribeAddressIfStack).
1368800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
1369800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
13703016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  StackDescription << AllocaVec.size() << " ";
1371800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
13721c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Insert poison calls for lifetime intrinsics for alloca.
13731c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  bool HavePoisonedAllocas = false;
13741c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
13751c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
13761c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IntrinsicInst *II = APC.InsBefore;
13771c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
13781c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    assert(AI);
13791c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IRBuilder<> IRB(II);
13801c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
13811c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    HavePoisonedAllocas |= APC.DoPoison;
13821c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
13831c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
1384b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1385800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1386800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1387800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1388800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1389800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1390800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1391800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1392800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1393b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert((AlignedSize % RedzoneSize()) == 0);
1394f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    Value *NewAllocaPtr = IRB.CreateIntToPtr(
1395800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1396f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov            AI->getType());
13971afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1398f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    AI->replaceAllUsesWith(NewAllocaPtr);
1399b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += AlignedSize + RedzoneSize();
1400800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1401800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1402800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
14033016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // The left-most redzone has enough space for at least 4 pointers.
14043016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the Magic value to redzone[0].
1405800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1406800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1407800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
14083016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the frame description constant to redzone[1].
14093016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  Value *BasePlus1 = IRB.CreateIntToPtr(
14103016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
14113016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IntptrPtrTy);
14129ce84c1c95c0153a2f33e188ce0db00770425f9eAlexey Samsonov  GlobalVariable *StackDescriptionGlobal =
1413a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
141459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
141559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                             IntptrTy);
1416800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
14173016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the PC to redzone[2].
14183016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  Value *BasePlus2 = IRB.CreateIntToPtr(
14193016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
14203016056769639878b4f152838f0cf16d2e482339Kostya Serebryany                                                   2 * ASan.LongSize/8)),
14213016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IntptrPtrTy);
14223016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1423800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1424800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
142559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
142659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1427800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1428800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1429800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1430800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1431800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1432800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
143659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1438f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // In use-after-return mode, mark the whole stack frame unaddressable.
1439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1442f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    } else if (HavePoisonedAllocas) {
1443f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // If we poisoned some allocas in llvm.lifetime analysis,
1444f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // unpoison whole stack frame now.
1445f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      assert(LocalStackBase == OrigStackBase);
1446f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1447800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1448800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1449800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1450bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  // We are done. Remove the old unused alloca instructions.
1451bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1452bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany    AllocaVec[i]->eraseFromParent();
1453800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1454f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
145559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
145659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                         IRBuilder<> IRB, bool DoPoison) {
1457f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  // For now just insert the call to ASan runtime.
1458f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1459f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1460f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1461f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                           : AsanUnpoisonStackMemoryFunc,
1462f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                  AddrArg, SizeArg);
1463f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov}
146459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
146559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Handling llvm.lifetime intrinsics for a given %alloca:
146659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
146759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
146859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
146959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     could be poisoned by previous llvm.lifetime.end instruction, as the
147059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     variable may go in and out of scope several times, e.g. in loops).
147159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (3) if we poisoned at least one %alloca in a function,
147259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     unpoison the whole stack frame at function exit.
147359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
14741c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey SamsonovAllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
14751c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
14761c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // We're intested only in allocas we can handle.
14771c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return isInterestingAlloca(*AI) ? AI : 0;
14781c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // See if we've already calculated (or started to calculate) alloca for a
14791c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // given value.
14801c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
14811c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (I != AllocaForValue.end())
14821c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return I->second;
14831c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Store 0 while we're calculating alloca for value V to avoid
14841c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // infinite recursion if the value references itself.
14851c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValue[V] = 0;
14861c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaInst *Res = 0;
14871c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (CastInst *CI = dyn_cast<CastInst>(V))
14881c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Res = findAllocaForValue(CI->getOperand(0));
14891c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  else if (PHINode *PN = dyn_cast<PHINode>(V)) {
14901c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
14911c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      Value *IncValue = PN->getIncomingValue(i);
14921c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      // Allow self-referencing phi-nodes.
14931c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      if (IncValue == PN) continue;
14941c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      AllocaInst *IncValueAI = findAllocaForValue(IncValue);
14951c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      // AI for incoming values should exist and should all be equal.
14961c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
14971c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        return 0;
14981c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      Res = IncValueAI;
149959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
150059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
15011c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (Res != 0)
15021c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaForValue[V] = Res;
150359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return Res;
150459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
1505