AddressSanitizer.cpp revision 8819c84aed10777ba91d4e862229882b8da0b272
1800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
3800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//                     The LLVM Compiler Infrastructure
4800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
5800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is distributed under the University of Illinois Open Source
6800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// License. See LICENSE.TXT for details.
7800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
8800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
9800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
10800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This file is a part of AddressSanitizer, an address sanity checker.
11800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Details of the algorithm:
12800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//
14800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//===----------------------------------------------------------------------===//
15800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
16800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#define DEBUG_TYPE "asan"
17800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
18d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include "llvm/Transforms/Instrumentation.h"
19800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/ArrayRef.h"
201c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov#include "llvm/ADT/DenseMap.h"
2159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov#include "llvm/ADT/DepthFirstIterator.h"
22800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/OwningPtr.h"
23800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallSet.h"
24800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallString.h"
25800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/SmallVector.h"
26800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/ADT/StringExtras.h"
2706fdbaa9145f01a291d4981ca5120b7bdcad44c6Evgeniy Stepanov#include "llvm/ADT/Triple.h"
281afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/DIBuilder.h"
290b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/DataLayout.h"
300b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Function.h"
310b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IRBuilder.h"
320b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/InlineAsm.h"
330b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/IntrinsicInst.h"
340b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/LLVMContext.h"
350b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Module.h"
360b8c9a80f20772c3793201ab5b251d3520b9cea3Chandler Carruth#include "llvm/IR/Type.h"
3759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov#include "llvm/InstVisitor.h"
381479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany#include "llvm/Support/CallSite.h"
39800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/CommandLine.h"
40800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/DataTypes.h"
41800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/Debug.h"
423e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany#include "llvm/Support/Endian.h"
43800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/raw_ostream.h"
44800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Support/system_error.h"
45800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/BasicBlockUtils.h"
4620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany#include "llvm/Transforms/Utils/Cloning.h"
471afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov#include "llvm/Transforms/Utils/Local.h"
48800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include "llvm/Transforms/Utils/ModuleUtils.h"
49405515d55f470d04ef75f653b7f1994329c9066bPeter Collingbourne#include "llvm/Transforms/Utils/SpecialCaseList.h"
50800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany#include <algorithm>
51d04a8d4b33ff316ca4cf961e06c9e312eff8e64fChandler Carruth#include <string>
52800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
53800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanyusing namespace llvm;
54800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
55800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowScale = 3;
56800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
57800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
58117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryanystatic const uint64_t kDefaultShort64bitShadowOffset = 0x7FFF8000;  // < 2G.
5948a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryanystatic const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
603e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryanystatic const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa8000;
61800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
62f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryanystatic const size_t kMinStackMallocSize = 1 << 6;  // 64B
63800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const size_t kMaxStackMallocSize = 1 << 16;  // 64K
64800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
65800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
66800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
674172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanModuleCtorName = "asan.module_ctor";
684172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanModuleDtorName = "asan.module_dtor";
694172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const int         kAsanCtorAndCtorPriority = 1;
704172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanReportErrorTemplate = "__asan_report_";
714172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanReportLoadN = "__asan_report_load_n";
724172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanReportStoreN = "__asan_report_store_n";
734172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
7448d7d1d231cde758599fa0a010c29a174907c12fAlexey Samsonovstatic const char *const kAsanUnregisterGlobalsName =
7548d7d1d231cde758599fa0a010c29a174907c12fAlexey Samsonov    "__asan_unregister_globals";
764172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
774172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
784172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanInitName = "__asan_init_v3";
794172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
804172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanMappingOffsetName = "__asan_mapping_offset";
814172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanMappingScaleName = "__asan_mapping_scale";
82f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryanystatic const int         kMaxAsanStackMallocSizeClass = 10;
83f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryanystatic const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
84f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryanystatic const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
854172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanGenPrefix = "__asan_gen_";
864172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanPoisonStackMemoryName =
874172a8abbabea2359d91bb07101166565127d798Craig Topper    "__asan_poison_stack_memory";
884172a8abbabea2359d91bb07101166565127d798Craig Topperstatic const char *const kAsanUnpoisonStackMemoryName =
89f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    "__asan_unpoison_stack_memory";
90800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
91ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryanystatic const char *const kAsanOptionDetectUAR =
92ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    "__asan_option_detect_stack_use_after_return";
93ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany
94671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// These constants must match the definitions in the run-time library.
95800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackLeftRedzoneMagic = 0xf1;
96800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackMidRedzoneMagic = 0xf2;
97800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackRightRedzoneMagic = 0xf3;
98800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic const int kAsanStackPartialRedzoneMagic = 0xf4;
990b956507cab3dc4b06b310d2674bb35c79f46dc0David Blaikie#ifndef NDEBUG
100671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryanystatic const int kAsanStackAfterReturnMagic = 0xf5;
1010b956507cab3dc4b06b310d2674bb35c79f46dc0David Blaikie#endif
102800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
103c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// Accesses sizes are powers of two: 1, 2, 4, 8, 16.
104c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanystatic const size_t kNumberOfAccessSizes = 5;
105c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
106800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Command-line flags.
107800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
108800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no-]asan-reads.
109800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
110800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument read instructions"), cl::Hidden, cl::init(true));
111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClInstrumentWrites("asan-instrument-writes",
112800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("instrument write instructions"), cl::Hidden, cl::init(true));
113e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic cl::opt<bool> ClInstrumentAtomics("asan-instrument-atomics",
114e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::desc("instrument atomic instructions (rmw, cmpxchg)"),
115e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany       cl::Hidden, cl::init(true));
1166e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryanystatic cl::opt<bool> ClAlwaysSlowPath("asan-always-slow-path",
1176e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::desc("use instrumentation with slow path for all accesses"),
1186e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany       cl::Hidden, cl::init(false));
119c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany// This flag limits the number of instructions to be instrumented
120324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// in any given BB. Normally, this should be set to unlimited (INT_MAX),
121324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
122324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany// set it to 10000.
123324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryanystatic cl::opt<int> ClMaxInsnsToInstrumentPerBB("asan-max-ins-per-bb",
124324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::init(10000),
125324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::desc("maximal number of instructions to instrument in any given BB"),
126324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany       cl::Hidden);
127800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-stack.
128800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClStack("asan-stack",
129800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle stack memory"), cl::Hidden, cl::init(true));
130800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-use-after-return.
131800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
132800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Check return-after-free"), cl::Hidden, cl::init(false));
133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This flag may need to be replaced with -f[no]asan-globals.
134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClGlobals("asan-globals",
135800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle global objects"), cl::Hidden, cl::init(true));
1369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryanystatic cl::opt<bool> ClInitializers("asan-initialization-order",
1379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       cl::desc("Handle C++ initializer order"), cl::Hidden, cl::init(false));
138800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClMemIntrin("asan-memintrin",
139800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Handle memset/memcpy/memmove"), cl::Hidden, cl::init(true));
1406c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryanystatic cl::opt<bool> ClRealignStack("asan-realign-stack",
1416c55412ea4b39103a3a5764d49ddfdf50e066d56Kostya Serebryany       cl::desc("Realign stack to 32"), cl::Hidden, cl::init(true));
142b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonovstatic cl::opt<std::string> ClBlacklistFile("asan-blacklist",
143b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov       cl::desc("File containing the list of objects to ignore "
144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                "during instrumentation"), cl::Hidden);
145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
14620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// This is an experimental feature that will allow to choose between
14720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// instrumented and non-instrumented code at link-time.
14820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// If this option is on, just before instrumenting a function we create its
14920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// clone; if the function is not changed by asan the clone is deleted.
15020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// If we end up with a clone, we put the instrumented function into a section
15120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// called "ASAN" and the uninstrumented function into a section called "NOASAN".
15220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany//
15320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// This is still a prototype, we need to figure out a way to keep two copies of
15420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany// a function so that the linker can easily choose one of them.
15520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryanystatic cl::opt<bool> ClKeepUninstrumented("asan-keep-uninstrumented-functions",
15620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany       cl::desc("Keep uninstrumented copies of functions"),
15720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany       cl::Hidden, cl::init(false));
15820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// These flags allow to change the shadow mapping.
160800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// The shadow mapping looks like
161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany//    Shadow = (Mem >> scale) + (1 << offset_log)
162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingScale("asan-mapping-scale",
163800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("scale of asan shadow mapping"), cl::Hidden, cl::init(0));
164800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClMappingOffsetLog("asan-mapping-offset-log",
165800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("offset of asan shadow mapping"), cl::Hidden, cl::init(-1));
166117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryanystatic cl::opt<bool> ClShort64BitOffset("asan-short-64bit-mapping-offset",
167117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany       cl::desc("Use short immediate constant as the mapping offset for 64bit"),
1680bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany       cl::Hidden, cl::init(true));
169800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Optimization flags. Not user visible, used mostly for testing
171800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// and benchmarking the tool.
172800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOpt("asan-opt",
173800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Optimize instrumentation"), cl::Hidden, cl::init(true));
174800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptSameTemp("asan-opt-same-temp",
175800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Instrument the same temp just once"), cl::Hidden,
176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::init(true));
177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<bool> ClOptGlobals("asan-opt-globals",
178800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       cl::desc("Don't instrument scalar globals"), cl::Hidden, cl::init(true));
179800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
180ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonovstatic cl::opt<bool> ClCheckLifetime("asan-check-lifetime",
181ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::desc("Use llvm.lifetime intrinsics to insert extra checks"),
182ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov       cl::Hidden, cl::init(false));
183ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov
184800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Debug flags.
185800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
186800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                            cl::init(0));
187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                 cl::Hidden, cl::init(0));
189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<std::string> ClDebugFunc("asan-debug-func",
190800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        cl::Hidden, cl::desc("Debug func"));
191800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
192800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
193800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug man inst"),
194800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                               cl::Hidden, cl::init(-1));
195800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
196800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanynamespace {
197ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany/// A set of dynamically initialized globals extracted from metadata.
198ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryanyclass SetOfDynamicallyInitializedGlobals {
199ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany public:
200ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  void Init(Module& M) {
201ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    // Clang generates metadata identifying all dynamically initialized globals.
202ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    NamedMDNode *DynamicGlobals =
203ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        M.getNamedMetadata("llvm.asan.dynamically_initialized_globals");
204ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    if (!DynamicGlobals)
205ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      return;
206ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    for (int i = 0, n = DynamicGlobals->getNumOperands(); i < n; ++i) {
207ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      MDNode *MDN = DynamicGlobals->getOperand(i);
208ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      assert(MDN->getNumOperands() == 1);
209ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      Value *VG = MDN->getOperand(0);
210ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // The optimizer may optimize away a global entirely, in which case we
211ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      // cannot instrument access to it.
212ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      if (!VG)
213ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        continue;
214ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany      DynInitGlobals.insert(cast<GlobalVariable>(VG));
215ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    }
216ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  }
217ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  bool Contains(GlobalVariable *G) { return DynInitGlobals.count(G) != 0; }
218ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany private:
219ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SmallSet<GlobalValue*, 32> DynInitGlobals;
220ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany};
221ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
22219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov/// This struct defines the shadow mapping using the rule:
22348a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany///   shadow = (mem >> Scale) ADD-or-OR Offset.
22419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovstruct ShadowMapping {
22519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  int Scale;
22619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  uint64_t Offset;
22748a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  bool OrShadowOffset;
22819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov};
22919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
23011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonovstatic ShadowMapping getShadowMapping(const Module &M, int LongSize,
23111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                      bool ZeroBaseShadow) {
23211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  llvm::Triple TargetTriple(M.getTargetTriple());
23311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool IsAndroid = TargetTriple.getEnvironment() == llvm::Triple::Android;
234c8a196ae8fad3cba7a777e2e7916fd36ebf70fe6Alexander Potapenko  bool IsMacOSX = TargetTriple.getOS() == llvm::Triple::MacOSX;
235f38cc38fa647d4e72c053c39bbe0cdec1342535fBill Schmidt  bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
236f38cc38fa647d4e72c053c39bbe0cdec1342535fBill Schmidt                 TargetTriple.getArch() == llvm::Triple::ppc64le;
2370bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany  bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
2383e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany  bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
2393e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                  TargetTriple.getArch() == llvm::Triple::mipsel;
24019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
24119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
24219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
24348a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // OR-ing shadow offset if more efficient (at least on x86),
24448a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // but on ppc64 we have to use add since the shadow offset is not neccesary
24548a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  // 1/8-th of the address space.
246117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany  Mapping.OrShadowOffset = !IsPPC64 && !ClShort64BitOffset;
24748a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany
24811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping.Offset = (IsAndroid || ZeroBaseShadow) ? 0 :
2493e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany      (LongSize == 32 ?
2503e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany       (IsMIPS32 ? kMIPS32_ShadowOffset32 : kDefaultShadowOffset32) :
25148a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany       IsPPC64 ? kPPC64_ShadowOffset64 : kDefaultShadowOffset64);
252c8a196ae8fad3cba7a777e2e7916fd36ebf70fe6Alexander Potapenko  if (!ZeroBaseShadow && ClShort64BitOffset && IsX86_64 && !IsMacOSX) {
2530bc55d517e8e64f0f441736fba2447781c405ef4Kostya Serebryany    assert(LongSize == 64);
254117de489a0d5f4ff280fb173fe45bd5ce8514d93Kostya Serebryany    Mapping.Offset = kDefaultShort64bitShadowOffset;
25539f02940ba085af79011f7e9095bf9902cd0fa6fKostya Serebryany  }
25639f02940ba085af79011f7e9095bf9902cd0fa6fKostya Serebryany  if (!ZeroBaseShadow && ClMappingOffsetLog >= 0) {
25719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    // Zero offset log is the special case.
25819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    Mapping.Offset = (ClMappingOffsetLog == 0) ? 0 : 1ULL << ClMappingOffsetLog;
25919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
26019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
26119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  Mapping.Scale = kDefaultShadowScale;
26219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  if (ClMappingScale) {
26319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    Mapping.Scale = ClMappingScale;
26419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
26519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
26619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  return Mapping;
267b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
268b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
26919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovstatic size_t RedzoneSizeForScale(int MappingScale) {
270b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // Redzone used for stack and globals is at least 32 bytes.
271b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
27219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  return std::max(32U, 1U << MappingScale);
273b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany}
274ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany
275800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany/// AddressSanitizer: instrument the code in module to find memory bugs.
276ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanystruct AddressSanitizer : public FunctionPass {
277b4ba5e68e1ac00bfb93572a1f271673deefd7ea9Alexey Samsonov  AddressSanitizer(bool CheckInitOrder = true,
278ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov                   bool CheckUseAfterReturn = false,
279b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov                   bool CheckLifetime = false,
28011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                   StringRef BlacklistFile = StringRef(),
28111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                   bool ZeroBaseShadow = false)
282ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : FunctionPass(ID),
283ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
284ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov        CheckUseAfterReturn(CheckUseAfterReturn || ClUseAfterReturn),
285b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckLifetime(CheckLifetime || ClCheckLifetime),
286b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
28711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                            : BlacklistFile),
28811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov        ZeroBaseShadow(ZeroBaseShadow) {}
2891416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
2901416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerFunctionPass";
2911416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
292ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMop(Instruction *I);
2936ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
2946ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                         Value *Addr, uint32_t TypeSize, bool IsWrite,
2956ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                         Value *SizeArgument);
296c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
297c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                           Value *ShadowValue, uint32_t TypeSize);
298ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
2996ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                 bool IsWrite, size_t AccessSizeIndex,
3006ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                 Value *SizeArgument);
301ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool instrumentMemIntrinsic(MemIntrinsic *MI);
302ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  void instrumentMemIntrinsicParam(Instruction *OrigIns, Value *Addr,
303c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                   Value *Size,
304800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                   Instruction *InsertBefore, bool IsWrite);
305800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
306ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  bool runOnFunction(Function &F);
307a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  bool maybeInsertAsanInitAtFunctionEntry(Function &F);
30819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  void emitShadowMapping(Module &M, IRBuilder<> &IRB) const;
309ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  virtual bool doInitialization(Module &M);
310800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  static char ID;  // Pass identification, replacement for typeid
311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany private:
3138b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  void initializeCallbacks(Module &M);
314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
3159b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
3165a3a9c937198084498a196dae856ac5a5a005bccKostya Serebryany  bool LooksLikeCodeInBug11395(Instruction *I);
3179b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  void FindDynamicInitializers(Module &M);
318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
319ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
320ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckUseAfterReturn;
321ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckLifetime;
32211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  SmallString<64> BlacklistFile;
32311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool ZeroBaseShadow;
32411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
325800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  LLVMContext *C;
3263574eca1b02600bac4e625297f4ecf745f4c4f32Micah Villmow  DataLayout *TD;
327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int LongSize;
328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *IntptrTy;
32919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanCtorFunction;
331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Function *AsanInitFunction;
332ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  Function *AsanHandleNoReturnFunc;
333405515d55f470d04ef75f653b7f1994329c9066bPeter Collingbourne  OwningPtr<SpecialCaseList> BL;
3349db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // This array is indexed by AccessIsWrite and log2(AccessSize).
3359db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  Function *AsanErrorCallback[2][kNumberOfAccessSizes];
3366ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // This array is indexed by AccessIsWrite.
3376ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Function *AsanErrorCallbackSized[2];
338f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  InlineAsm *EmptyAsm;
339ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
34059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
34159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  friend struct FunctionStackPoisoner;
342800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany};
343c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
3441416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyclass AddressSanitizerModule : public ModulePass {
345b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany public:
346b4ba5e68e1ac00bfb93572a1f271673deefd7ea9Alexey Samsonov  AddressSanitizerModule(bool CheckInitOrder = true,
34711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         StringRef BlacklistFile = StringRef(),
34811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         bool ZeroBaseShadow = false)
349ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      : ModulePass(ID),
350b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        CheckInitOrder(CheckInitOrder || ClInitializers),
351b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov        BlacklistFile(BlacklistFile.empty() ? ClBlacklistFile
35211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                            : BlacklistFile),
35311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov        ZeroBaseShadow(ZeroBaseShadow) {}
3541416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  bool runOnModule(Module &M);
3551416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  static char ID;  // Pass identification, replacement for typeid
3561416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  virtual const char *getPassName() const {
3571416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return "AddressSanitizerModule";
3581416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  }
359f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
360b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany private:
3614684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  void initializeCallbacks(Module &M);
3624684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
363b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  bool ShouldInstrumentGlobal(GlobalVariable *G);
364ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
36519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t RedzoneSize() const {
36619cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    return RedzoneSizeForScale(Mapping.Scale);
36719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
368b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
369ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  bool CheckInitOrder;
370b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov  SmallString<64> BlacklistFile;
37111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  bool ZeroBaseShadow;
37211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
373405515d55f470d04ef75f653b7f1994329c9066bPeter Collingbourne  OwningPtr<SpecialCaseList> BL;
374b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  SetOfDynamicallyInitializedGlobals DynamicallyInitializedGlobals;
375b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Type *IntptrTy;
376b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  LLVMContext *C;
3771416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  DataLayout *TD;
37819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
3794684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanPoisonGlobals;
3804684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnpoisonGlobals;
3814684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanRegisterGlobals;
3824684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  Function *AsanUnregisterGlobals;
383b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany};
384b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
38559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Stack poisoning does not play well with exception handling.
38659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// When an exception is thrown, we essentially bypass the code
38759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// that unpoisones the stack. This is why the run-time library has
38859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
38959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// stack in the interceptor. This however does not work inside the
39059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// actual function which catches the exception. Most likely because the
39159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// compiler hoists the load of the shadow value somewhere too high.
39259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// This causes asan to report a non-existing bug on 453.povray.
39359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// It sounds like an LLVM bug.
39459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovstruct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
39559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function &F;
39659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AddressSanitizer &ASan;
39759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  DIBuilder DIB;
39859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  LLVMContext *C;
39959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrTy;
40059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Type *IntptrPtrTy;
40119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  ShadowMapping Mapping;
40259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
40359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<AllocaInst*, 16> AllocaVec;
40459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  SmallVector<Instruction*, 8> RetVec;
40559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t TotalStackSize;
40659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  unsigned StackAlignment;
40759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
408f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
409f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany           *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
41059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
41159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
4121c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Stores a place and arguments of poisoning/unpoisoning call for alloca.
4131c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  struct AllocaPoisonCall {
4141c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IntrinsicInst *InsBefore;
4151c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    uint64_t Size;
4161c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool DoPoison;
4171c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  };
4181c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  SmallVector<AllocaPoisonCall, 8> AllocaPoisonCallVec;
4191c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
4201c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Maps Value to an AllocaInst from which the Value is originated.
4211c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  typedef DenseMap<Value*, AllocaInst*> AllocaForValueMapTy;
4221c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValueMapTy AllocaForValue;
4231c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
42459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
42559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      : F(F), ASan(ASan), DIB(*F.getParent()), C(ASan.C),
42659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov        IntptrTy(ASan.IntptrTy), IntptrPtrTy(PointerType::get(IntptrTy, 0)),
42719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov        Mapping(ASan.Mapping),
42819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov        TotalStackSize(0), StackAlignment(1 << Mapping.Scale) {}
42959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
43059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool runOnFunction() {
43159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (!ClStack) return false;
43259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    // Collect alloca, ret, lifetime instructions etc.
43359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    for (df_iterator<BasicBlock*> DI = df_begin(&F.getEntryBlock()),
43459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov         DE = df_end(&F.getEntryBlock()); DI != DE; ++DI) {
43559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      BasicBlock *BB = *DI;
43659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      visit(*BB);
43759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
43859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (AllocaVec.empty()) return false;
43959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
44059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    initializeCallbacks(*F.getParent());
44159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
44259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonStack();
44359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
44459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    if (ClDebugStack) {
44559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      DEBUG(dbgs() << F);
44659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
44759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return true;
44859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
44959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
45059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Finds all static Alloca instructions and puts
45159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // poisoned red zones around all of them.
45259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // Then unpoison everything back before the function returns.
45359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void poisonStack();
45459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
45559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ----------------------- Visitors.
45659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect all Ret instructions.
45759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitReturnInst(ReturnInst &RI) {
45859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    RetVec.push_back(&RI);
45959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
46059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
46159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  /// \brief Collect Alloca instructions we want (and can) handle.
46259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void visitAllocaInst(AllocaInst &AI) {
4631c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!isInterestingAlloca(AI)) return;
46459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
46559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = std::max(StackAlignment, AI.getAlignment());
46659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    AllocaVec.push_back(&AI);
467d4429214a2dffcfd8f97956ac8b1a67c4795d242Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(&AI);
46859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    TotalStackSize += AlignedSize;
46959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
47059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
4711c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// \brief Collect lifetime intrinsic calls to check for use-after-scope
4721c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// errors.
4731c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  void visitIntrinsicInst(IntrinsicInst &II) {
4741c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!ASan.CheckLifetime) return;
4751c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Intrinsic::ID ID = II.getIntrinsicID();
4761c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (ID != Intrinsic::lifetime_start &&
4771c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        ID != Intrinsic::lifetime_end)
4781c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      return;
4791c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Found lifetime intrinsic, add ASan instrumentation if necessary.
4801c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
4811c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // If size argument is undefined, don't do anything.
4821c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (Size->isMinusOne()) return;
4831c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Check that size doesn't saturate uint64_t and can
4841c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // be stored in IntptrTy.
4851c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    const uint64_t SizeValue = Size->getValue().getLimitedValue();
4861c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (SizeValue == ~0ULL ||
4871c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
4881c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      return;
4891c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // Find alloca instruction that corresponds to llvm.lifetime argument.
4901c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
4911c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    if (!AI) return;
4921c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool DoPoison = (ID == Intrinsic::lifetime_end);
4931c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaPoisonCall APC = {&II, SizeValue, DoPoison};
4941c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaPoisonCallVec.push_back(APC);
4951c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
4961c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
49759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // ---------------------- Helpers.
49859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  void initializeCallbacks(Module &M);
49959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
5001c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Check if we want (and can) handle this alloca.
5014c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  bool isInterestingAlloca(AllocaInst &AI) const {
5021c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return (!AI.isArrayAllocation() &&
5031c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov            AI.isStaticAlloca() &&
504d4429214a2dffcfd8f97956ac8b1a67c4795d242Kostya Serebryany            AI.getAlignment() <= RedzoneSize() &&
5051c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov            AI.getAllocatedType()->isSized());
5061c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
5071c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
50819cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t RedzoneSize() const {
50919cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov    return RedzoneSizeForScale(Mapping.Scale);
51019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  }
5114c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  uint64_t getAllocaSizeInBytes(AllocaInst *AI) const {
51259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    Type *Ty = AI->getAllocatedType();
51359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = ASan.TD->getTypeAllocSize(Ty);
51459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return SizeInBytes;
51559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
5164c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  uint64_t getAlignedSize(uint64_t SizeInBytes) const {
51759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    size_t RZ = RedzoneSize();
51859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return ((SizeInBytes + RZ - 1) / RZ) * RZ;
51959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
5204c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  uint64_t getAlignedAllocaSize(AllocaInst *AI) const {
52159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
52259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    return getAlignedSize(SizeInBytes);
52359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
5241c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  /// Finds alloca where the value comes from.
5251c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaInst *findAllocaForValue(Value *V);
5264c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  void poisonRedZones(const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB,
52759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                      Value *ShadowBase, bool DoPoison);
5284c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
529671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany
530671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany  void SetShadowToStackAfterReturnInlined(IRBuilder<> &IRB, Value *ShadowBase,
531671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany                                          int Size);
53259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov};
53359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
534800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}  // namespace
535800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
536800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanychar AddressSanitizer::ID = 0;
537800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyINITIALIZE_PASS(AddressSanitizer, "asan",
538800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs.",
539800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    false, false)
540ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey SamsonovFunctionPass *llvm::createAddressSanitizerFunctionPass(
541b0dcf61252e58715a3bea79f4c112572df361c30Alexey Samsonov    bool CheckInitOrder, bool CheckUseAfterReturn, bool CheckLifetime,
54211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov    StringRef BlacklistFile, bool ZeroBaseShadow) {
543ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov  return new AddressSanitizer(CheckInitOrder, CheckUseAfterReturn,
54411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                              CheckLifetime, BlacklistFile, ZeroBaseShadow);
545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
546800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
5471416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanychar AddressSanitizerModule::ID = 0;
5481416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya SerebryanyINITIALIZE_PASS(AddressSanitizerModule, "asan-module",
5491416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
5501416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    "ModulePass", false, false)
551b0dcf61252e58715a3bea79f4c112572df361c30Alexey SamsonovModulePass *llvm::createAddressSanitizerModulePass(
55211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov    bool CheckInitOrder, StringRef BlacklistFile, bool ZeroBaseShadow) {
55311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  return new AddressSanitizerModule(CheckInitOrder, BlacklistFile,
55411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                                    ZeroBaseShadow);
55525878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko}
55625878042030e85c244b41bfcdfad27c32360e2ecAlexander Potapenko
5572735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryanystatic size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
558c6af2432c802d241c8fffbe0371c023e6c58844eMichael J. Spencer  size_t Res = countTrailingZeros(TypeSize / 8);
5592735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  assert(Res < kNumberOfAccessSizes);
5602735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  return Res;
5612735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany}
5622735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany
56355a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling// \brief Create a constant for Str so that we can pass it to the run-time lib.
564800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str) {
56518c7f80b3e83ab584bd8572695a3cde8bafd9d3cChris Lattner  Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
5665111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GlobalVariable *GV = new GlobalVariable(M, StrConst->getType(), true,
56755a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling                            GlobalValue::InternalLinkage, StrConst,
56851c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany                            kAsanGenPrefix);
5695111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GV->setUnnamedAddr(true);  // Ok to merge these.
5705111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
5715111627ac1b0ae8a5a9d4dc1be8b22939ba850d0Kostya Serebryany  return GV;
57251c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany}
57351c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany
57451c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryanystatic bool GlobalWasGeneratedByAsan(GlobalVariable *G) {
57551c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  return G->getName().find(kAsanGenPrefix) == 0;
576800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
577800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
578800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyValue *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
579800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Shadow >> scale
58019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
58119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  if (Mapping.Offset == 0)
582800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return Shadow;
583800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // (Shadow >> scale) | offset
58448a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  if (Mapping.OrShadowOffset)
58548a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany    return IRB.CreateOr(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
58648a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany  else
58748a615fee78c3c262c60147a65dc6fff5fd6bb3bKostya Serebryany    return IRB.CreateAdd(Shadow, ConstantInt::get(IntptrTy, Mapping.Offset));
588800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
589800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
590c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryanyvoid AddressSanitizer::instrumentMemIntrinsicParam(
591ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    Instruction *OrigIns,
592800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Addr, Value *Size, Instruction *InsertBefore, bool IsWrite) {
5936ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRBuilder<> IRB(InsertBefore);
5946ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  if (Size->getType() != IntptrTy)
5956ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    Size = IRB.CreateIntCast(Size, IntptrTy, false);
596800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the first byte.
5976ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(OrigIns, InsertBefore, Addr, 8, IsWrite, Size);
598800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Check the last byte.
5996ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRB.SetInsertPoint(InsertBefore);
6006ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *SizeMinusOne = IRB.CreateSub(Size, ConstantInt::get(IntptrTy, 1));
6016ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
6026ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *AddrLast = IRB.CreateAdd(AddrLong, SizeMinusOne);
6036ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(OrigIns, InsertBefore, AddrLast, 8, IsWrite, Size);
604800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
605800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
606800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// Instrument memset/memmove/memcpy
607ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
608800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Dst = MI->getDest();
609800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  MemTransferInst *MemTran = dyn_cast<MemTransferInst>(MI);
6102735cf4aa52e31b8d2de90f836c3ad991215e04eKostya Serebryany  Value *Src = MemTran ? MemTran->getSource() : 0;
611800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Length = MI->getLength();
612800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
613800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Constant *ConstLength = dyn_cast<Constant>(Length);
614800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsertBefore = MI;
615800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ConstLength) {
616800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ConstLength->isNullValue()) return false;
617800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  } else {
618800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // The size is not a constant so it could be zero -- check at run-time.
619800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRB(InsertBefore);
620800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
621800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(Length,
62256139bc493790612ee6281630678e293be6b2eb2Kostya Serebryany                                  Constant::getNullValue(Length->getType()));
6234a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    InsertBefore = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
624800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
625800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
626ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  instrumentMemIntrinsicParam(MI, Dst, Length, InsertBefore, true);
627800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (Src)
628ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    instrumentMemIntrinsicParam(MI, Src, Length, InsertBefore, false);
629800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
630800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
631800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
632e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// If I is an interesting memory access, return the PointerOperand
633e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany// and set IsWrite. Otherwise return NULL.
634e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryanystatic Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite) {
635800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
636e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentReads) return NULL;
637e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = false;
638800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return LI->getPointerOperand();
639800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
640e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
641e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentWrites) return NULL;
642e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
643e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return SI->getPointerOperand();
644e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
645e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
646e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
647e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
648e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return RMW->getPointerOperand();
649e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
650e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
651e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    if (!ClInstrumentAtomics) return NULL;
652e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    *IsWrite = true;
653e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany    return XCHG->getPointerOperand();
654e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  }
655e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  return NULL;
656800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
657800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
658ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentMop(Instruction *I) {
6593780ad8b998d93d7db406919c06137cdb786ef05Axel Naumann  bool IsWrite = false;
660e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  Value *Addr = isInterestingMemoryAccess(I, &IsWrite);
661e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  assert(Addr);
6629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (ClOpt && ClOptGlobals) {
6639b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (GlobalVariable *G = dyn_cast<GlobalVariable>(Addr)) {
6649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If initialization order checking is disabled, a simple access to a
6659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // dynamically initialized global is always valid.
666ee548275c63a1eeffda9d3edd2bea04e1dadcc67Alexey Samsonov      if (!CheckInitOrder)
6679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
6689b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      // If a global variable does not have dynamic initialization we don't
669407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // have to instrument it.  However, if a global does not have initailizer
670407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      // at all, we assume it has dynamic initializer (in other TU).
671407790604b8f71f7172bbdfb76c27e1799d241c2Kostya Serebryany      if (G->hasInitializer() && !DynamicallyInitializedGlobals.Contains(G))
6729b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        return;
6739b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
674800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
6759b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
676800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigPtrTy = Addr->getType();
677800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *OrigTy = cast<PointerType>(OrigPtrTy)->getElementType();
678800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
679800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(OrigTy->isSized());
680605ff6655b31033dde21e61416751847bd0ee201Kostya Serebryany  uint32_t TypeSize = TD->getTypeStoreSizeInBits(OrigTy);
681800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6826ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  assert((TypeSize % 8) == 0);
683800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
6846ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check.
6856ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  if (TypeSize == 8  || TypeSize == 16 ||
6866ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      TypeSize == 32 || TypeSize == 64 || TypeSize == 128)
6876ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    return instrumentAddress(I, I, Addr, TypeSize, IsWrite, 0);
6886ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // Instrument unusual size (but still multiple of 8).
6896ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // We can not do it with a single check, so we do 1-byte check for the first
6906ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
6916ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  // to report the actual access size.
692800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(I);
6936ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *LastByte =  IRB.CreateIntToPtr(
6946ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      IRB.CreateAdd(IRB.CreatePointerCast(Addr, IntptrTy),
6956ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                    ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
6966ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      OrigPtrTy);
6976ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
6986ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(I, I, Addr, 8, IsWrite, Size);
6996ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  instrumentAddress(I, I, LastByte, 8, IsWrite, Size);
700800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
701800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
70255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// Validate the result of Module::getOrInsertFunction called for an interface
70355cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// function of AddressSanitizer. If the instrumented module defines a function
70455cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// with the same name, their prototypes must match, otherwise
70555cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko// getOrInsertFunction returns a bitcast.
706b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryanystatic Function *checkInterfaceFunction(Constant *FuncOrBitcast) {
70755cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  if (isa<Function>(FuncOrBitcast)) return cast<Function>(FuncOrBitcast);
70855cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  FuncOrBitcast->dump();
70955cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko  report_fatal_error("trying to redefine an AddressSanitizer "
71055cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko                     "interface function");
71155cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko}
71255cabae685991ac6bc6d96b14e2139f64a0c9967Alexander Potapenko
713800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya SerebryanyInstruction *AddressSanitizer::generateCrashCode(
714ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    Instruction *InsertBefore, Value *Addr,
7156ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    bool IsWrite, size_t AccessSizeIndex, Value *SizeArgument) {
716ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  IRBuilder<> IRB(InsertBefore);
7176ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  CallInst *Call = SizeArgument
7186ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    ? IRB.CreateCall2(AsanErrorCallbackSized[IsWrite], Addr, SizeArgument)
7196ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany    : IRB.CreateCall(AsanErrorCallback[IsWrite][AccessSizeIndex], Addr);
7206ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany
721f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We don't do Call->setDoesNotReturn() because the BB already has
722f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // UnreachableInst at the end.
723f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // This EmptyAsm is required to avoid callback merge.
724f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  IRB.CreateCall(EmptyAsm);
7253c7faae346f548c55cad86d82a2e242443001f23Kostya Serebryany  return Call;
726800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
727800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7282735cf4aa52e31b8d2de90f836c3ad991215e04eKostya SerebryanyValue *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
729c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            Value *ShadowValue,
730c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany                                            uint32_t TypeSize) {
73119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t Granularity = 1 << Mapping.Scale;
732c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // Addr & (Granularity - 1)
733c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  Value *LastAccessedByte = IRB.CreateAnd(
734c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany      AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
735c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (Addr & (Granularity - 1)) + size - 1
736c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  if (TypeSize / 8 > 1)
737c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    LastAccessedByte = IRB.CreateAdd(
738c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany        LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
739c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
740c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  LastAccessedByte = IRB.CreateIntCast(
7416e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany      LastAccessedByte, ShadowValue->getType(), false);
742c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
743c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
744c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany}
745c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany
746ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanyvoid AddressSanitizer::instrumentAddress(Instruction *OrigIns,
7476ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         Instruction *InsertBefore,
7486ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         Value *Addr, uint32_t TypeSize,
7496ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany                                         bool IsWrite, Value *SizeArgument) {
7506ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  IRBuilder<> IRB(InsertBefore);
751800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
752800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
753800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowTy  = IntegerType::get(
75419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov      *C, std::max(8U, TypeSize >> Mapping.Scale));
755800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
756800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowPtr = memToShadow(AddrLong, IRB);
757800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *CmpVal = Constant::getNullValue(ShadowTy);
758800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *ShadowValue = IRB.CreateLoad(
759800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
760800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
761800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
76211c2a47af825a0f89d75aaa97ad873ed2acef266Kostya Serebryany  size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
76319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t Granularity = 1 << Mapping.Scale;
764ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  TerminatorInst *CrashTerm = 0;
765ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
7666e2d506dc962873a0e05092bbb034f9a615d1084Kostya Serebryany  if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
7674a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    TerminatorInst *CheckTerm =
7684a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
769ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    assert(dyn_cast<BranchInst>(CheckTerm)->isUnconditional());
770f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BasicBlock *NextBB = CheckTerm->getSuccessor(0);
771c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    IRB.SetInsertPoint(CheckTerm);
772c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany    Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
773ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    BasicBlock *CrashBlock =
774ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
775ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany    CrashTerm = new UnreachableInst(*C, CrashBlock);
776f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
777f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany    ReplaceInstWithInst(CheckTerm, NewTerm);
778c0ed3e548c6f688e22685de04e210c7b59ac3433Kostya Serebryany  } else {
7794a2dec05cef5882b745dd248d79e42a42cdbc87bEvgeniy Stepanov    CrashTerm = SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), true);
780800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
781ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany
7826ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  Instruction *Crash = generateCrashCode(
7836ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany      CrashTerm, AddrLong, IsWrite, AccessSizeIndex, SizeArgument);
784ebd6454929f2ba3b92f61c151eccde0b8b0a8dedKostya Serebryany  Crash->setDebugLoc(OrigIns->getDebugLoc());
785800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
786800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
7871416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanyvoid AddressSanitizerModule::createInitializerPoisonCalls(
788ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    Module &M, GlobalValue *ModuleName) {
7899b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // We do all of our poisoning and unpoisoning within _GLOBAL__I_a.
7909b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Function *GlobalInit = M.getFunction("_GLOBAL__I_a");
7919b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // If that function is not present, this TU contains no globals, or they have
7929b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // all been optimized away
7939b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!GlobalInit)
7949b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return;
7959b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7969b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Set up the arguments to our poison/unpoison functions.
7979b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  IRBuilder<> IRB(GlobalInit->begin()->getFirstInsertionPt());
7989b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
7999b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add a call to poison all external globals before the given function starts.
800ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
801ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
8029b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Add calls to unpoison all globals before each return instruction.
8049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Function::iterator I = GlobalInit->begin(), E = GlobalInit->end();
8059b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      I != E; ++I) {
8069b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator())) {
8079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      CallInst::Create(AsanUnpoisonGlobals, "", RI);
8089b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8099b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
8109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
8119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8121416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
8139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  Type *Ty = cast<PointerType>(G->getType())->getElementType();
814324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
8159b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
81659a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany  if (BL->isIn(*G)) return false;
8179b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!Ty->isSized()) return false;
8189b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (!G->hasInitializer()) return false;
81951c7c65e32f76ec5a50cdecfe2b4c287c57da127Kostya Serebryany  if (GlobalWasGeneratedByAsan(G)) return false;  // Our own global.
8209b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Touch only those globals that will not be defined in other modules.
8219b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Don't handle ODR type linkages since other modules may be built w/o asan.
8229b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
8239b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::PrivateLinkage &&
8249b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      G->getLinkage() != GlobalVariable::InternalLinkage)
8259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8269b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Two problems with thread-locals:
8279b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - The address of the main thread's copy can't be computed at link-time.
8289b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   - Need to poison all copies, not just the main thread's one.
8299b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->isThreadLocal())
8309b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8319b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // For now, just ignore this Alloca if the alignment is large.
832b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  if (G->getAlignment() > RedzoneSize()) return false;
8339b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8349b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Ignore all the globals with the names starting with "\01L_OBJC_".
8359b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Many of those are put into the .cstring section. The linker compresses
8369b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // that section by removing the spare \0s after the string terminator, so
8379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // our redzones get broken.
8389b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if ((G->getName().find("\01L_OBJC_") == 0) ||
8399b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      (G->getName().find("\01l_OBJC_") == 0)) {
8409b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    DEBUG(dbgs() << "Ignoring \\01L_OBJC_* global: " << *G);
8419b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    return false;
8429b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
8439b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8449b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  if (G->hasSection()) {
8459b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    StringRef Section(G->getSection());
8469b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Ignore the globals from the __OBJC section. The ObjC runtime assumes
8479b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
8489b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // them.
8499b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if ((Section.find("__OBJC,") == 0) ||
8509b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        (Section.find("__DATA, __objc_") == 0)) {
8519b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G);
8529b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
8539b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8549b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
8559b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Constant CFString instances are compiled in the following way:
8569b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the string buffer is emitted into
8579b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     __TEXT,__cstring,cstring_literals
8589b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //  -- the constant NSConstantString structure referencing that buffer
8599b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    //     is placed into __DATA,__cfstring
8609b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Therefore there's no point in placing redzones into __DATA,__cfstring.
8619b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Moreover, it causes the linker to crash on OS X 10.7
8629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (Section.find("__DATA,__cfstring") == 0) {
8639b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      DEBUG(dbgs() << "Ignoring CFString: " << *G);
8649b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      return false;
8659b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    }
8669b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  }
8679b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8689b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  return true;
8699b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany}
8709b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
8714684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonovvoid AddressSanitizerModule::initializeCallbacks(Module &M) {
8724684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  IRBuilder<> IRB(*C);
8734684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare our poisoning and unpoisoning functions.
8744684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
875ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov      kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, NULL));
8764684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
8774684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8784684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnpoisonGlobalsName, IRB.getVoidTy(), NULL));
8794684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
8804684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  // Declare functions that register/unregister globals.
8814684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8824684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanRegisterGlobalsName, IRB.getVoidTy(),
8834684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IntptrTy, IntptrTy, NULL));
8844684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
8854684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals = checkInterfaceFunction(M.getOrInsertFunction(
8864684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      kAsanUnregisterGlobalsName,
8874684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov      IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
8884684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
8894684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov}
8904684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov
891800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// This function replaces all global variables with new variables that have
892800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// trailing redzones. It also creates a function that poisons
893800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany// redzones and inserts this function into llvm.global_ctors.
8941416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryanybool AddressSanitizerModule::runOnModule(Module &M) {
8951416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!ClGlobals) return false;
8961416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
8971416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany  if (!TD)
8981416edc30adbd53b2be863f7f3de56de4a4c9d0aKostya Serebryany    return false;
899e39e1316f034e9932cb8da535541a3e35a0e490aAlexey Samsonov  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
900d6f62c8da5aa4f3388cec1542309ffa623cac601Alexey Samsonov  if (BL->isIn(M)) return false;
901b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  C = &(M.getContext());
90219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  int LongSize = TD->getPointerSizeInBits();
90319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  IntptrTy = Type::getIntNTy(*C, LongSize);
90411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
9054684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  initializeCallbacks(M);
9064684858624d7ffe82379783e9b678227d5e0b515Alexey Samsonov  DynamicallyInitializedGlobals.Init(M);
907b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
908800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<GlobalVariable *, 16> GlobalsToChange;
909800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
9109b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  for (Module::GlobalListType::iterator G = M.global_begin(),
9119b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany       E = M.global_end(); G != E; ++G) {
9129b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    if (ShouldInstrumentGlobal(G))
9139b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany      GlobalsToChange.push_back(G);
914800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
915800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
916800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  size_t n = GlobalsToChange.size();
917800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (n == 0) return false;
918800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
919800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // A global is described by a structure
920800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t beg;
921800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size;
922800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   size_t size_with_redzone;
923800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  //   const char *name;
924086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany  //   const char *module_name;
9259b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  //   size_t has_dynamic_init;
926800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // We initialize an array of such structures and pass it to a run-time call.
927800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  StructType *GlobalStructTy = StructType::get(IntptrTy, IntptrTy,
9289b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany                                               IntptrTy, IntptrTy,
929086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany                                               IntptrTy, IntptrTy, NULL);
9308819c84aed10777ba91d4e862229882b8da0b272Rafael Espindola  SmallVector<Constant *, 16> Initializers(n);
931b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany
932b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
933b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  assert(CtorFunc);
934b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
935800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
936ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  bool HasDynamicallyInitializedGlobals = false;
9379b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
938086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany  GlobalVariable *ModuleName = createPrivateGlobalForString(
939086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany      M, M.getModuleIdentifier());
940ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  // We shouldn't merge same module names, as this string serves as unique
941ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  // module ID in runtime.
942ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  ModuleName->setUnnamedAddr(false);
943086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany
944800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0; i < n; i++) {
94529f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    static const uint64_t kMaxGlobalRedzone = 1 << 18;
946800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *G = GlobalsToChange[i];
947800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    PointerType *PtrTy = cast<PointerType>(G->getType());
948800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *Ty = PtrTy->getElementType();
949208a4ff2b56f453910bb817540f34b8169f7702aKostya Serebryany    uint64_t SizeInBytes = TD->getTypeAllocSize(Ty);
95029f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    uint64_t MinRZ = RedzoneSize();
95163f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // MinRZ <= RZ <= kMaxGlobalRedzone
95263f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // and trying to make RZ to be ~ 1/4 of SizeInBytes.
95329f975f8ffda1f5d78cbf2530c2316abef11aa70Kostya Serebryany    uint64_t RZ = std::max(MinRZ,
95463f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany                         std::min(kMaxGlobalRedzone,
95563f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany                                  (SizeInBytes / MinRZ / 4) * MinRZ));
95663f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    uint64_t RightRedzoneSize = RZ;
95763f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    // Round up to MinRZ
95863f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    if (SizeInBytes % MinRZ)
95963f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany      RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
96063f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
961800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
9629b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Determine whether this global should be poisoned in initialization.
963ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany    bool GlobalHasDynamicInitializer =
964ca23d43084c45a7d6f4371d62f45be044650ce38Kostya Serebryany        DynamicallyInitializedGlobals.Contains(G);
96559a4a47a7bea7cc17877c6a3954ad9f8309ff1cbKostya Serebryany    // Don't check initialization order if this global is blacklisted.
96646e11c4c97fe1c424241e4098801456303a5c86ePeter Collingbourne    GlobalHasDynamicInitializer &= !BL->isIn(*G, "init");
967800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
968800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StructType *NewTy = StructType::get(Ty, RightRedZoneTy, NULL);
969800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Constant *NewInitializer = ConstantStruct::get(
970800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NewTy, G->getInitializer(),
971800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        Constant::getNullValue(RightRedZoneTy), NULL);
972800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
973086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany    GlobalVariable *Name = createPrivateGlobalForString(M, G->getName());
974800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
975800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Create a new global variable with enough space for a redzone.
97655a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling    GlobalValue::LinkageTypes Linkage = G->getLinkage();
97755a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling    if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
97855a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling      Linkage = GlobalValue::InternalLinkage;
979800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    GlobalVariable *NewGlobal = new GlobalVariable(
98055a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling        M, NewTy, G->isConstant(), Linkage,
981ce718ff9f42c7da092eaa01dd0242e8d5ba84713Hans Wennborg        NewInitializer, "", G, G->getThreadLocalMode());
982800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->copyAttributesFrom(G);
98363f0846f1eb43332a08811d332b813276b727eb6Kostya Serebryany    NewGlobal->setAlignment(MinRZ);
984800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
985800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Indices2[2];
986800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[0] = IRB.getInt32(0);
987800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Indices2[1] = IRB.getInt32(0);
988800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
989800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->replaceAllUsesWith(
990f1639abf1aaba1448f719f595156cd0f4cd560ccKostya Serebryany        ConstantExpr::getGetElementPtr(NewGlobal, Indices2, true));
991800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NewGlobal->takeName(G);
992800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    G->eraseFromParent();
993800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
994800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Initializers[i] = ConstantStruct::get(
995800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        GlobalStructTy,
996800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(NewGlobal, IntptrTy),
997800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes),
998800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
999800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantExpr::getPointerCast(Name, IntptrTy),
1000086a472dbed9911f83add781e020cb49c89829d0Kostya Serebryany        ConstantExpr::getPointerCast(ModuleName, IntptrTy),
10019b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany        ConstantInt::get(IntptrTy, GlobalHasDynamicInitializer),
1002800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        NULL);
10039b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
10049b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany    // Populate the first and last globals declared in this TU.
1005ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    if (CheckInitOrder && GlobalHasDynamicInitializer)
1006ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov      HasDynamicallyInitializedGlobals = true;
10079b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany
1008324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany    DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1009800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1010800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1011800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1012800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  GlobalVariable *AllGlobals = new GlobalVariable(
101355a1a590bf0cadf88dfbef2aab6948ffec35c1c3Bill Wendling      M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1014800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1015800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10169b9f87a87ac1b373c4c6a70904315bebbd01c50cKostya Serebryany  // Create calls for poisoning before initializers run and unpoisoning after.
1017ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov  if (CheckInitOrder && HasDynamicallyInitializedGlobals)
1018ca825ea24de2f3d819845ee01796dc6c7a45170dAlexey Samsonov    createInitializerPoisonCalls(M, ModuleName);
1019800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateCall2(AsanRegisterGlobals,
1020800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  IRB.CreatePointerCast(AllGlobals, IntptrTy),
1021800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  ConstantInt::get(IntptrTy, n));
1022800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10237bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // We also need to unregister globals at the end, e.g. when a shared library
10247bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  // gets closed.
10257bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  Function *AsanDtorFunction = Function::Create(
10267bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
10277bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
10287bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
10297bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
10307bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  IRB_Dtor.CreateCall2(AsanUnregisterGlobals,
10317bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       IRB.CreatePointerCast(AllGlobals, IntptrTy),
10327bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany                       ConstantInt::get(IntptrTy, n));
10337bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndCtorPriority);
10347bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany
1035800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  DEBUG(dbgs() << M);
1036800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  return true;
1037800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1038800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
10398b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanyvoid AddressSanitizer::initializeCallbacks(Module &M) {
10408b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(*C);
10419db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  // Create __asan_report* callbacks.
10429db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
10439db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
10449db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany         AccessSizeIndex++) {
10459db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      // IsWrite and TypeSize are encoded in the function name.
10469db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany      std::string FunctionName = std::string(kAsanReportErrorTemplate) +
10479db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany          (AccessIsWrite ? "store" : "load") + itostr(1 << AccessSizeIndex);
10484f0c69623c10a3a49f6926fd53694ee532e06a85Kostya Serebryany      // If we are merging crash callbacks, they have two parameters.
10497846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany      AsanErrorCallback[AccessIsWrite][AccessSizeIndex] =
10507846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany          checkInterfaceFunction(M.getOrInsertFunction(
10517846c1c851a53a8280f9d8ed57cd98d82c742551Kostya Serebryany              FunctionName, IRB.getVoidTy(), IntptrTy, NULL));
10529db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany    }
10539db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany  }
10546ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  AsanErrorCallbackSized[0] = checkInterfaceFunction(M.getOrInsertFunction(
10556ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany              kAsanReportLoadN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
10566ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany  AsanErrorCallbackSized[1] = checkInterfaceFunction(M.getOrInsertFunction(
10576ecccdbb2bf24a011b9c8ecbdd39be5a02269670Kostya Serebryany              kAsanReportStoreN, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
1058ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
1059ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  AsanHandleNoReturnFunc = checkInterfaceFunction(M.getOrInsertFunction(
1060ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany      kAsanHandleNoReturnName, IRB.getVoidTy(), NULL));
1061f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  // We insert an empty inline asm after __asan_report* to avoid callback merge.
1062f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany  EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1063f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            StringRef(""), StringRef(""),
1064f7b08226eb44458f6f38cbeaca527028803c725aKostya Serebryany                            /*hasSideEffects=*/true);
10658b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany}
10668b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
106719cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonovvoid AddressSanitizer::emitShadowMapping(Module &M, IRBuilder<> &IRB) const {
106811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Tell the values of mapping offset and scale to the run-time.
106911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  GlobalValue *asan_mapping_offset =
107011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
107111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                     ConstantInt::get(IntptrTy, Mapping.Offset),
107211af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                     kAsanMappingOffsetName);
107311af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Read the global, otherwise it may be optimized away.
107411af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  IRB.CreateLoad(asan_mapping_offset, true);
107511af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov
107611af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  GlobalValue *asan_mapping_scale =
107711af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov      new GlobalVariable(M, IntptrTy, true, GlobalValue::LinkOnceODRLinkage,
107811af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         ConstantInt::get(IntptrTy, Mapping.Scale),
107911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov                         kAsanMappingScaleName);
108011af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  // Read the global, otherwise it may be optimized away.
108111af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  IRB.CreateLoad(asan_mapping_scale, true);
108219cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov}
108319cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov
10848b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany// virtual
10858b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryanybool AddressSanitizer::doInitialization(Module &M) {
10868b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // Initialize the private fields. No one has accessed them before.
10878b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  TD = getAnalysisIfAvailable<DataLayout>();
10888b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10898b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  if (!TD)
10908b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany    return false;
1091e39e1316f034e9932cb8da535541a3e35a0e490aAlexey Samsonov  BL.reset(SpecialCaseList::createOrDie(BlacklistFile));
10928b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  DynamicallyInitializedGlobals.Init(M);
10938b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10948b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  C = &(M.getContext());
10958b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  LongSize = TD->getPointerSizeInBits();
10968b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IntptrTy = Type::getIntNTy(*C, LongSize);
10978b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany
10988b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanCtorFunction = Function::Create(
10998b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      FunctionType::get(Type::getVoidTy(*C), false),
11008b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      GlobalValue::InternalLinkage, kAsanModuleCtorName, &M);
11018b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  BasicBlock *AsanCtorBB = BasicBlock::Create(*C, "", AsanCtorFunction);
11028b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  // call __asan_init in the module ctor.
11038b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRBuilder<> IRB(ReturnInst::Create(*C, AsanCtorBB));
11048b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction = checkInterfaceFunction(
11058b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany      M.getOrInsertFunction(kAsanInitName, IRB.getVoidTy(), NULL));
11068b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  AsanInitFunction->setLinkage(Function::ExternalLinkage);
11078b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  IRB.CreateCall(AsanInitFunction);
11089db5b5ffa9fccd5c7f1f39a3e9aa66cc4a5eedc1Kostya Serebryany
110911af9a873f9e1409a422ab31e22729368805afafAlexey Samsonov  Mapping = getShadowMapping(M, LongSize, ZeroBaseShadow);
111019cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  emitShadowMapping(M, IRB);
1111800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
11127bcfc9950bac0f411f9671e8d6ce483bd219727eKostya Serebryany  appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndCtorPriority);
1113ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany  return true;
1114ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany}
1115ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany
1116a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryanybool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1117a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // For each NSObject descendant having a +load method, this method is invoked
1118a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // by the ObjC runtime before any of the static constructors is called.
1119a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // Therefore we need to instrument such methods with a call to __asan_init
1120a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // at the beginning in order to initialize our runtime before any access to
1121a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // the shadow memory.
1122a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // We cannot just ignore these methods, because they may call other
1123a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  // instrumented functions.
1124a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  if (F.getName().find(" load]") != std::string::npos) {
1125a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRBuilder<> IRB(F.begin()->begin());
1126a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    IRB.CreateCall(AsanInitFunction);
1127a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany    return true;
1128a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  }
1129a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  return false;
1130a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany}
1131a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
1132ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryanybool AddressSanitizer::runOnFunction(Function &F) {
1133800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (BL->isIn(F)) return false;
1134800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (&F == AsanCtorFunction) return false;
11353797adb94fdc6b747cb0e97a64b15b931f2533b8Kostya Serebryany  if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
1136324d96b9e265b0fd8bf63a28340910def64e2164Kostya Serebryany  DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
11378b390ffbfdd52a23a45a21de99aa1c31f3ce623fKostya Serebryany  initializeCallbacks(*F.getParent());
1138a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
11398eec41fc778e99d42172a7f6de76faa43a6d8847Kostya Serebryany  // If needed, insert __asan_init before checking for SanitizeAddress attr.
1140a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany  maybeInsertAsanInitAtFunctionEntry(F);
1141a1a8a323f43a95620fc4c6b5aad8d5ff5e5eb590Kostya Serebryany
114220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (!F.hasFnAttribute(Attribute::SanitizeAddress))
11436765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling    return false;
1144800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1145800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (!ClDebugFunc.empty() && ClDebugFunc != F.getName())
1146800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return false;
11476765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling
11486765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // We want to instrument every address only once per basic block (unless there
11496765834754cbb3cb0f15b4b15e98c5e73fa50066Bill Wendling  // are calls between uses).
1150800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallSet<Value*, 16> TempsToInstrument;
1151800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallVector<Instruction*, 16> ToInstrument;
115295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  SmallVector<Instruction*, 8> NoReturnCalls;
115320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  int NumAllocas = 0;
1154e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany  bool IsWrite;
1155800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1156800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Fill the set of memory operations to instrument.
1157800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (Function::iterator FI = F.begin(), FE = F.end();
1158800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       FI != FE; ++FI) {
1159800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    TempsToInstrument.clear();
1160324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany    int NumInsnsPerBB = 0;
1161800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    for (BasicBlock::iterator BI = FI->begin(), BE = FI->end();
1162800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany         BI != BE; ++BI) {
1163bcb55ce3862bbbedac4e09d7099c9e0efc434e4bKostya Serebryany      if (LooksLikeCodeInBug11395(BI)) return false;
1164e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (Value *Addr = isInterestingMemoryAccess(BI, &IsWrite)) {
1165800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        if (ClOpt && ClOptSameTemp) {
1166800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          if (!TempsToInstrument.insert(Addr))
1167800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            continue;  // We've seen this temp in the current BB.
1168800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1169800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else if (isa<MemIntrinsic>(BI) && ClMemIntrin) {
1170800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        // ok, take it.
1171800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      } else {
117220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany        if (isa<AllocaInst>(BI))
117320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany          NumAllocas++;
11741479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany        CallSite CS(BI);
11751479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany        if (CS) {
1176800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          // A call inside BB.
1177800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          TempsToInstrument.clear();
11781479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany          if (CS.doesNotReturn())
11791479c9bb392325688b72e5829bbb7939c4a079a4Kostya Serebryany            NoReturnCalls.push_back(CS.getInstruction());
1180800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        }
1181800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        continue;
1182800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1183800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      ToInstrument.push_back(BI);
1184324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      NumInsnsPerBB++;
1185324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany      if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB)
1186324cbb89f2759fb9ad347bd2af4631e50c39c8f3Kostya Serebryany        break;
1187800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1188800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1189800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
119020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  Function *UninstrumentedDuplicate = 0;
119120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  bool LikelyToInstrument =
119220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      !NoReturnCalls.empty() || !ToInstrument.empty() || (NumAllocas > 0);
119320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (ClKeepUninstrumented && LikelyToInstrument) {
119420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    ValueToValueMapTy VMap;
119520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate = CloneFunction(&F, VMap, false);
119620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate->removeFnAttr(Attribute::SanitizeAddress);
119720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    UninstrumentedDuplicate->setName("NOASAN_" + F.getName());
119820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    F.getParent()->getFunctionList().push_back(UninstrumentedDuplicate);
119920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  }
120020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
1201800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Instrument.
1202800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  int NumInstrumented = 0;
1203800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = ToInstrument.size(); i != n; i++) {
1204800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Inst = ToInstrument[i];
1205800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (ClDebugMin < 0 || ClDebugMax < 0 ||
1206800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
1207e6cf2e0bd09544eeb69665deb908d264e62a71c2Kostya Serebryany      if (isInterestingMemoryAccess(Inst, &IsWrite))
1208ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMop(Inst);
1209800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      else
1210ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany        instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1211800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1212800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    NumInstrumented++;
1213800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1214800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
121559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  FunctionStackPoisoner FSP(F, *this);
121659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool ChangedStack = FSP.runOnFunction();
121795e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
121895e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
121995e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
122095e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  for (size_t i = 0, n = NoReturnCalls.size(); i != n; i++) {
122195e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    Instruction *CI = NoReturnCalls[i];
122295e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany    IRBuilder<> IRB(CI);
1223ee4edeccabe1854ee895f52d4ac5588bd5f40c80Kostya Serebryany    IRB.CreateCall(AsanHandleNoReturnFunc);
122495e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany  }
122595e3cf44a9d4672655dee3bd558bfeefa631dd55Kostya Serebryany
122620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  bool res = NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty();
122720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  DEBUG(dbgs() << "ASAN done instrumenting: " << res << " " << F << "\n");
122820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
122920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  if (ClKeepUninstrumented) {
123020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    if (!res) {
123120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      // No instrumentation is done, no need for the duplicate.
123220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      if (UninstrumentedDuplicate)
123320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany        UninstrumentedDuplicate->eraseFromParent();
123420985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    } else {
123520985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      // The function was instrumented. We must have the duplicate.
123620985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      assert(UninstrumentedDuplicate);
123720985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      UninstrumentedDuplicate->setSection("NOASAN");
123820985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      assert(!F.hasSection());
123920985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany      F.setSection("ASAN");
124020985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany    }
124120985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  }
124220985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany
124320985711c76b8799d689a9c0e416b68896333c23Kostya Serebryany  return res;
1244800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1245800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1246800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic uint64_t ValueForPoison(uint64_t PoisonByte, size_t ShadowRedzoneSize) {
1247800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 1) return PoisonByte;
1248800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 2) return (PoisonByte << 8) + PoisonByte;
1249800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (ShadowRedzoneSize == 4)
1250800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    return (PoisonByte << 24) + (PoisonByte << 16) +
1251800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        (PoisonByte << 8) + (PoisonByte);
1252858143816d43e58b17bfd11cb1b57afbd7f0f893Craig Topper  llvm_unreachable("ShadowRedzoneSize is either 1, 2 or 4");
1253800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1254800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1255800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryanystatic void PoisonShadowPartialRightRedzone(uint8_t *Shadow,
1256800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t Size,
1257b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                            size_t RZSize,
1258800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            size_t ShadowGranularity,
1259800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                            uint8_t Magic) {
1260b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  for (size_t i = 0; i < RZSize;
1261800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany       i+= ShadowGranularity, Shadow++) {
1262800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (i + ShadowGranularity <= Size) {
1263800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = 0;  // fully addressable
1264800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else if (i >= Size) {
1265800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Magic;  // unaddressable
1266800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    } else {
1267800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      *Shadow = Size - i;  // first Size-i bytes are addressable
1268800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1269800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1270800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1271800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
127259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Workaround for bug 11395: we don't want to instrument stack in functions
127359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// with large assembly blobs (32-bit only), otherwise reg alloc may crash.
127459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// FIXME: remove once the bug 11395 is fixed.
127559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovbool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
127659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (LongSize != 32) return false;
127759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  CallInst *CI = dyn_cast<CallInst>(I);
127859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (!CI || !CI->isInlineAsm()) return false;
127959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (CI->getNumArgOperands() <= 5) return false;
128059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  // We have inline assembly with quite a few arguments.
128159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return true;
128259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
128359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
128459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::initializeCallbacks(Module &M) {
128559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  IRBuilder<> IRB(*C);
1286f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
1287f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    std::string Suffix = itostr(i);
1288f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    AsanStackMallocFunc[i] = checkInterfaceFunction(
1289f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany        M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
1290f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany                              IntptrTy, IntptrTy, NULL));
1291f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    AsanStackFreeFunc[i] = checkInterfaceFunction(M.getOrInsertFunction(
1292f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany        kAsanStackFreeNameTemplate + Suffix, IRB.getVoidTy(), IntptrTy,
1293f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany        IntptrTy, IntptrTy, NULL));
1294f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  }
129559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanPoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
129659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanPoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
129759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  AsanUnpoisonStackMemoryFunc = checkInterfaceFunction(M.getOrInsertFunction(
129859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov      kAsanUnpoisonStackMemoryName, IRB.getVoidTy(), IntptrTy, IntptrTy, NULL));
129959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
130059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
130159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonRedZones(
13024c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak  const ArrayRef<AllocaInst*> &AllocaVec, IRBuilder<> &IRB, Value *ShadowBase,
130359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoPoison) {
130419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov  size_t ShadowRZSize = RedzoneSize() >> Mapping.Scale;
1305800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(ShadowRZSize >= 1 && ShadowRZSize <= 4);
1306800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZTy = Type::getIntNTy(*C, ShadowRZSize * 8);
1307800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *RZPtrTy = PointerType::get(RZTy, 0);
1308800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1309800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonLeft  = ConstantInt::get(RZTy,
1310800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackLeftRedzoneMagic : 0LL, ShadowRZSize));
1311800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonMid   = ConstantInt::get(RZTy,
1312800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackMidRedzoneMagic : 0LL, ShadowRZSize));
1313800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *PoisonRight = ConstantInt::get(RZTy,
1314800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    ValueForPoison(DoPoison ? kAsanStackRightRedzoneMagic : 0LL, ShadowRZSize));
1315800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1316800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison the first red zone.
1317800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(PoisonLeft, IRB.CreateIntToPtr(ShadowBase, RZPtrTy));
1318800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1319800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // poison all other red zones.
1320b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1321800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1322800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1323800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1324800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1325b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert(AlignedSize - SizeInBytes < RedzoneSize());
1326800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Value *Ptr = NULL;
1327800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1328800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Pos += AlignedSize;
1329800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1330800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    assert(ShadowBase->getType() == IntptrTy);
1331800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (SizeInBytes < AlignedSize) {
1332800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      // Poison the partial redzone at right
1333800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Ptr = IRB.CreateAdd(
1334800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany          ShadowBase, ConstantInt::get(IntptrTy,
133519cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                                       (Pos >> Mapping.Scale) - ShadowRZSize));
1336b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany      size_t AddressableBytes = RedzoneSize() - (AlignedSize - SizeInBytes);
1337800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      uint32_t Poison = 0;
1338800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      if (DoPoison) {
1339800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        PoisonShadowPartialRightRedzone((uint8_t*)&Poison, AddressableBytes,
1340b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany                                        RedzoneSize(),
134119cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                                        1ULL << Mapping.Scale,
1342800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                                        kAsanStackPartialRedzoneMagic);
13433e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany        Poison =
13443e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany            ASan.TD->isLittleEndian()
13453e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                ? support::endian::byte_swap<uint32_t, support::little>(Poison)
13463e1d45bf44f882f3ee139d452dd50305d831a341Kostya Serebryany                : support::endian::byte_swap<uint32_t, support::big>(Poison);
1347800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      }
1348800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      Value *PartialPoison = ConstantInt::get(RZTy, Poison);
1349800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      IRB.CreateStore(PartialPoison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1350800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1351800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1352800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Poison the full redzone at right.
1353800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Ptr = IRB.CreateAdd(ShadowBase,
135419cd7e9ce28ed7f3326ebcd386eec215ab3763f9Alexey Samsonov                        ConstantInt::get(IntptrTy, Pos >> Mapping.Scale));
13551c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    bool LastAlloca = (i == AllocaVec.size() - 1);
13561c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Value *Poison = LastAlloca ? PoisonRight : PoisonMid;
1357800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRB.CreateStore(Poison, IRB.CreateIntToPtr(Ptr, RZPtrTy));
1358800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1359b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += RedzoneSize();
1360800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1361800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1362800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1363f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany// Fake stack allocator (asan_fake_stack.h) has 11 size classes
1364f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany// for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
1365f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryanystatic int StackMallocSizeClass(uint64_t LocalStackSize) {
1366f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  assert(LocalStackSize <= kMaxStackMallocSize);
1367f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  uint64_t MaxSize = kMinStackMallocSize;
1368f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  for (int i = 0; ; i++, MaxSize *= 2)
1369f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    if (LocalStackSize <= MaxSize)
1370f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany      return i;
1371f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  llvm_unreachable("impossible LocalStackSize");
1372f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany}
1373f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany
1374671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// Set Size bytes starting from ShadowBase to kAsanStackAfterReturnMagic.
1375671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// We can not use MemSet intrinsic because it may end up calling the actual
1376671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// memset. Size is a multiple of 8.
1377671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// Currently this generates 8-byte stores on x86_64; it may be better to
1378671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany// generate wider stores.
1379671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryanyvoid FunctionStackPoisoner::SetShadowToStackAfterReturnInlined(
1380671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany    IRBuilder<> &IRB, Value *ShadowBase, int Size) {
1381671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany  assert(!(Size % 8));
1382671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany  assert(kAsanStackAfterReturnMagic == 0xf5);
1383671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany  for (int i = 0; i < Size; i += 8) {
1384671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany    Value *p = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
1385671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany    IRB.CreateStore(ConstantInt::get(IRB.getInt64Ty(), 0xf5f5f5f5f5f5f5f5ULL),
1386671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany                    IRB.CreateIntToPtr(p, IRB.getInt64Ty()->getPointerTo()));
1387671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany  }
1388671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany}
1389671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany
139059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonStack() {
139159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  uint64_t LocalStackSize = TotalStackSize +
139259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                            (AllocaVec.size() + 1) * RedzoneSize();
1393800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
139459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  bool DoStackMalloc = ASan.CheckUseAfterReturn
1395800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      && LocalStackSize <= kMaxStackMallocSize;
1396f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany  int StackMallocIdx = -1;
1397800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
13981c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  assert(AllocaVec.size() > 0);
1399800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Instruction *InsBefore = AllocaVec[0];
1400800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRBuilder<> IRB(InsBefore);
1401800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1402800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1403800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Type *ByteArrayTy = ArrayType::get(IRB.getInt8Ty(), LocalStackSize);
1404800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  AllocaInst *MyAlloca =
1405800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany      new AllocaInst(ByteArrayTy, "MyAlloca", InsBefore);
140659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  if (ClRealignStack && StackAlignment < RedzoneSize())
140759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    StackAlignment = RedzoneSize();
140859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  MyAlloca->setAlignment(StackAlignment);
1409800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(MyAlloca->isStaticAlloca());
1410800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *OrigStackBase = IRB.CreatePointerCast(MyAlloca, IntptrTy);
1411800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *LocalStackBase = OrigStackBase;
1412800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1413800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  if (DoStackMalloc) {
1414ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    // LocalStackBase = OrigStackBase
1415ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    // if (__asan_option_detect_stack_use_after_return)
1416ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    //   LocalStackBase = __asan_stack_malloc_N(LocalStackBase, OrigStackBase);
1417f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    StackMallocIdx = StackMallocSizeClass(LocalStackSize);
1418f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany    assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
1419ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    Constant *OptionDetectUAR = F.getParent()->getOrInsertGlobal(
1420ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany        kAsanOptionDetectUAR, IRB.getInt32Ty());
1421ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    Value *Cmp = IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUAR),
1422ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany                                  Constant::getNullValue(IRB.getInt32Ty()));
1423ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    Instruction *Term =
1424ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany        SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1425ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    BasicBlock *CmpBlock = cast<Instruction>(Cmp)->getParent();
1426ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    IRBuilder<> IRBIf(Term);
1427ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    LocalStackBase = IRBIf.CreateCall2(
1428ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany        AsanStackMallocFunc[StackMallocIdx],
1429800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany        ConstantInt::get(IntptrTy, LocalStackSize), OrigStackBase);
1430ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    BasicBlock *SetBlock = cast<Instruction>(LocalStackBase)->getParent();
1431ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    IRB.SetInsertPoint(InsBefore);
1432ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    PHINode *Phi = IRB.CreatePHI(IntptrTy, 2);
1433ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    Phi->addIncoming(OrigStackBase, CmpBlock);
1434ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    Phi->addIncoming(LocalStackBase, SetBlock);
1435ac04abaf5a1df4c4bf48367cfbb41600289c4d78Kostya Serebryany    LocalStackBase = Phi;
1436800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1437800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
14383016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // This string will be parsed by the run-time (DescribeAddressIfStack).
1439800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  SmallString<2048> StackDescriptionStorage;
1440800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  raw_svector_ostream StackDescription(StackDescriptionStorage);
14413016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  StackDescription << AllocaVec.size() << " ";
1442800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
14431c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Insert poison calls for lifetime intrinsics for alloca.
14441c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  bool HavePoisonedAllocas = false;
14451c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  for (size_t i = 0, n = AllocaPoisonCallVec.size(); i < n; i++) {
14461c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    const AllocaPoisonCall &APC = AllocaPoisonCallVec[i];
14471c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IntrinsicInst *II = APC.InsBefore;
14481c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
14491c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    assert(AI);
14501c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    IRBuilder<> IRB(II);
14511c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    poisonAlloca(AI, APC.Size, IRB, APC.DoPoison);
14521c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    HavePoisonedAllocas |= APC.DoPoison;
14531c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  }
14541c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov
1455b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany  uint64_t Pos = RedzoneSize();
1456800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Replace Alloca instructions with base+offset.
1457800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++) {
1458800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    AllocaInst *AI = AllocaVec[i];
1459800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t SizeInBytes = getAllocaSizeInBytes(AI);
1460800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StringRef Name = AI->getName();
1461800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    StackDescription << Pos << " " << SizeInBytes << " "
1462800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                     << Name.size() << " " << Name << " ";
1463800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    uint64_t AlignedSize = getAlignedAllocaSize(AI);
1464b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    assert((AlignedSize % RedzoneSize()) == 0);
1465f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    Value *NewAllocaPtr = IRB.CreateIntToPtr(
1466800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany            IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Pos)),
1467f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov            AI->getType());
14681afbb517965e29b07cb42e2335d5eadd87de6535Alexey Samsonov    replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB);
1469f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    AI->replaceAllUsesWith(NewAllocaPtr);
1470b9a12ea0fd92bfdb4c6eb5af333648a618f68686Kostya Serebryany    Pos += AlignedSize + RedzoneSize();
1471800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1472800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  assert(Pos == LocalStackSize);
1473800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
14743016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // The left-most redzone has enough space for at least 4 pointers.
14753016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the Magic value to redzone[0].
1476800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
1477800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
1478800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                  BasePlus0);
14793016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the frame description constant to redzone[1].
14803016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  Value *BasePlus1 = IRB.CreateIntToPtr(
14813016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, ASan.LongSize/8)),
14823016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IntptrPtrTy);
14839ce84c1c95c0153a2f33e188ce0db00770425f9eAlexey Samsonov  GlobalVariable *StackDescriptionGlobal =
1484a5f54f14435d881b10d8eb65e19fa42af95757e9Kostya Serebryany      createPrivateGlobalForString(*F.getParent(), StackDescription.str());
148559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal,
148659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov                                             IntptrTy);
1487800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  IRB.CreateStore(Description, BasePlus1);
14883016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  // Write the PC to redzone[2].
14893016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  Value *BasePlus2 = IRB.CreateIntToPtr(
14903016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy,
14913016056769639878b4f152838f0cf16d2e482339Kostya Serebryany                                                   2 * ASan.LongSize/8)),
14923016056769639878b4f152838f0cf16d2e482339Kostya Serebryany    IntptrPtrTy);
14933016056769639878b4f152838f0cf16d2e482339Kostya Serebryany  IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
1494800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1495800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Poison the stack redzones at the entry.
149659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
149759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  poisonRedZones(AllocaVec, IRB, ShadowBase, true);
1498800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1499800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  // Unpoison the stack before all ret instructions.
1500800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  for (size_t i = 0, n = RetVec.size(); i < n; i++) {
1501800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    Instruction *Ret = RetVec[i];
1502800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBuilder<> IRBRet(Ret);
1503800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Mark the current frame as retired.
1504800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
1505800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany                       BasePlus0);
1506800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    // Unpoison the stack.
150759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    poisonRedZones(AllocaVec, IRBRet, ShadowBase, false);
1508800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    if (DoStackMalloc) {
1509f3d4b35f24f4e54b2cb99e06f47a958e5557d01eKostya Serebryany      assert(StackMallocIdx >= 0);
1510f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // In use-after-return mode, mark the whole stack frame unaddressable.
1511671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany      if (StackMallocIdx <= 4) {
1512671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        // For small sizes inline the whole thing:
1513671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        // if LocalStackBase != OrigStackBase:
1514671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        //     memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
1515671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        //     **SavedFlagPtr(LocalStackBase) = 0
1516671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        // FIXME: if LocalStackBase != OrigStackBase don't call poisonRedZones.
1517671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        Value *Cmp = IRBRet.CreateICmpNE(LocalStackBase, OrigStackBase);
1518671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        TerminatorInst *PoisonTerm =
1519671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            SplitBlockAndInsertIfThen(cast<Instruction>(Cmp), false);
1520671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        IRBuilder<> IRBPoison(PoisonTerm);
1521671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        int ClassSize = kMinStackMallocSize << StackMallocIdx;
1522671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        SetShadowToStackAfterReturnInlined(IRBPoison, ShadowBase,
1523671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany                                           ClassSize >> Mapping.Scale);
1524671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
1525671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            LocalStackBase,
1526671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
1527671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        Value *SavedFlagPtr = IRBPoison.CreateLoad(
1528671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
1529671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        IRBPoison.CreateStore(
1530671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            Constant::getNullValue(IRBPoison.getInt8Ty()),
1531671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany            IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
1532671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany      } else {
1533671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        // For larger frames call __asan_stack_free_*.
1534671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany        IRBRet.CreateCall3(AsanStackFreeFunc[StackMallocIdx], LocalStackBase,
1535671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany                           ConstantInt::get(IntptrTy, LocalStackSize),
1536671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany                           OrigStackBase);
1537671c3ba921d5b8271307a8caa5e29f512d2e8e82Kostya Serebryany      }
1538f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov    } else if (HavePoisonedAllocas) {
1539f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // If we poisoned some allocas in llvm.lifetime analysis,
1540f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      // unpoison whole stack frame now.
1541f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      assert(LocalStackBase == OrigStackBase);
1542f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov      poisonAlloca(LocalStackBase, LocalStackSize, IRBRet, false);
1543800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany    }
1544800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany  }
1545800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany
1546bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  // We are done. Remove the old unused alloca instructions.
1547bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany  for (size_t i = 0, n = AllocaVec.size(); i < n; i++)
1548bd0052a0f26f04b8fcf59e8f645e5e33751e1f6eKostya Serebryany    AllocaVec[i]->eraseFromParent();
1549800e03f59896ef4b26d988f1878370bb5aeec0d8Kostya Serebryany}
1550f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov
155159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonovvoid FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
15524c71064129d1e5def34d74ee47c4f3beaa0a66dfJakub Staszak                                         IRBuilder<> &IRB, bool DoPoison) {
1553f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  // For now just insert the call to ASan runtime.
1554f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
1555f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  Value *SizeArg = ConstantInt::get(IntptrTy, Size);
1556f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov  IRB.CreateCall2(DoPoison ? AsanPoisonStackMemoryFunc
1557f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                           : AsanUnpoisonStackMemoryFunc,
1558f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov                  AddrArg, SizeArg);
1559f985f44b13681071e585acb7a5703a2c1c23b6ceAlexey Samsonov}
156059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
156159cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// Handling llvm.lifetime intrinsics for a given %alloca:
156259cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
156359cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
156459cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
156559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     could be poisoned by previous llvm.lifetime.end instruction, as the
156659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     variable may go in and out of scope several times, e.g. in loops).
156759cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov// (3) if we poisoned at least one %alloca in a function,
156859cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov//     unpoison the whole stack frame at function exit.
156959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov
15701c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey SamsonovAllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
15711c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
15721c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    // We're intested only in allocas we can handle.
15731c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return isInterestingAlloca(*AI) ? AI : 0;
15741c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // See if we've already calculated (or started to calculate) alloca for a
15751c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // given value.
15761c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
15771c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (I != AllocaForValue.end())
15781c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    return I->second;
15791c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // Store 0 while we're calculating alloca for value V to avoid
15801c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  // infinite recursion if the value references itself.
15811c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaForValue[V] = 0;
15821c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  AllocaInst *Res = 0;
15831c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (CastInst *CI = dyn_cast<CastInst>(V))
15841c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    Res = findAllocaForValue(CI->getOperand(0));
15851c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  else if (PHINode *PN = dyn_cast<PHINode>(V)) {
15861c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
15871c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      Value *IncValue = PN->getIncomingValue(i);
15881c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      // Allow self-referencing phi-nodes.
15891c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      if (IncValue == PN) continue;
15901c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      AllocaInst *IncValueAI = findAllocaForValue(IncValue);
15911c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      // AI for incoming values should exist and should all be equal.
15921c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      if (IncValueAI == 0 || (Res != 0 && IncValueAI != Res))
15931c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov        return 0;
15941c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov      Res = IncValueAI;
159559cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov    }
159659cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  }
15971c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov  if (Res != 0)
15981c8b825c4396ad9cd38f713d9e9a51adae1d4c4eAlexey Samsonov    AllocaForValue[V] = Res;
159959cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov  return Res;
160059cca13a80ed78ccbcdaa9bf20381bd48243f2f1Alexey Samsonov}
1601