AddressSanitizer.cpp revision 4684858624d7ffe82379783e9b678227d5e0b515
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"
19b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany#include "BlackList.h"
20800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.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"
28d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/DataLayout.h"
291afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/DIBuilder.h"
30d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Function.h"
31d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/IRBuilder.h"
32d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/InlineAsm.h"
3359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov#include "llvm/InstVisitor.h"
34d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/IntrinsicInst.h"
35d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/LLVMContext.h"
36d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Module.h"
37800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
38800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
42800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Target/TargetMachine.h"
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
441afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/Transforms/Utils/Local.h"
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
46d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Type.h"
47800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
48d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include <string>
49800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
51800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
52800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
5506fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanovstatic const uint64_t kDefaultShadowOffsetAndroid = 0;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
58800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
59800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
60800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanModuleCtorName = "asan.module_ctor";
627bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanModuleDtorName = "asan.module_dtor";
637bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const int   kAsanCtorAndCtorPriority = 1;
64800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanReportErrorTemplate = "__asan_report_";
65800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanRegisterGlobalsName = "__asan_register_globals";
667bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryanystatic const char *kAsanUnregisterGlobalsName = "__asan_unregister_globals";
679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
689b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic const char *kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
69800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanInitName = "__asan_init";
7095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryanystatic const char *kAsanHandleNoReturnName = "__asan_handle_no_return";
71800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingOffsetName = "__asan_mapping_offset";
72800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanMappingScaleName = "__asan_mapping_scale";
73800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackMallocName = "__asan_stack_malloc";
74800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const char *kAsanStackFreeName = "__asan_stack_free";
7551c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryanystatic const char *kAsanGenPrefix = "__asan_gen_";
76f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonovstatic const char *kAsanPoisonStackMemoryName = "__asan_poison_stack_memory";
77f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonovstatic const char *kAsanUnpoisonStackMemoryName =
78f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    "__asan_unpoison_stack_memory";
79800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
80800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
81800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
82800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
83800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
84800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
85c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
86c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
87c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
88800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
89800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
90800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
91800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
92800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
93800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
94800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
95e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
96e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
97e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
986e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryanystatic cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
996e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::desc("use instrumentation with slow path for all accesses"),
1006e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::Hidden, cl::init(false));
101c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
102324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
103324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
104324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
105324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
106324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
107324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
108324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
1189b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic cl::opt<bool> ClInitializers("asan-initialization-order",
1199b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
1226c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryanystatic cl::opt<bool> ClRealignStack("asan-realign-stack",
1236c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryany       cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
124b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonovstatic cl::opt<std::string> ClBlacklistFile("asan-blacklist",
125b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov       cl::desc("File containing the list of objects to ignore "
126800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
141800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
142800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
146ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonovstatic cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
147ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
148ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::Hidden, cl::init(false));
149ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov
150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
155800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
156800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
163ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany/// A set of dynamically initialized globals extracted from metadata.
164ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryanyclass SetOfDynamicallyInitializedGlobals {
165ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany public:
166ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  void Init(Module& M) {
167ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    // Clang generates metadata identifying all dynamically initialized globals.
168ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    NamedMDNode *DynamicGlobals =
169ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
170ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    if (!DynamicGlobals)
171ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      return;
172ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
173ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      MDNode *MDN = DynamicGlobals->getOperand(i);
174ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      assert(MDN->getNumOperands() == 1);
175ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      Value *VG = MDN->getOperand(0);
176ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // The optimizer may optimize away a global entirely, in which case we
177ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // cannot instrument access to it.
178ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      if (!VG)
179ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        continue;
180ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      DynInitGlobals.insert(cast<GlobalVariable>(VG));
181ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    }
182ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  }
183ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
184ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany private:
185ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SmallSet<GlobalValue*, 32> DynInitGlobals;
186ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany};
187ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
188b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryanystatic int MappingScale() {
189b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  return ClMappingScale ? ClMappingScale : kDefaultShadowScale;
190b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
191b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
192b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryanystatic size_t RedzoneSize() {
193b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
194b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
195b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  return std::max(32U, 1U << MappingScale());
196b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
197ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
198800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
199ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanystruct AddressSanitizer : public FunctionPass {
200ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  AddressSanitizer(bool CheckInitOrder = false,
201ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov                   bool CheckUseAfterReturn = false,
202b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                   bool CheckLifetime = false,
203b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                   StringRef BlacklistFile = StringRef())
204ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : FunctionPass(ID),
205ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
206ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
207b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckLifetime(CheckLifetime || ClCheckLifetime),
208b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
209b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                                            : BlacklistFile) {}
2101416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
2111416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerFunctionPass";
2121416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
213ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMop(Instruction *I);
214ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentAddress(Instruction *OrigIns, IRBuilder<> &IRB,
215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite);
216c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
217c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
218ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
2192735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex);
220ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool instrumentMemIntrinsic(MemIntrinsic *MI);
221ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
222c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
223800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
224800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
225ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool runOnFunction(Function &F);
2269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void createInitializerPoisonCalls(Module &M,
2279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                    Value *FirstAddr, Value *LastAddr);
228a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
229ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  virtual bool doInitialization(Module &M);
230800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
231800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
232800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
2338b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  void initializeCallbacks(Module &M);
234800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
2359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
2365a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
2379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void FindDynamicInitializers(Module &M);
238800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
239ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
240ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckUseAfterReturn;
241ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckLifetime;
242800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
2433574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  DataLayout *TD;
244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint64_t MappingOffset;
245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
249ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  Function *AsanHandleNoReturnFunc;
250b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  SmallString<64> BlacklistFile;
251b5b86d263a651566cb25c0f406f75ceffb771029Kostya Serebryany  OwningPtr<BlackList> BL;
2529db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
2539db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
254f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
255ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
25659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
25759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  friend struct FunctionStackPoisoner;
258800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
259c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
2601416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyclass AddressSanitizerModule : public ModulePass {
261b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany public:
262b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  AddressSanitizerModule(bool CheckInitOrder = false,
263b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                         StringRef BlacklistFile = StringRef())
264ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : ModulePass(ID),
265b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
266b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
267b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                                            : BlacklistFile) {}
2681416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  bool runOnModule(Module &M);
2691416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  static char ID;  // Pass identification, replacement for typeid
2701416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
2711416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerModule";
2721416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
273f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
274b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany private:
2754684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  void initializeCallbacks(Module &M);
2764684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
277b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
278b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  void createInitializerPoisonCalls(Module &M, Value *FirstAddr,
279b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                    Value *LastAddr);
280b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
281ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
282b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  SmallString<64> BlacklistFile;
283b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  OwningPtr<BlackList> BL;
284b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
285b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Type *IntptrTy;
286b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  LLVMContext *C;
2871416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  DataLayout *TD;
2884684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanPoisonGlobals;
2894684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnpoisonGlobals;
2904684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanRegisterGlobals;
2914684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnregisterGlobals;
292b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany};
293b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
29459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Stack poisoning does not play well with exception handling.
29559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// When an exception is thrown, we essentially bypass the code
29659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// that unpoisones the stack. This is why the run-time library has
29759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
29859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// stack in the interceptor. This however does not work inside the
29959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// actual function which catches the exception. Most likely because the
30059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// compiler hoists the load of the shadow value somewhere too high.
30159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// This causes asan to report a non-existing bug on 453.povray.
30259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// It sounds like an LLVM bug.
30359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovstruct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
30459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function &F;
30559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AddressSanitizer &ASan;
30659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  DIBuilder DIB;
30759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  LLVMContext *C;
30859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrTy;
30959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrPtrTy;
31059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
31159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<AllocaInst*, 16> AllocaVec;
31259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<Instruction*, 8> RetVec;
31359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t TotalStackSize;
31459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  unsigned StackAlignment;
31559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
31659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function *AsanStackMallocFunc, *AsanStackFreeFunc;
31759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
31859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
31959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
32059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
32159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
32259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        TotalStackSize(0), StackAlignment(1 << MappingScale()) {}
32359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
32459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool runOnFunction() {
32559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!ClStack) return false;
32659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // Collect alloca, ret, lifetime instructions etc.
32759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
32859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov         DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
32959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      BasicBlock *BB = *DI;
33059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      visit(*BB);
33159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
33259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (AllocaVec.empty()) return false;
33359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
33459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    initializeCallbacks(*F.getParent());
33559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
33659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonStack();
33759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
33859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (ClDebugStack) {
33959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      DEBUG(dbgs() << F);
34059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
34159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return true;
34259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
34359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
34459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Finds all static Alloca instructions and puts
34559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // poisoned red zones around all of them.
34659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Then unpoison everything back before the function returns.
34759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonStack();
34859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
34959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ----------------------- Visitors.
35059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect all Ret instructions.
35159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitReturnInst(ReturnInst &RI) {
35259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    RetVec.push_back(&RI);
35359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
35459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
35559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect Alloca instructions we want (and can) handle.
35659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitAllocaInst(AllocaInst &AI) {
35759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (AI.isArrayAllocation()) return;
35859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!AI.isStaticAlloca()) return;
35959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!AI.getAllocatedType()->isSized()) return;
36059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
36159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = std::max(StackAlignment, AI.getAlignment());
36259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    AllocaVec.push_back(&AI);
36359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t AlignedSize =  getAlignedAllocaSize(&AI);
36459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    TotalStackSize += AlignedSize;
36559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
36659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
36759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ---------------------- Helpers.
36859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void initializeCallbacks(Module &M);
36959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
37059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAllocaSizeInBytes(AllocaInst *AI) {
37159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Type *Ty = AI->getAllocatedType();
37259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
37359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return SizeInBytes;
37459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
37559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAlignedSize(uint64_t SizeInBytes) {
37659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    size_t RZ = RedzoneSize();
37759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return ((SizeInBytes + RZ - 1) / RZ) * RZ;
37859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
37959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t getAlignedAllocaSize(AllocaInst *AI) {
38059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
38159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return getAlignedSize(SizeInBytes);
38259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
38359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB,
38459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                      Value *ShadowBase, bool DoPoison);
38559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> IRB, bool DoPoison);
38659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// Analyze lifetime intrinsics for given alloca. Use Value* instead of
38759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// AllocaInst* here, as we call this method after we merge all allocas into a
38859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// single one. Returns true if ASan added some instrumentation.
38959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool handleAllocaLifetime(Value *Alloca);
39059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// Analyze lifetime intrinsics for a specific value, casted from alloca.
39159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// Returns true if if ASan added some instrumentation.
39259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool handleValueLifetime(Value *V);
39359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov};
39459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
395800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
396800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
397800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
398800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
399800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
400800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
401ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey SamsonovFunctionPass *llvm::createAddressSanitizerFunctionPass(
402b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov    bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
403b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov    StringRef BlacklistFile) {
404ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
405b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                              CheckLifetime, BlacklistFile);
406800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
407800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
4081416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanychar AddressSanitizerModule::ID = 0;
4091416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya SerebryanyINITIALIZE_PASS(AddressSanitizerModule, "asan-module",
4101416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
4111416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "ModulePass", false, false)
412b0dcf61252e58715a3bea79f4c112572df361c30Alexey SamsonovModulePass *llvm::createAddressSanitizerModulePass(
413b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov    bool CheckInitOrder, StringRef BlacklistFile) {
414b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  return new AddressSanitizerModule(CheckInitOrder, BlacklistFile);
41525878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
41625878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
4172735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
4182735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  size_t Res = CountTrailingZeros_32(TypeSize / 8);
4192735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
4202735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
4212735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
4222735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
423800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Create a constant for Str so that we can pass it to the run-time lib.
424800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
42518c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
426800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return new GlobalVariable(M, StrConst->getType(), true,
42751c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany                            GlobalValue::PrivateLinkage, StrConst,
42851c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany                            kAsanGenPrefix);
42951c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany}
43051c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany
43151c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryanystatic bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
43251c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  return G->getName().find(kAsanGenPrefix) == 0;
433800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
434800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
435800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
437b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Shadow = IRB.CreateLShr(Shadow, MappingScale());
438800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (MappingOffset == 0)
439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
441800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy,
442800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                               MappingOffset));
443800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
444800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
445c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
446ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    Instruction *OrigIns,
447800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
448800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
449800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
450800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
451ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentAddress(OrigIns, IRB, Addr, 8, IsWrite);
452800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
453800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
454800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  {
455800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
456800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *SizeMinusOne = IRB.CreateSub(
457800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Size, ConstantInt::get(Size->getType(), 1));
458800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    SizeMinusOne = IRB.CreateIntCast(SizeMinusOne, IntptrTy, false);
459800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
460800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *AddrPlusSizeMinisOne = IRB.CreateAdd(AddrLong, SizeMinusOne);
461ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentAddress(OrigIns, IRB, AddrPlusSizeMinisOne, 8, IsWrite);
462800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
463800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
464800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
465800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
466ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
467800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
468800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
4692735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
470800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
471800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
472800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
473800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
474800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
475800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
478800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
479800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
480800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
48156139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
4824a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
483800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
484800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
485ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
486800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
487ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
488800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
489800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
490800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
491e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
492e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
493e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
495e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
496e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
497800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
499e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
500e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
501e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
502e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
503e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
504e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
505e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
506e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
507e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
508e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
509e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
510e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
511e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
512e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
513e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
514e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
515800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
516800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
517ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentMop(Instruction *I) {
5183780ad8b998d93d7db406919c06137cdb786ef05Axel Naumann  bool IsWrite = false;
519e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
520e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
5219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClOpt && ClOptGlobals) {
5229b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
5239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If initialization order checking is disabled, a simple access to a
5249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // dynamically initialized global is always valid.
525ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      if (!CheckInitOrder)
5269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
5279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If a global variable does not have dynamic initialization we don't
528407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // have to instrument it.  However, if a global does not have initailizer
529407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // at all, we assume it has dynamic initializer (in other TU).
530407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
5319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
5329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
533800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
5349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
540800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
541800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (TypeSize != 8  && TypeSize != 16 &&
542800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      TypeSize != 32 && TypeSize != 64 && TypeSize != 128) {
543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Ignore all unusual sizes.
544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return;
545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
547800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
548ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentAddress(I, IRB, Addr, TypeSize, IsWrite);
549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
550800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
55155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
55255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
55355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
55455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
555b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryanystatic Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
55655cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
55755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
55855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
55955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
56055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
56155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
562800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
563ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
5644f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex) {
565ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
566ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  CallInst *Call = IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex],
567ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany                                  Addr);
568f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
569f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
570f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
571f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
5723c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
573800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
574800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5752735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
576c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
577c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
578b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  size_t Granularity = 1 << MappingScale();
579c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
580c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
581c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
582c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
583c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
584c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
585c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
586c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
587c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
5886e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany      LastAccessedByte, ShadowValue->getType(), false);
589c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
590c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
591c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
592c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
593ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
594800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         IRBuilder<> &IRB, Value *Addr,
595800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                         uint32_t TypeSize, bool IsWrite) {
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
597800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
599b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany      *C, std::max(8U, TypeSize >> MappingScale()));
600800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
601800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
602800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
603800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
604800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
605800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
606800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
60711c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
608b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  size_t Granularity = 1 << MappingScale();
609ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
610ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
6116e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
6124a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    TerminatorInst *CheckTerm =
6134a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
614ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
615f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
616c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
617c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
618ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    BasicBlock *CrashBlock =
619ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
620ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
621f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
622f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
623c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
6244a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
626ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
627ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *Crash =
628ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany      generateCrashCode(CrashTerm, AddrLong, IsWrite, AccessSizeIndex);
629ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
631800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6321416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyvoid AddressSanitizerModule::createInitializerPoisonCalls(
633b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Module &M, Value *FirstAddr, Value *LastAddr) {
6349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
6359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
6369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // If that function is not present, this TU contains no globals, or they have
6379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // all been optimized away
6389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!GlobalInit)
6399b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
6409b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6419b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Set up the arguments to our poison/unpoison functions.
6429b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
6439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6449b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add a call to poison all external globals before the given function starts.
6459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRB.CreateCall2(AsanPoisonGlobals, FirstAddr, LastAddr);
6469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add calls to unpoison all globals before each return instruction.
6489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
6499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      I != E; ++I) {
6509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
6519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      CallInst::Create(AsanUnpoisonGlobals, "", RI);
6529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
6539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
6549b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
6559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6561416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
6579b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Type *Ty = cast<PointerType>(G->getType())->getElementType();
658324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
6599b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
66059a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany  if (BL->isIn(*G)) return false;
6619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!Ty->isSized()) return false;
6629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!G->hasInitializer()) return false;
66351c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
6649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Touch only those globals that will not be defined in other modules.
6659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Don't handle ODR type linkages since other modules may be built w/o asan.
6669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
6679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::PrivateLinkage &&
6689b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::InternalLinkage)
6699b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
6709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Two problems with thread-locals:
6719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - The address of the main thread's copy can't be computed at link-time.
6729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - Need to poison all copies, not just the main thread's one.
6739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->isThreadLocal())
6749b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
6759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // For now, just ignore this Alloca if the alignment is large.
676b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  if (G->getAlignment() > RedzoneSize()) return false;
6779b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Ignore all the globals with the names starting with "\01L_OBJC_".
6799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Many of those are put into the .cstring section. The linker compresses
6809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // that section by removing the spare \0s after the string terminator, so
6819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // our redzones get broken.
6829b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if ((G->getName().find("\01L_OBJC_") == 0) ||
6839b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      (G->getName().find("\01l_OBJC_") == 0)) {
6849b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
6859b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
6869b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
6879b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
6889b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->hasSection()) {
6899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    StringRef Section(G->getSection());
6909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
6919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
6929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // them.
6939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if ((Section.find("__OBJC,") == 0) ||
6949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        (Section.find("__DATA, __objc_") == 0)) {
6959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
6969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
6979b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
6989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
6999b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Constant CFString instances are compiled in the following way:
7009b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the string buffer is emitted into
7019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     __TEXT,__cstring,cstring_literals
7029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the constant NSConstantString structure referencing that buffer
7039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     is placed into __DATA,__cfstring
7049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Therefore there's no point in placing redzones into __DATA,__cfstring.
7059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Moreover, it causes the linker to crash on OS X 10.7
7069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (Section.find("__DATA,__cfstring") == 0) {
7079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring CFString: " << *G);
7089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
7099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
7109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
7119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return true;
7139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
7149b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7154684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonovvoid AddressSanitizerModule::initializeCallbacks(Module &M) {
7164684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  IRBuilder<> IRB(*C);
7174684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare our poisoning and unpoisoning functions.
7184684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
7194684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
7204684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
7214684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
7224684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
7234684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
7244684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare functions that register/unregister globals.
7254684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
7264684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanRegisterGlobalsName, IRB.getVoidTy(),
7274684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IntptrTy, IntptrTy, NULL));
7284684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
7294684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
7304684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnregisterGlobalsName,
7314684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
7324684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
7334684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov}
7344684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
735800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
736800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
737800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
7381416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::runOnModule(Module &M) {
7391416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!ClGlobals) return false;
7401416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
7411416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!TD)
7421416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return false;
743b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  BL.reset(new BlackList(BlacklistFile));
744d6f62c8da5aa4f3388cec1542309ffa623cac601Alexey Samsonov  if (BL->isIn(M)) return false;
745b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  C = &(M.getContext());
746b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  IntptrTy = Type::getIntNTy(*C, TD->getPointerSizeInBits());
7474684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  initializeCallbacks(M);
7484684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  DynamicallyInitializedGlobals.Init(M);
749b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
750800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
751800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Module::GlobalListType::iterator G = M.global_begin(),
7539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       E = M.global_end(); G != E; ++G) {
7549b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ShouldInstrumentGlobal(G))
7559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      GlobalsToChange.push_back(G);
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
761800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
762800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
763800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
764800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
765800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
7669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   size_t has_dynamic_init;
767800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
768800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
7699b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, IntptrTy,
7709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, NULL);
7719b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  SmallVector<Constant *, 16> Initializers(n), DynamicInit;
772800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
773b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
774b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
775b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  assert(CtorFunc);
776b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
777800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7789b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // The addresses of the first and last dynamically initialized globals in
7799b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // this TU.  Used in initialization order checking.
7809b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Value *FirstDynamic = 0, *LastDynamic = 0;
7819b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
782800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
783800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
784800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
785800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
786208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
787b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    size_t RZ = RedzoneSize();
788b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    uint64_t RightRedzoneSize = RZ + (RZ - (SizeInBytes % RZ));
789800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
7909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Determine whether this global should be poisoned in initialization.
791ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    bool GlobalHasDynamicInitializer =
792ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        DynamicallyInitializedGlobals.Contains(G);
79359a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany    // Don't check initialization order if this global is blacklisted.
7947dadac65d375ff21b7a36bfb7642578d2f467525Kostya Serebryany    GlobalHasDynamicInitializer &= !BL->isInInit(*G);
795800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
796800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
797800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
798800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
799800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
800800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
801a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    SmallString<2048> DescriptionOfGlobal = G->getName();
802a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += " (";
803a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += M.getModuleIdentifier();
804a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    DescriptionOfGlobal += ")";
805a4b2b1d8fbb84b0b6fac5abce21a2a5c5e907282Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, DescriptionOfGlobal);
806800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
807800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
808800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
809800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        M, NewTy, G->isConstant(), G->getLinkage(),
810ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
811800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
812b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    NewGlobal->setAlignment(RZ);
813800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
814800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
815800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
816800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
817800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
818800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
819f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
820800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
821800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
822800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
823800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
824800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
825800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
826800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
827800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
828800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
8299b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
830800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
8319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8329b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Populate the first and last globals declared in this TU.
833ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov    if (CheckInitOrder && GlobalHasDynamicInitializer) {
8349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      LastDynamic = ConstantExpr::getPointerCast(NewGlobal, IntptrTy);
8359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      if (FirstDynamic == 0)
8369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        FirstDynamic = LastDynamic;
8379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
839324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
840800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
841800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
842800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
843800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
844800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      M, ArrayOfGlobalStructTy, false, GlobalVariable::PrivateLinkage,
845800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
846800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Create calls for poisoning before initializers run and unpoisoning after.
848ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  if (CheckInitOrder && FirstDynamic && LastDynamic)
8499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    createInitializerPoisonCalls(M, FirstDynamic, LastDynamic);
850800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
851800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
852800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
853800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8547bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
8557bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
8567bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
8577bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
8587bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
8597bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
8607bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
8617bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
8627bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
8637bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
8647bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
8657bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
866800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
867800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
868800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
869800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
8708b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanyvoid AddressSanitizer::initializeCallbacks(Module &M) {
8718b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(*C);
8729db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
8739db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
8749db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
8759db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
8769db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
8779db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
8789db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
8794f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
8807846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
8817846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany          checkInterfaceFunction(M.getOrInsertFunction(
8827846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
8839db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
8849db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
885ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
886ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
887ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
888f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
889f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
890f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
891f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
8928b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany}
8938b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
8948b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany// virtual
8958b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanybool AddressSanitizer::doInitialization(Module &M) {
8968b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // Initialize the private fields. No one has accessed them before.
8978b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
8988b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
8998b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  if (!TD)
9008b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany    return false;
901b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  BL.reset(new BlackList(BlacklistFile));
9028b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  DynamicallyInitializedGlobals.Init(M);
9038b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
9048b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  C = &(M.getContext());
9058b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  LongSize = TD->getPointerSizeInBits();
9068b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
9078b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
9088b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanCtorFunction = Function::Create(
9098b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
9108b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
9118b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
9128b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // call __asan_init in the module ctor.
9138b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
9148b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction = checkInterfaceFunction(
9158b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
9168b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
9178b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRB.CreateCall(AsanInitFunction);
9189db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
91906fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  llvm::Triple targetTriple(M.getTargetTriple());
92043bf70986bb13c812e87ca959dd8f2dd9edf802cLogan Chien  bool isAndroid = targetTriple.getEnvironment() == llvm::Triple::Android;
92106fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov
92206fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov  MappingOffset = isAndroid ? kDefaultShadowOffsetAndroid :
92306fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov    (LongSize == 32 ? kDefaultShadowOffset32 : kDefaultShadowOffset64);
924800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ClMappingOffsetLog >= 0) {
925800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClMappingOffsetLog == 0) {
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // special case
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 0;
928800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
929800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      MappingOffset = 1ULL << ClMappingOffsetLog;
930800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
931800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
932800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
933800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9348c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingOffsetLog >= 0) {
9358c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Tell the run-time the current values of mapping offset and scale.
9368c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_offset =
9378c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
9388c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       ConstantInt::get(IntptrTy, MappingOffset),
9398c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                       kAsanMappingOffsetName);
9408c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
9418c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_offset, true);
9428c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
9438c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  if (ClMappingScale) {
9448c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    GlobalValue *asan_mapping_scale =
9458c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany        new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
946b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                           ConstantInt::get(IntptrTy, MappingScale()),
9478c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany                           kAsanMappingScaleName);
9488c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    // Read the global, otherwise it may be optimized away.
9498c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany    IRB.CreateLoad(asan_mapping_scale, true);
9508c0134a77615b66f57250f0662bc899e4574551eKostya Serebryany  }
951800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9527bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
9539b02741d2284d9516a59666c211fe1f57e8803adKostya Serebryany
954ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  return true;
955ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany}
956ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
957a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
958a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
959a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
960a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
961a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
962a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
963a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
964a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
965a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
966a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
967a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
968a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
969a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
970a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
971a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
972a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
973ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::runOnFunction(Function &F) {
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
976324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
9778b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  initializeCallbacks(*F.getParent());
978a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
979a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // If needed, insert __asan_init before checking for AddressSafety attr.
980a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
981a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
982034b94b17006f51722886b0f2283fb6fb19aca1fBill Wendling  if (!F.getFnAttributes().hasAttribute(Attribute::AddressSafety))
9836765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling    return false;
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
9876765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling
9886765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // We want to instrument every address only once per basic block (unless there
9896765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // are calls between uses).
990800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
99295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
993e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
999324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
1000800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1001800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
1002bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
1003e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1004800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
1005800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
1006800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
1007800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1008800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
101195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany        if (CallInst *CI = dyn_cast<CallInst>(BI)) {
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
1013800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
1014a17babb021aa9dc3441ecce1ac8a62d2b27edecbKostya Serebryany          if (CI->doesNotReturn()) {
101595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany            NoReturnCalls.push_back(CI);
101695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany          }
1017800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1018800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
1021324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
1022324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1023324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
1024800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1025800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1026800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1027800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
1028800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
1029800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1030800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
1031800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
1032800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1033e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
1034ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMop(Inst);
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
1036ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
1039800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1040800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
104159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner FSP(F, *this);
104259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool ChangedStack = FSP.runOnFunction();
104395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
104495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
104595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
104695e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
104795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
104895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
1049ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    IRB.CreateCall(AsanHandleNoReturnFunc);
105095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
1051324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN done instrumenting:\n" << F << "\n");
105295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
105395e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  return NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
1054800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1055800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1056800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1057800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
1058800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1059800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
1060800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
1061800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
1062858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1063800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1064800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1065800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1066800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
1067b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                            size_t RZSize,
1068800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
1069800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
1070b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  for (size_t i = 0; i < RZSize;
1071800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
1072800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
1073800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
1074800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
1075800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
1076800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
1077800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
1078800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1079800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1080800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1081800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
108259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Workaround for bug 11395: we don't want to instrument stack in functions
108359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
108459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// FIXME: remove once the bug 11395 is fixed.
108559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovbool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
108659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (LongSize != 32) return false;
108759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  CallInst *CI = dyn_cast<CallInst>(I);
108859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (!CI || !CI->isInlineAsm()) return false;
108959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (CI->getNumArgOperands() <= 5) return false;
109059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // We have inline assembly with quite a few arguments.
109159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return true;
109259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
109359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
109459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::initializeCallbacks(Module &M) {
109559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  IRBuilder<> IRB(*C);
109659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanStackMallocFunc = checkInterfaceFunction(M.getOrInsertFunction(
109759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanStackMallocName, IntptrTy, IntptrTy, IntptrTy, NULL));
109859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanStackFreeFunc = checkInterfaceFunction(M.getOrInsertFunction(
109959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanStackFreeName, IRB.getVoidTy(),
110059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      IntptrTy, IntptrTy, IntptrTy, NULL));
110159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
110259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
110359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
110459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
110559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
110659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
110759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonRedZones(
110859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> IRB, Value *ShadowBase,
110959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoPoison) {
1110b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  size_t ShadowRZSize = RedzoneSize() >> MappingScale();
1111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1113800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
1114800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1115800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
1116800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1117800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
1118800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1119800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
1120800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1121800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1122800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
1123800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1124800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1125800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
1126b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1131b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize());
1132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
1133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
1135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1136800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
1137800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
1138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
1139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
1140800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
1141b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                       (Pos >> MappingScale()) - ShadowRZSize));
1142b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany      size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1143800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
1144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
1145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1146b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                        RedzoneSize(),
1147b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                        1ULL << MappingScale(),
1148800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
1149800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1152800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1153800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1154800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
1155800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
1156b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                        ConstantInt::get(IntptrTy, Pos >> MappingScale()));
1157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Poison = i == AllocaVec.size() - 1 ? PoisonRight : PoisonMid;
1158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1160b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += RedzoneSize();
1161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
116459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonStack() {
1165f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  bool HavePoisonedAllocas = false;
116659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t LocalStackSize = TotalStackSize +
116759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                            (AllocaVec.size() + 1) * RedzoneSize();
1168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
116959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoStackMalloc = ASan.CheckUseAfterReturn
1170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
1171800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1172800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
1173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
1174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
1178800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
117959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (ClRealignStack && StackAlignment < RedzoneSize())
118059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = RedzoneSize();
118159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  MyAlloca->setAlignment(StackAlignment);
1182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
1183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
1185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    LocalStackBase = IRB.CreateCall2(AsanStackMallocFunc,
1188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // This string will be parsed by the run-time (DescribeStackAddress).
1192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
1193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
1194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StackDescription << F.getName() << " " << AllocaVec.size() << " ";
1195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1196b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1197800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1198800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1199800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1200800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1201800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1205b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert((AlignedSize % RedzoneSize()) == 0);
1206f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    Value *NewAllocaPtr = IRB.CreateIntToPtr(
1207800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1208f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov            AI->getType());
12091afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1210f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    AI->replaceAllUsesWith(NewAllocaPtr);
1211f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    // Analyze lifetime intrinsics only for static allocas we handle.
121259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (ASan.CheckLifetime)
1213f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      HavePoisonedAllocas |= handleAllocaLifetime(NewAllocaPtr);
1214b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += AlignedSize + RedzoneSize();
1215800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1216800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1217800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1218800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Write the Magic value and the frame description constant to the redzone.
1219800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1220800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1221800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
1222800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus1 = IRB.CreateAdd(LocalStackBase,
122359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                   ConstantInt::get(IntptrTy,
122459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                                    ASan.LongSize/8));
1225800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  BasePlus1 = IRB.CreateIntToPtr(BasePlus1, IntptrPtrTy);
12269ce84c1c95c0153a2f33e188ce0db00770425f9eAlexey Samsonov  GlobalVariable *StackDescriptionGlobal =
1227a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
122859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
122959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                             IntptrTy);
1230800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
1231800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1232800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
123359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
123459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1235800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1236800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1237800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1238800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1239800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1240800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1241800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1242800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1243800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
124459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1246f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // In use-after-return mode, mark the whole stack frame unaddressable.
1247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRBRet.CreateCall3(AsanStackFreeFunc, LocalStackBase,
1248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         ConstantInt::get(IntptrTy, LocalStackSize),
1249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                         OrigStackBase);
1250f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    } else if (HavePoisonedAllocas) {
1251f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // If we poisoned some allocas in llvm.lifetime analysis,
1252f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // unpoison whole stack frame now.
1253f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      assert(LocalStackBase == OrigStackBase);
1254f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1255800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1257800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1258bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  // We are done. Remove the old unused alloca instructions.
1259bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1260bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany    AllocaVec[i]->eraseFromParent();
1261800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1262f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
126359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
126459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                         IRBuilder<> IRB, bool DoPoison) {
1265f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  // For now just insert the call to ASan runtime.
1266f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1267f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1268f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1269f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                           : AsanUnpoisonStackMemoryFunc,
1270f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                  AddrArg, SizeArg);
1271f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov}
127259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
127359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Handling llvm.lifetime intrinsics for a given %alloca:
127459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
127559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
127659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
127759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     could be poisoned by previous llvm.lifetime.end instruction, as the
127859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     variable may go in and out of scope several times, e.g. in loops).
127959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (3) if we poisoned at least one %alloca in a function,
128059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     unpoison the whole stack frame at function exit.
128159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovbool FunctionStackPoisoner::handleAllocaLifetime(Value *Alloca) {
128259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  assert(ASan.CheckLifetime);
128359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *AllocaType = Alloca->getType();
128459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *Int8PtrTy = Type::getInt8PtrTy(AllocaType->getContext());
128559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
128659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool Res = false;
128759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Typical code looks like this:
128859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // %alloca = alloca <type>, <alignment>
128959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ... some code ...
129059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // %val1 = bitcast <type>* %alloca to i8*
129159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // call void @llvm.lifetime.start(i64 <size>, i8* %val1)
129259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ... more code ...
129359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // %val2 = bitcast <type>* %alloca to i8*
129459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // call void @llvm.lifetime.start(i64 <size>, i8* %val2)
129559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // That is, to handle %alloca we must find all its casts to
129659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // i8* values, and find lifetime instructions for these values.
129759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (AllocaType == Int8PtrTy)
129859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Res |= handleValueLifetime(Alloca);
129959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  for (Value::use_iterator UI = Alloca->use_begin(), UE = Alloca->use_end();
130059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov       UI != UE; ++UI) {
130159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (UI->getType() != Int8PtrTy) continue;
130259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (UI->stripPointerCasts() != Alloca) continue;
130359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Res |= handleValueLifetime(*UI);
130459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
130559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return Res;
130659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
130759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
130859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovbool FunctionStackPoisoner::handleValueLifetime(Value *V) {
130959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  assert(ASan.CheckLifetime);
131059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool Res = false;
131159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
131259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov       ++UI) {
131359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI);
131459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!II) continue;
131559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Intrinsic::ID ID = II->getIntrinsicID();
131659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (ID != Intrinsic::lifetime_start &&
131759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        ID != Intrinsic::lifetime_end)
131859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      continue;
131959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (V != II->getArgOperand(1))
132059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      continue;
132159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // Found lifetime intrinsic, add ASan instrumentation if necessary.
132259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    ConstantInt *Size = dyn_cast<ConstantInt>(II->getArgOperand(0));
132359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // If size argument is undefined, don't do anything.
132459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (Size->isMinusOne())
132559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      continue;
132659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // Check that size doesn't saturate uint64_t and can
132759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // be stored in IntptrTy.
132859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    const uint64_t SizeValue = Size->getValue().getLimitedValue();
132959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (SizeValue == ~0ULL ||
133059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        !ConstantInt::isValueValidForType(IntptrTy, SizeValue)) {
133159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      continue;
133259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
133359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    IRBuilder<> IRB(II);
133459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    bool DoPoison = (ID == Intrinsic::lifetime_end);
133559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonAlloca(V, SizeValue, IRB, DoPoison);
133659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Res = true;
133759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
133859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return Res;
133959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
1340