]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
Merge ^/head r311460 through r311545.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Transforms / Instrumentation / AddressSanitizer.cpp
1 //===-- AddressSanitizer.cpp - memory error detector ------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 // Details of the algorithm:
12 //  http://code.google.com/p/address-sanitizer/wiki/AddressSanitizerAlgorithm
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/SetVector.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/TargetLibraryInfo.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/CallSite.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/IRBuilder.h"
34 #include "llvm/IR/InlineAsm.h"
35 #include "llvm/IR/InstVisitor.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/IR/MDBuilder.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/IR/Type.h"
41 #include "llvm/MC/MCSectionMachO.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/DataTypes.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/Endian.h"
46 #include "llvm/Support/SwapByteOrder.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/Transforms/Instrumentation.h"
49 #include "llvm/Transforms/Scalar.h"
50 #include "llvm/Transforms/Utils/ASanStackFrameLayout.h"
51 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
52 #include "llvm/Transforms/Utils/Cloning.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Transforms/Utils/ModuleUtils.h"
55 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
56 #include <algorithm>
57 #include <iomanip>
58 #include <limits>
59 #include <sstream>
60 #include <string>
61 #include <system_error>
62
63 using namespace llvm;
64
65 #define DEBUG_TYPE "asan"
66
67 static const uint64_t kDefaultShadowScale = 3;
68 static const uint64_t kDefaultShadowOffset32 = 1ULL << 29;
69 static const uint64_t kDefaultShadowOffset64 = 1ULL << 44;
70 static const uint64_t kDynamicShadowSentinel = ~(uint64_t)0;
71 static const uint64_t kIOSShadowOffset32 = 1ULL << 30;
72 static const uint64_t kIOSSimShadowOffset32 = 1ULL << 30;
73 static const uint64_t kIOSSimShadowOffset64 = kDefaultShadowOffset64;
74 static const uint64_t kSmallX86_64ShadowOffset = 0x7FFF8000;  // < 2G.
75 static const uint64_t kLinuxKasan_ShadowOffset64 = 0xdffffc0000000000;
76 static const uint64_t kPPC64_ShadowOffset64 = 1ULL << 41;
77 static const uint64_t kSystemZ_ShadowOffset64 = 1ULL << 52;
78 static const uint64_t kMIPS32_ShadowOffset32 = 0x0aaa0000;
79 static const uint64_t kMIPS64_ShadowOffset64 = 1ULL << 37;
80 static const uint64_t kAArch64_ShadowOffset64 = 1ULL << 36;
81 static const uint64_t kFreeBSD_ShadowOffset32 = 1ULL << 30;
82 static const uint64_t kFreeBSD_ShadowOffset64 = 1ULL << 46;
83 static const uint64_t kWindowsShadowOffset32 = 3ULL << 28;
84 // The shadow memory space is dynamically allocated.
85 static const uint64_t kWindowsShadowOffset64 = kDynamicShadowSentinel;
86
87 static const size_t kMinStackMallocSize = 1 << 6;   // 64B
88 static const size_t kMaxStackMallocSize = 1 << 16;  // 64K
89 static const uintptr_t kCurrentStackFrameMagic = 0x41B58AB3;
90 static const uintptr_t kRetiredStackFrameMagic = 0x45E0360E;
91
92 static const char *const kAsanModuleCtorName = "asan.module_ctor";
93 static const char *const kAsanModuleDtorName = "asan.module_dtor";
94 static const uint64_t kAsanCtorAndDtorPriority = 1;
95 static const char *const kAsanReportErrorTemplate = "__asan_report_";
96 static const char *const kAsanRegisterGlobalsName = "__asan_register_globals";
97 static const char *const kAsanUnregisterGlobalsName =
98     "__asan_unregister_globals";
99 static const char *const kAsanRegisterImageGlobalsName =
100   "__asan_register_image_globals";
101 static const char *const kAsanUnregisterImageGlobalsName =
102   "__asan_unregister_image_globals";
103 static const char *const kAsanPoisonGlobalsName = "__asan_before_dynamic_init";
104 static const char *const kAsanUnpoisonGlobalsName = "__asan_after_dynamic_init";
105 static const char *const kAsanInitName = "__asan_init";
106 static const char *const kAsanVersionCheckName =
107     "__asan_version_mismatch_check_v8";
108 static const char *const kAsanPtrCmp = "__sanitizer_ptr_cmp";
109 static const char *const kAsanPtrSub = "__sanitizer_ptr_sub";
110 static const char *const kAsanHandleNoReturnName = "__asan_handle_no_return";
111 static const int kMaxAsanStackMallocSizeClass = 10;
112 static const char *const kAsanStackMallocNameTemplate = "__asan_stack_malloc_";
113 static const char *const kAsanStackFreeNameTemplate = "__asan_stack_free_";
114 static const char *const kAsanGenPrefix = "__asan_gen_";
115 static const char *const kODRGenPrefix = "__odr_asan_gen_";
116 static const char *const kSanCovGenPrefix = "__sancov_gen_";
117 static const char *const kAsanSetShadowPrefix = "__asan_set_shadow_";
118 static const char *const kAsanPoisonStackMemoryName =
119     "__asan_poison_stack_memory";
120 static const char *const kAsanUnpoisonStackMemoryName =
121     "__asan_unpoison_stack_memory";
122 static const char *const kAsanGlobalsRegisteredFlagName =
123     "__asan_globals_registered";
124
125 static const char *const kAsanOptionDetectUseAfterReturn =
126     "__asan_option_detect_stack_use_after_return";
127
128 static const char *const kAsanShadowMemoryDynamicAddress =
129     "__asan_shadow_memory_dynamic_address";
130
131 static const char *const kAsanAllocaPoison = "__asan_alloca_poison";
132 static const char *const kAsanAllocasUnpoison = "__asan_allocas_unpoison";
133
134 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
135 static const size_t kNumberOfAccessSizes = 5;
136
137 static const unsigned kAllocaRzSize = 32;
138
139 // Command-line flags.
140 static cl::opt<bool> ClEnableKasan(
141     "asan-kernel", cl::desc("Enable KernelAddressSanitizer instrumentation"),
142     cl::Hidden, cl::init(false));
143 static cl::opt<bool> ClRecover(
144     "asan-recover",
145     cl::desc("Enable recovery mode (continue-after-error)."),
146     cl::Hidden, cl::init(false));
147
148 // This flag may need to be replaced with -f[no-]asan-reads.
149 static cl::opt<bool> ClInstrumentReads("asan-instrument-reads",
150                                        cl::desc("instrument read instructions"),
151                                        cl::Hidden, cl::init(true));
152 static cl::opt<bool> ClInstrumentWrites(
153     "asan-instrument-writes", cl::desc("instrument write instructions"),
154     cl::Hidden, cl::init(true));
155 static cl::opt<bool> ClInstrumentAtomics(
156     "asan-instrument-atomics",
157     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
158     cl::init(true));
159 static cl::opt<bool> ClAlwaysSlowPath(
160     "asan-always-slow-path",
161     cl::desc("use instrumentation with slow path for all accesses"), cl::Hidden,
162     cl::init(false));
163 static cl::opt<bool> ClForceDynamicShadow(
164     "asan-force-dynamic-shadow",
165     cl::desc("Load shadow address into a local variable for each function"),
166     cl::Hidden, cl::init(false));
167
168 // This flag limits the number of instructions to be instrumented
169 // in any given BB. Normally, this should be set to unlimited (INT_MAX),
170 // but due to http://llvm.org/bugs/show_bug.cgi?id=12652 we temporary
171 // set it to 10000.
172 static cl::opt<int> ClMaxInsnsToInstrumentPerBB(
173     "asan-max-ins-per-bb", cl::init(10000),
174     cl::desc("maximal number of instructions to instrument in any given BB"),
175     cl::Hidden);
176 // This flag may need to be replaced with -f[no]asan-stack.
177 static cl::opt<bool> ClStack("asan-stack", cl::desc("Handle stack memory"),
178                              cl::Hidden, cl::init(true));
179 static cl::opt<uint32_t> ClMaxInlinePoisoningSize(
180     "asan-max-inline-poisoning-size",
181     cl::desc(
182         "Inline shadow poisoning for blocks up to the given size in bytes."),
183     cl::Hidden, cl::init(64));
184 static cl::opt<bool> ClUseAfterReturn("asan-use-after-return",
185                                       cl::desc("Check stack-use-after-return"),
186                                       cl::Hidden, cl::init(true));
187 static cl::opt<bool> ClUseAfterScope("asan-use-after-scope",
188                                      cl::desc("Check stack-use-after-scope"),
189                                      cl::Hidden, cl::init(false));
190 // This flag may need to be replaced with -f[no]asan-globals.
191 static cl::opt<bool> ClGlobals("asan-globals",
192                                cl::desc("Handle global objects"), cl::Hidden,
193                                cl::init(true));
194 static cl::opt<bool> ClInitializers("asan-initialization-order",
195                                     cl::desc("Handle C++ initializer order"),
196                                     cl::Hidden, cl::init(true));
197 static cl::opt<bool> ClInvalidPointerPairs(
198     "asan-detect-invalid-pointer-pair",
199     cl::desc("Instrument <, <=, >, >=, - with pointer operands"), cl::Hidden,
200     cl::init(false));
201 static cl::opt<unsigned> ClRealignStack(
202     "asan-realign-stack",
203     cl::desc("Realign stack to the value of this flag (power of two)"),
204     cl::Hidden, cl::init(32));
205 static cl::opt<int> ClInstrumentationWithCallsThreshold(
206     "asan-instrumentation-with-call-threshold",
207     cl::desc(
208         "If the function being instrumented contains more than "
209         "this number of memory accesses, use callbacks instead of "
210         "inline checks (-1 means never use callbacks)."),
211     cl::Hidden, cl::init(7000));
212 static cl::opt<std::string> ClMemoryAccessCallbackPrefix(
213     "asan-memory-access-callback-prefix",
214     cl::desc("Prefix for memory access callbacks"), cl::Hidden,
215     cl::init("__asan_"));
216 static cl::opt<bool>
217     ClInstrumentDynamicAllocas("asan-instrument-dynamic-allocas",
218                                cl::desc("instrument dynamic allocas"),
219                                cl::Hidden, cl::init(true));
220 static cl::opt<bool> ClSkipPromotableAllocas(
221     "asan-skip-promotable-allocas",
222     cl::desc("Do not instrument promotable allocas"), cl::Hidden,
223     cl::init(true));
224
225 // These flags allow to change the shadow mapping.
226 // The shadow mapping looks like
227 //    Shadow = (Mem >> scale) + offset
228 static cl::opt<int> ClMappingScale("asan-mapping-scale",
229                                    cl::desc("scale of asan shadow mapping"),
230                                    cl::Hidden, cl::init(0));
231 static cl::opt<unsigned long long> ClMappingOffset(
232     "asan-mapping-offset",
233     cl::desc("offset of asan shadow mapping [EXPERIMENTAL]"), cl::Hidden,
234     cl::init(0));
235
236 // Optimization flags. Not user visible, used mostly for testing
237 // and benchmarking the tool.
238 static cl::opt<bool> ClOpt("asan-opt", cl::desc("Optimize instrumentation"),
239                            cl::Hidden, cl::init(true));
240 static cl::opt<bool> ClOptSameTemp(
241     "asan-opt-same-temp", cl::desc("Instrument the same temp just once"),
242     cl::Hidden, cl::init(true));
243 static cl::opt<bool> ClOptGlobals("asan-opt-globals",
244                                   cl::desc("Don't instrument scalar globals"),
245                                   cl::Hidden, cl::init(true));
246 static cl::opt<bool> ClOptStack(
247     "asan-opt-stack", cl::desc("Don't instrument scalar stack variables"),
248     cl::Hidden, cl::init(false));
249
250 static cl::opt<bool> ClDynamicAllocaStack(
251     "asan-stack-dynamic-alloca",
252     cl::desc("Use dynamic alloca to represent stack variables"), cl::Hidden,
253     cl::init(true));
254
255 static cl::opt<uint32_t> ClForceExperiment(
256     "asan-force-experiment",
257     cl::desc("Force optimization experiment (for testing)"), cl::Hidden,
258     cl::init(0));
259
260 static cl::opt<bool>
261     ClUsePrivateAliasForGlobals("asan-use-private-alias",
262                                 cl::desc("Use private aliases for global"
263                                          " variables"),
264                                 cl::Hidden, cl::init(false));
265
266 static cl::opt<bool>
267     ClUseMachOGlobalsSection("asan-globals-live-support",
268                              cl::desc("Use linker features to support dead "
269                                       "code stripping of globals "
270                                       "(Mach-O only)"),
271                              cl::Hidden, cl::init(true));
272
273 // Debug flags.
274 static cl::opt<int> ClDebug("asan-debug", cl::desc("debug"), cl::Hidden,
275                             cl::init(0));
276 static cl::opt<int> ClDebugStack("asan-debug-stack", cl::desc("debug stack"),
277                                  cl::Hidden, cl::init(0));
278 static cl::opt<std::string> ClDebugFunc("asan-debug-func", cl::Hidden,
279                                         cl::desc("Debug func"));
280 static cl::opt<int> ClDebugMin("asan-debug-min", cl::desc("Debug min inst"),
281                                cl::Hidden, cl::init(-1));
282 static cl::opt<int> ClDebugMax("asan-debug-max", cl::desc("Debug max inst"),
283                                cl::Hidden, cl::init(-1));
284
285 STATISTIC(NumInstrumentedReads, "Number of instrumented reads");
286 STATISTIC(NumInstrumentedWrites, "Number of instrumented writes");
287 STATISTIC(NumOptimizedAccessesToGlobalVar,
288           "Number of optimized accesses to global vars");
289 STATISTIC(NumOptimizedAccessesToStackVar,
290           "Number of optimized accesses to stack vars");
291
292 namespace {
293 /// Frontend-provided metadata for source location.
294 struct LocationMetadata {
295   StringRef Filename;
296   int LineNo;
297   int ColumnNo;
298
299   LocationMetadata() : Filename(), LineNo(0), ColumnNo(0) {}
300
301   bool empty() const { return Filename.empty(); }
302
303   void parse(MDNode *MDN) {
304     assert(MDN->getNumOperands() == 3);
305     MDString *DIFilename = cast<MDString>(MDN->getOperand(0));
306     Filename = DIFilename->getString();
307     LineNo =
308         mdconst::extract<ConstantInt>(MDN->getOperand(1))->getLimitedValue();
309     ColumnNo =
310         mdconst::extract<ConstantInt>(MDN->getOperand(2))->getLimitedValue();
311   }
312 };
313
314 /// Frontend-provided metadata for global variables.
315 class GlobalsMetadata {
316  public:
317   struct Entry {
318     Entry() : SourceLoc(), Name(), IsDynInit(false), IsBlacklisted(false) {}
319     LocationMetadata SourceLoc;
320     StringRef Name;
321     bool IsDynInit;
322     bool IsBlacklisted;
323   };
324
325   GlobalsMetadata() : inited_(false) {}
326
327   void reset() {
328     inited_ = false;
329     Entries.clear();
330   }
331
332   void init(Module &M) {
333     assert(!inited_);
334     inited_ = true;
335     NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
336     if (!Globals) return;
337     for (auto MDN : Globals->operands()) {
338       // Metadata node contains the global and the fields of "Entry".
339       assert(MDN->getNumOperands() == 5);
340       auto *GV = mdconst::extract_or_null<GlobalVariable>(MDN->getOperand(0));
341       // The optimizer may optimize away a global entirely.
342       if (!GV) continue;
343       // We can already have an entry for GV if it was merged with another
344       // global.
345       Entry &E = Entries[GV];
346       if (auto *Loc = cast_or_null<MDNode>(MDN->getOperand(1)))
347         E.SourceLoc.parse(Loc);
348       if (auto *Name = cast_or_null<MDString>(MDN->getOperand(2)))
349         E.Name = Name->getString();
350       ConstantInt *IsDynInit =
351           mdconst::extract<ConstantInt>(MDN->getOperand(3));
352       E.IsDynInit |= IsDynInit->isOne();
353       ConstantInt *IsBlacklisted =
354           mdconst::extract<ConstantInt>(MDN->getOperand(4));
355       E.IsBlacklisted |= IsBlacklisted->isOne();
356     }
357   }
358
359   /// Returns metadata entry for a given global.
360   Entry get(GlobalVariable *G) const {
361     auto Pos = Entries.find(G);
362     return (Pos != Entries.end()) ? Pos->second : Entry();
363   }
364
365  private:
366   bool inited_;
367   DenseMap<GlobalVariable *, Entry> Entries;
368 };
369
370 /// This struct defines the shadow mapping using the rule:
371 ///   shadow = (mem >> Scale) ADD-or-OR Offset.
372 struct ShadowMapping {
373   int Scale;
374   uint64_t Offset;
375   bool OrShadowOffset;
376 };
377
378 static ShadowMapping getShadowMapping(Triple &TargetTriple, int LongSize,
379                                       bool IsKasan) {
380   bool IsAndroid = TargetTriple.isAndroid();
381   bool IsIOS = TargetTriple.isiOS() || TargetTriple.isWatchOS();
382   bool IsFreeBSD = TargetTriple.isOSFreeBSD();
383   bool IsLinux = TargetTriple.isOSLinux();
384   bool IsPPC64 = TargetTriple.getArch() == llvm::Triple::ppc64 ||
385                  TargetTriple.getArch() == llvm::Triple::ppc64le;
386   bool IsSystemZ = TargetTriple.getArch() == llvm::Triple::systemz;
387   bool IsX86 = TargetTriple.getArch() == llvm::Triple::x86;
388   bool IsX86_64 = TargetTriple.getArch() == llvm::Triple::x86_64;
389   bool IsMIPS32 = TargetTriple.getArch() == llvm::Triple::mips ||
390                   TargetTriple.getArch() == llvm::Triple::mipsel;
391   bool IsMIPS64 = TargetTriple.getArch() == llvm::Triple::mips64 ||
392                   TargetTriple.getArch() == llvm::Triple::mips64el;
393   bool IsAArch64 = TargetTriple.getArch() == llvm::Triple::aarch64;
394   bool IsWindows = TargetTriple.isOSWindows();
395
396   ShadowMapping Mapping;
397
398   if (LongSize == 32) {
399     // Android is always PIE, which means that the beginning of the address
400     // space is always available.
401     if (IsAndroid)
402       Mapping.Offset = 0;
403     else if (IsMIPS32)
404       Mapping.Offset = kMIPS32_ShadowOffset32;
405     else if (IsFreeBSD)
406       Mapping.Offset = kFreeBSD_ShadowOffset32;
407     else if (IsIOS)
408       // If we're targeting iOS and x86, the binary is built for iOS simulator.
409       Mapping.Offset = IsX86 ? kIOSSimShadowOffset32 : kIOSShadowOffset32;
410     else if (IsWindows)
411       Mapping.Offset = kWindowsShadowOffset32;
412     else
413       Mapping.Offset = kDefaultShadowOffset32;
414   } else {  // LongSize == 64
415     if (IsPPC64)
416       Mapping.Offset = kPPC64_ShadowOffset64;
417     else if (IsSystemZ)
418       Mapping.Offset = kSystemZ_ShadowOffset64;
419     else if (IsFreeBSD)
420       Mapping.Offset = kFreeBSD_ShadowOffset64;
421     else if (IsLinux && IsX86_64) {
422       if (IsKasan)
423         Mapping.Offset = kLinuxKasan_ShadowOffset64;
424       else
425         Mapping.Offset = kSmallX86_64ShadowOffset;
426     } else if (IsWindows && IsX86_64) {
427       Mapping.Offset = kWindowsShadowOffset64;
428     } else if (IsMIPS64)
429       Mapping.Offset = kMIPS64_ShadowOffset64;
430     else if (IsIOS)
431       // If we're targeting iOS and x86, the binary is built for iOS simulator.
432       // We are using dynamic shadow offset on the 64-bit devices.
433       Mapping.Offset =
434         IsX86_64 ? kIOSSimShadowOffset64 : kDynamicShadowSentinel;
435     else if (IsAArch64)
436       Mapping.Offset = kAArch64_ShadowOffset64;
437     else
438       Mapping.Offset = kDefaultShadowOffset64;
439   }
440
441   if (ClForceDynamicShadow) {
442     Mapping.Offset = kDynamicShadowSentinel;
443   }
444
445   Mapping.Scale = kDefaultShadowScale;
446   if (ClMappingScale.getNumOccurrences() > 0) {
447     Mapping.Scale = ClMappingScale;
448   }
449
450   if (ClMappingOffset.getNumOccurrences() > 0) {
451     Mapping.Offset = ClMappingOffset;
452   }
453
454   // OR-ing shadow offset if more efficient (at least on x86) if the offset
455   // is a power of two, but on ppc64 we have to use add since the shadow
456   // offset is not necessary 1/8-th of the address space.  On SystemZ,
457   // we could OR the constant in a single instruction, but it's more
458   // efficient to load it once and use indexed addressing.
459   Mapping.OrShadowOffset = !IsAArch64 && !IsPPC64 && !IsSystemZ
460                            && !(Mapping.Offset & (Mapping.Offset - 1))
461                            && Mapping.Offset != kDynamicShadowSentinel;
462
463   return Mapping;
464 }
465
466 static size_t RedzoneSizeForScale(int MappingScale) {
467   // Redzone used for stack and globals is at least 32 bytes.
468   // For scales 6 and 7, the redzone has to be 64 and 128 bytes respectively.
469   return std::max(32U, 1U << MappingScale);
470 }
471
472 /// AddressSanitizer: instrument the code in module to find memory bugs.
473 struct AddressSanitizer : public FunctionPass {
474   explicit AddressSanitizer(bool CompileKernel = false, bool Recover = false,
475                             bool UseAfterScope = false)
476       : FunctionPass(ID), CompileKernel(CompileKernel || ClEnableKasan),
477         Recover(Recover || ClRecover),
478         UseAfterScope(UseAfterScope || ClUseAfterScope),
479         LocalDynamicShadow(nullptr) {
480     initializeAddressSanitizerPass(*PassRegistry::getPassRegistry());
481   }
482   StringRef getPassName() const override {
483     return "AddressSanitizerFunctionPass";
484   }
485   void getAnalysisUsage(AnalysisUsage &AU) const override {
486     AU.addRequired<DominatorTreeWrapperPass>();
487     AU.addRequired<TargetLibraryInfoWrapperPass>();
488   }
489   uint64_t getAllocaSizeInBytes(const AllocaInst &AI) const {
490     uint64_t ArraySize = 1;
491     if (AI.isArrayAllocation()) {
492       const ConstantInt *CI = dyn_cast<ConstantInt>(AI.getArraySize());
493       assert(CI && "non-constant array size");
494       ArraySize = CI->getZExtValue();
495     }
496     Type *Ty = AI.getAllocatedType();
497     uint64_t SizeInBytes =
498         AI.getModule()->getDataLayout().getTypeAllocSize(Ty);
499     return SizeInBytes * ArraySize;
500   }
501   /// Check if we want (and can) handle this alloca.
502   bool isInterestingAlloca(const AllocaInst &AI);
503
504   /// If it is an interesting memory access, return the PointerOperand
505   /// and set IsWrite/Alignment. Otherwise return nullptr.
506   /// MaybeMask is an output parameter for the mask Value, if we're looking at a
507   /// masked load/store.
508   Value *isInterestingMemoryAccess(Instruction *I, bool *IsWrite,
509                                    uint64_t *TypeSize, unsigned *Alignment,
510                                    Value **MaybeMask = nullptr);
511   void instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis, Instruction *I,
512                      bool UseCalls, const DataLayout &DL);
513   void instrumentPointerComparisonOrSubtraction(Instruction *I);
514   void instrumentAddress(Instruction *OrigIns, Instruction *InsertBefore,
515                          Value *Addr, uint32_t TypeSize, bool IsWrite,
516                          Value *SizeArgument, bool UseCalls, uint32_t Exp);
517   void instrumentUnusualSizeOrAlignment(Instruction *I,
518                                         Instruction *InsertBefore, Value *Addr,
519                                         uint32_t TypeSize, bool IsWrite,
520                                         Value *SizeArgument, bool UseCalls,
521                                         uint32_t Exp);
522   Value *createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
523                            Value *ShadowValue, uint32_t TypeSize);
524   Instruction *generateCrashCode(Instruction *InsertBefore, Value *Addr,
525                                  bool IsWrite, size_t AccessSizeIndex,
526                                  Value *SizeArgument, uint32_t Exp);
527   void instrumentMemIntrinsic(MemIntrinsic *MI);
528   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
529   bool runOnFunction(Function &F) override;
530   bool maybeInsertAsanInitAtFunctionEntry(Function &F);
531   void maybeInsertDynamicShadowAtFunctionEntry(Function &F);
532   void markEscapedLocalAllocas(Function &F);
533   bool doInitialization(Module &M) override;
534   bool doFinalization(Module &M) override;
535   static char ID;  // Pass identification, replacement for typeid
536
537   DominatorTree &getDominatorTree() const { return *DT; }
538
539  private:
540   void initializeCallbacks(Module &M);
541
542   bool LooksLikeCodeInBug11395(Instruction *I);
543   bool GlobalIsLinkerInitialized(GlobalVariable *G);
544   bool isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis, Value *Addr,
545                     uint64_t TypeSize) const;
546
547   /// Helper to cleanup per-function state.
548   struct FunctionStateRAII {
549     AddressSanitizer *Pass;
550     FunctionStateRAII(AddressSanitizer *Pass) : Pass(Pass) {
551       assert(Pass->ProcessedAllocas.empty() &&
552              "last pass forgot to clear cache");
553       assert(!Pass->LocalDynamicShadow);
554     }
555     ~FunctionStateRAII() {
556       Pass->LocalDynamicShadow = nullptr;
557       Pass->ProcessedAllocas.clear();
558     }
559   };
560
561   LLVMContext *C;
562   Triple TargetTriple;
563   int LongSize;
564   bool CompileKernel;
565   bool Recover;
566   bool UseAfterScope;
567   Type *IntptrTy;
568   ShadowMapping Mapping;
569   DominatorTree *DT;
570   Function *AsanCtorFunction = nullptr;
571   Function *AsanInitFunction = nullptr;
572   Function *AsanHandleNoReturnFunc;
573   Function *AsanPtrCmpFunction, *AsanPtrSubFunction;
574   // This array is indexed by AccessIsWrite, Experiment and log2(AccessSize).
575   Function *AsanErrorCallback[2][2][kNumberOfAccessSizes];
576   Function *AsanMemoryAccessCallback[2][2][kNumberOfAccessSizes];
577   // This array is indexed by AccessIsWrite and Experiment.
578   Function *AsanErrorCallbackSized[2][2];
579   Function *AsanMemoryAccessCallbackSized[2][2];
580   Function *AsanMemmove, *AsanMemcpy, *AsanMemset;
581   InlineAsm *EmptyAsm;
582   Value *LocalDynamicShadow;
583   GlobalsMetadata GlobalsMD;
584   DenseMap<const AllocaInst *, bool> ProcessedAllocas;
585
586   friend struct FunctionStackPoisoner;
587 };
588
589 class AddressSanitizerModule : public ModulePass {
590  public:
591   explicit AddressSanitizerModule(bool CompileKernel = false,
592                                   bool Recover = false)
593       : ModulePass(ID), CompileKernel(CompileKernel || ClEnableKasan),
594         Recover(Recover || ClRecover) {}
595   bool runOnModule(Module &M) override;
596   static char ID;  // Pass identification, replacement for typeid
597   StringRef getPassName() const override { return "AddressSanitizerModule"; }
598
599 private:
600   void initializeCallbacks(Module &M);
601
602   bool InstrumentGlobals(IRBuilder<> &IRB, Module &M);
603   bool ShouldInstrumentGlobal(GlobalVariable *G);
604   bool ShouldUseMachOGlobalsSection() const;
605   StringRef getGlobalMetadataSection() const;
606   void poisonOneInitializer(Function &GlobalInit, GlobalValue *ModuleName);
607   void createInitializerPoisonCalls(Module &M, GlobalValue *ModuleName);
608   size_t MinRedzoneSizeForGlobal() const {
609     return RedzoneSizeForScale(Mapping.Scale);
610   }
611
612   GlobalsMetadata GlobalsMD;
613   bool CompileKernel;
614   bool Recover;
615   Type *IntptrTy;
616   LLVMContext *C;
617   Triple TargetTriple;
618   ShadowMapping Mapping;
619   Function *AsanPoisonGlobals;
620   Function *AsanUnpoisonGlobals;
621   Function *AsanRegisterGlobals;
622   Function *AsanUnregisterGlobals;
623   Function *AsanRegisterImageGlobals;
624   Function *AsanUnregisterImageGlobals;
625 };
626
627 // Stack poisoning does not play well with exception handling.
628 // When an exception is thrown, we essentially bypass the code
629 // that unpoisones the stack. This is why the run-time library has
630 // to intercept __cxa_throw (as well as longjmp, etc) and unpoison the entire
631 // stack in the interceptor. This however does not work inside the
632 // actual function which catches the exception. Most likely because the
633 // compiler hoists the load of the shadow value somewhere too high.
634 // This causes asan to report a non-existing bug on 453.povray.
635 // It sounds like an LLVM bug.
636 struct FunctionStackPoisoner : public InstVisitor<FunctionStackPoisoner> {
637   Function &F;
638   AddressSanitizer &ASan;
639   DIBuilder DIB;
640   LLVMContext *C;
641   Type *IntptrTy;
642   Type *IntptrPtrTy;
643   ShadowMapping Mapping;
644
645   SmallVector<AllocaInst *, 16> AllocaVec;
646   SmallVector<AllocaInst *, 16> StaticAllocasToMoveUp;
647   SmallVector<Instruction *, 8> RetVec;
648   unsigned StackAlignment;
649
650   Function *AsanStackMallocFunc[kMaxAsanStackMallocSizeClass + 1],
651       *AsanStackFreeFunc[kMaxAsanStackMallocSizeClass + 1];
652   Function *AsanSetShadowFunc[0x100] = {};
653   Function *AsanPoisonStackMemoryFunc, *AsanUnpoisonStackMemoryFunc;
654   Function *AsanAllocaPoisonFunc, *AsanAllocasUnpoisonFunc;
655
656   // Stores a place and arguments of poisoning/unpoisoning call for alloca.
657   struct AllocaPoisonCall {
658     IntrinsicInst *InsBefore;
659     AllocaInst *AI;
660     uint64_t Size;
661     bool DoPoison;
662   };
663   SmallVector<AllocaPoisonCall, 8> DynamicAllocaPoisonCallVec;
664   SmallVector<AllocaPoisonCall, 8> StaticAllocaPoisonCallVec;
665
666   SmallVector<AllocaInst *, 1> DynamicAllocaVec;
667   SmallVector<IntrinsicInst *, 1> StackRestoreVec;
668   AllocaInst *DynamicAllocaLayout = nullptr;
669   IntrinsicInst *LocalEscapeCall = nullptr;
670
671   // Maps Value to an AllocaInst from which the Value is originated.
672   typedef DenseMap<Value *, AllocaInst *> AllocaForValueMapTy;
673   AllocaForValueMapTy AllocaForValue;
674
675   bool HasNonEmptyInlineAsm = false;
676   bool HasReturnsTwiceCall = false;
677   std::unique_ptr<CallInst> EmptyInlineAsm;
678
679   FunctionStackPoisoner(Function &F, AddressSanitizer &ASan)
680       : F(F),
681         ASan(ASan),
682         DIB(*F.getParent(), /*AllowUnresolved*/ false),
683         C(ASan.C),
684         IntptrTy(ASan.IntptrTy),
685         IntptrPtrTy(PointerType::get(IntptrTy, 0)),
686         Mapping(ASan.Mapping),
687         StackAlignment(1 << Mapping.Scale),
688         EmptyInlineAsm(CallInst::Create(ASan.EmptyAsm)) {}
689
690   bool runOnFunction() {
691     if (!ClStack) return false;
692     // Collect alloca, ret, lifetime instructions etc.
693     for (BasicBlock *BB : depth_first(&F.getEntryBlock())) visit(*BB);
694
695     if (AllocaVec.empty() && DynamicAllocaVec.empty()) return false;
696
697     initializeCallbacks(*F.getParent());
698
699     processDynamicAllocas();
700     processStaticAllocas();
701
702     if (ClDebugStack) {
703       DEBUG(dbgs() << F);
704     }
705     return true;
706   }
707
708   // Finds all Alloca instructions and puts
709   // poisoned red zones around all of them.
710   // Then unpoison everything back before the function returns.
711   void processStaticAllocas();
712   void processDynamicAllocas();
713
714   void createDynamicAllocasInitStorage();
715
716   // ----------------------- Visitors.
717   /// \brief Collect all Ret instructions.
718   void visitReturnInst(ReturnInst &RI) { RetVec.push_back(&RI); }
719
720   /// \brief Collect all Resume instructions.
721   void visitResumeInst(ResumeInst &RI) { RetVec.push_back(&RI); }
722
723   /// \brief Collect all CatchReturnInst instructions.
724   void visitCleanupReturnInst(CleanupReturnInst &CRI) { RetVec.push_back(&CRI); }
725
726   void unpoisonDynamicAllocasBeforeInst(Instruction *InstBefore,
727                                         Value *SavedStack) {
728     IRBuilder<> IRB(InstBefore);
729     Value *DynamicAreaPtr = IRB.CreatePtrToInt(SavedStack, IntptrTy);
730     // When we insert _asan_allocas_unpoison before @llvm.stackrestore, we
731     // need to adjust extracted SP to compute the address of the most recent
732     // alloca. We have a special @llvm.get.dynamic.area.offset intrinsic for
733     // this purpose.
734     if (!isa<ReturnInst>(InstBefore)) {
735       Function *DynamicAreaOffsetFunc = Intrinsic::getDeclaration(
736           InstBefore->getModule(), Intrinsic::get_dynamic_area_offset,
737           {IntptrTy});
738
739       Value *DynamicAreaOffset = IRB.CreateCall(DynamicAreaOffsetFunc, {});
740
741       DynamicAreaPtr = IRB.CreateAdd(IRB.CreatePtrToInt(SavedStack, IntptrTy),
742                                      DynamicAreaOffset);
743     }
744
745     IRB.CreateCall(AsanAllocasUnpoisonFunc,
746                    {IRB.CreateLoad(DynamicAllocaLayout), DynamicAreaPtr});
747   }
748
749   // Unpoison dynamic allocas redzones.
750   void unpoisonDynamicAllocas() {
751     for (auto &Ret : RetVec)
752       unpoisonDynamicAllocasBeforeInst(Ret, DynamicAllocaLayout);
753
754     for (auto &StackRestoreInst : StackRestoreVec)
755       unpoisonDynamicAllocasBeforeInst(StackRestoreInst,
756                                        StackRestoreInst->getOperand(0));
757   }
758
759   // Deploy and poison redzones around dynamic alloca call. To do this, we
760   // should replace this call with another one with changed parameters and
761   // replace all its uses with new address, so
762   //   addr = alloca type, old_size, align
763   // is replaced by
764   //   new_size = (old_size + additional_size) * sizeof(type)
765   //   tmp = alloca i8, new_size, max(align, 32)
766   //   addr = tmp + 32 (first 32 bytes are for the left redzone).
767   // Additional_size is added to make new memory allocation contain not only
768   // requested memory, but also left, partial and right redzones.
769   void handleDynamicAllocaCall(AllocaInst *AI);
770
771   /// \brief Collect Alloca instructions we want (and can) handle.
772   void visitAllocaInst(AllocaInst &AI) {
773     if (!ASan.isInterestingAlloca(AI)) {
774       if (AI.isStaticAlloca()) {
775         // Skip over allocas that are present *before* the first instrumented
776         // alloca, we don't want to move those around.
777         if (AllocaVec.empty())
778           return;
779
780         StaticAllocasToMoveUp.push_back(&AI);
781       }
782       return;
783     }
784
785     StackAlignment = std::max(StackAlignment, AI.getAlignment());
786     if (!AI.isStaticAlloca())
787       DynamicAllocaVec.push_back(&AI);
788     else
789       AllocaVec.push_back(&AI);
790   }
791
792   /// \brief Collect lifetime intrinsic calls to check for use-after-scope
793   /// errors.
794   void visitIntrinsicInst(IntrinsicInst &II) {
795     Intrinsic::ID ID = II.getIntrinsicID();
796     if (ID == Intrinsic::stackrestore) StackRestoreVec.push_back(&II);
797     if (ID == Intrinsic::localescape) LocalEscapeCall = &II;
798     if (!ASan.UseAfterScope)
799       return;
800     if (ID != Intrinsic::lifetime_start && ID != Intrinsic::lifetime_end)
801       return;
802     // Found lifetime intrinsic, add ASan instrumentation if necessary.
803     ConstantInt *Size = dyn_cast<ConstantInt>(II.getArgOperand(0));
804     // If size argument is undefined, don't do anything.
805     if (Size->isMinusOne()) return;
806     // Check that size doesn't saturate uint64_t and can
807     // be stored in IntptrTy.
808     const uint64_t SizeValue = Size->getValue().getLimitedValue();
809     if (SizeValue == ~0ULL ||
810         !ConstantInt::isValueValidForType(IntptrTy, SizeValue))
811       return;
812     // Find alloca instruction that corresponds to llvm.lifetime argument.
813     AllocaInst *AI = findAllocaForValue(II.getArgOperand(1));
814     if (!AI || !ASan.isInterestingAlloca(*AI))
815       return;
816     bool DoPoison = (ID == Intrinsic::lifetime_end);
817     AllocaPoisonCall APC = {&II, AI, SizeValue, DoPoison};
818     if (AI->isStaticAlloca())
819       StaticAllocaPoisonCallVec.push_back(APC);
820     else if (ClInstrumentDynamicAllocas)
821       DynamicAllocaPoisonCallVec.push_back(APC);
822   }
823
824   void visitCallSite(CallSite CS) {
825     Instruction *I = CS.getInstruction();
826     if (CallInst *CI = dyn_cast<CallInst>(I)) {
827       HasNonEmptyInlineAsm |=
828           CI->isInlineAsm() && !CI->isIdenticalTo(EmptyInlineAsm.get());
829       HasReturnsTwiceCall |= CI->canReturnTwice();
830     }
831   }
832
833   // ---------------------- Helpers.
834   void initializeCallbacks(Module &M);
835
836   bool doesDominateAllExits(const Instruction *I) const {
837     for (auto Ret : RetVec) {
838       if (!ASan.getDominatorTree().dominates(I, Ret)) return false;
839     }
840     return true;
841   }
842
843   /// Finds alloca where the value comes from.
844   AllocaInst *findAllocaForValue(Value *V);
845
846   // Copies bytes from ShadowBytes into shadow memory for indexes where
847   // ShadowMask is not zero. If ShadowMask[i] is zero, we assume that
848   // ShadowBytes[i] is constantly zero and doesn't need to be overwritten.
849   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
850                     IRBuilder<> &IRB, Value *ShadowBase);
851   void copyToShadow(ArrayRef<uint8_t> ShadowMask, ArrayRef<uint8_t> ShadowBytes,
852                     size_t Begin, size_t End, IRBuilder<> &IRB,
853                     Value *ShadowBase);
854   void copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
855                           ArrayRef<uint8_t> ShadowBytes, size_t Begin,
856                           size_t End, IRBuilder<> &IRB, Value *ShadowBase);
857
858   void poisonAlloca(Value *V, uint64_t Size, IRBuilder<> &IRB, bool DoPoison);
859
860   Value *createAllocaForLayout(IRBuilder<> &IRB, const ASanStackFrameLayout &L,
861                                bool Dynamic);
862   PHINode *createPHI(IRBuilder<> &IRB, Value *Cond, Value *ValueIfTrue,
863                      Instruction *ThenTerm, Value *ValueIfFalse);
864 };
865
866 } // anonymous namespace
867
868 char AddressSanitizer::ID = 0;
869 INITIALIZE_PASS_BEGIN(
870     AddressSanitizer, "asan",
871     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
872     false)
873 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
874 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
875 INITIALIZE_PASS_END(
876     AddressSanitizer, "asan",
877     "AddressSanitizer: detects use-after-free and out-of-bounds bugs.", false,
878     false)
879 FunctionPass *llvm::createAddressSanitizerFunctionPass(bool CompileKernel,
880                                                        bool Recover,
881                                                        bool UseAfterScope) {
882   assert(!CompileKernel || Recover);
883   return new AddressSanitizer(CompileKernel, Recover, UseAfterScope);
884 }
885
886 char AddressSanitizerModule::ID = 0;
887 INITIALIZE_PASS(
888     AddressSanitizerModule, "asan-module",
889     "AddressSanitizer: detects use-after-free and out-of-bounds bugs."
890     "ModulePass",
891     false, false)
892 ModulePass *llvm::createAddressSanitizerModulePass(bool CompileKernel,
893                                                    bool Recover) {
894   assert(!CompileKernel || Recover);
895   return new AddressSanitizerModule(CompileKernel, Recover);
896 }
897
898 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
899   size_t Res = countTrailingZeros(TypeSize / 8);
900   assert(Res < kNumberOfAccessSizes);
901   return Res;
902 }
903
904 // \brief Create a constant for Str so that we can pass it to the run-time lib.
905 static GlobalVariable *createPrivateGlobalForString(Module &M, StringRef Str,
906                                                     bool AllowMerging) {
907   Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
908   // We use private linkage for module-local strings. If they can be merged
909   // with another one, we set the unnamed_addr attribute.
910   GlobalVariable *GV =
911       new GlobalVariable(M, StrConst->getType(), true,
912                          GlobalValue::PrivateLinkage, StrConst, kAsanGenPrefix);
913   if (AllowMerging) GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
914   GV->setAlignment(1);  // Strings may not be merged w/o setting align 1.
915   return GV;
916 }
917
918 /// \brief Create a global describing a source location.
919 static GlobalVariable *createPrivateGlobalForSourceLoc(Module &M,
920                                                        LocationMetadata MD) {
921   Constant *LocData[] = {
922       createPrivateGlobalForString(M, MD.Filename, true),
923       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.LineNo),
924       ConstantInt::get(Type::getInt32Ty(M.getContext()), MD.ColumnNo),
925   };
926   auto LocStruct = ConstantStruct::getAnon(LocData);
927   auto GV = new GlobalVariable(M, LocStruct->getType(), true,
928                                GlobalValue::PrivateLinkage, LocStruct,
929                                kAsanGenPrefix);
930   GV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
931   return GV;
932 }
933
934 /// \brief Check if \p G has been created by a trusted compiler pass.
935 static bool GlobalWasGeneratedByCompiler(GlobalVariable *G) {
936   // Do not instrument asan globals.
937   if (G->getName().startswith(kAsanGenPrefix) ||
938       G->getName().startswith(kSanCovGenPrefix) ||
939       G->getName().startswith(kODRGenPrefix))
940     return true;
941
942   // Do not instrument gcov counter arrays.
943   if (G->getName() == "__llvm_gcov_ctr")
944     return true;
945
946   return false;
947 }
948
949 Value *AddressSanitizer::memToShadow(Value *Shadow, IRBuilder<> &IRB) {
950   // Shadow >> scale
951   Shadow = IRB.CreateLShr(Shadow, Mapping.Scale);
952   if (Mapping.Offset == 0) return Shadow;
953   // (Shadow >> scale) | offset
954   Value *ShadowBase;
955   if (LocalDynamicShadow)
956     ShadowBase = LocalDynamicShadow;
957   else
958     ShadowBase = ConstantInt::get(IntptrTy, Mapping.Offset);
959   if (Mapping.OrShadowOffset)
960     return IRB.CreateOr(Shadow, ShadowBase);
961   else
962     return IRB.CreateAdd(Shadow, ShadowBase);
963 }
964
965 // Instrument memset/memmove/memcpy
966 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
967   IRBuilder<> IRB(MI);
968   if (isa<MemTransferInst>(MI)) {
969     IRB.CreateCall(
970         isa<MemMoveInst>(MI) ? AsanMemmove : AsanMemcpy,
971         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
972          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
973          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
974   } else if (isa<MemSetInst>(MI)) {
975     IRB.CreateCall(
976         AsanMemset,
977         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
978          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
979          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
980   }
981   MI->eraseFromParent();
982 }
983
984 /// Check if we want (and can) handle this alloca.
985 bool AddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
986   auto PreviouslySeenAllocaInfo = ProcessedAllocas.find(&AI);
987
988   if (PreviouslySeenAllocaInfo != ProcessedAllocas.end())
989     return PreviouslySeenAllocaInfo->getSecond();
990
991   bool IsInteresting =
992       (AI.getAllocatedType()->isSized() &&
993        // alloca() may be called with 0 size, ignore it.
994        ((!AI.isStaticAlloca()) || getAllocaSizeInBytes(AI) > 0) &&
995        // We are only interested in allocas not promotable to registers.
996        // Promotable allocas are common under -O0.
997        (!ClSkipPromotableAllocas || !isAllocaPromotable(&AI)) &&
998        // inalloca allocas are not treated as static, and we don't want
999        // dynamic alloca instrumentation for them as well.
1000        !AI.isUsedWithInAlloca());
1001
1002   ProcessedAllocas[&AI] = IsInteresting;
1003   return IsInteresting;
1004 }
1005
1006 Value *AddressSanitizer::isInterestingMemoryAccess(Instruction *I,
1007                                                    bool *IsWrite,
1008                                                    uint64_t *TypeSize,
1009                                                    unsigned *Alignment,
1010                                                    Value **MaybeMask) {
1011   // Skip memory accesses inserted by another instrumentation.
1012   if (I->getMetadata("nosanitize")) return nullptr;
1013
1014   // Do not instrument the load fetching the dynamic shadow address.
1015   if (LocalDynamicShadow == I)
1016     return nullptr;
1017
1018   Value *PtrOperand = nullptr;
1019   const DataLayout &DL = I->getModule()->getDataLayout();
1020   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1021     if (!ClInstrumentReads) return nullptr;
1022     *IsWrite = false;
1023     *TypeSize = DL.getTypeStoreSizeInBits(LI->getType());
1024     *Alignment = LI->getAlignment();
1025     PtrOperand = LI->getPointerOperand();
1026   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1027     if (!ClInstrumentWrites) return nullptr;
1028     *IsWrite = true;
1029     *TypeSize = DL.getTypeStoreSizeInBits(SI->getValueOperand()->getType());
1030     *Alignment = SI->getAlignment();
1031     PtrOperand = SI->getPointerOperand();
1032   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
1033     if (!ClInstrumentAtomics) return nullptr;
1034     *IsWrite = true;
1035     *TypeSize = DL.getTypeStoreSizeInBits(RMW->getValOperand()->getType());
1036     *Alignment = 0;
1037     PtrOperand = RMW->getPointerOperand();
1038   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
1039     if (!ClInstrumentAtomics) return nullptr;
1040     *IsWrite = true;
1041     *TypeSize = DL.getTypeStoreSizeInBits(XCHG->getCompareOperand()->getType());
1042     *Alignment = 0;
1043     PtrOperand = XCHG->getPointerOperand();
1044   } else if (auto CI = dyn_cast<CallInst>(I)) {
1045     auto *F = dyn_cast<Function>(CI->getCalledValue());
1046     if (F && (F->getName().startswith("llvm.masked.load.") ||
1047               F->getName().startswith("llvm.masked.store."))) {
1048       unsigned OpOffset = 0;
1049       if (F->getName().startswith("llvm.masked.store.")) {
1050         if (!ClInstrumentWrites)
1051           return nullptr;
1052         // Masked store has an initial operand for the value.
1053         OpOffset = 1;
1054         *IsWrite = true;
1055       } else {
1056         if (!ClInstrumentReads)
1057           return nullptr;
1058         *IsWrite = false;
1059       }
1060
1061       auto BasePtr = CI->getOperand(0 + OpOffset);
1062       auto Ty = cast<PointerType>(BasePtr->getType())->getElementType();
1063       *TypeSize = DL.getTypeStoreSizeInBits(Ty);
1064       if (auto AlignmentConstant =
1065               dyn_cast<ConstantInt>(CI->getOperand(1 + OpOffset)))
1066         *Alignment = (unsigned)AlignmentConstant->getZExtValue();
1067       else
1068         *Alignment = 1; // No alignment guarantees. We probably got Undef
1069       if (MaybeMask)
1070         *MaybeMask = CI->getOperand(2 + OpOffset);
1071       PtrOperand = BasePtr;
1072     }
1073   }
1074
1075   // Do not instrument acesses from different address spaces; we cannot deal
1076   // with them.
1077   if (PtrOperand) {
1078     Type *PtrTy = cast<PointerType>(PtrOperand->getType()->getScalarType());
1079     if (PtrTy->getPointerAddressSpace() != 0)
1080       return nullptr;
1081   }
1082
1083   // Treat memory accesses to promotable allocas as non-interesting since they
1084   // will not cause memory violations. This greatly speeds up the instrumented
1085   // executable at -O0.
1086   if (ClSkipPromotableAllocas)
1087     if (auto AI = dyn_cast_or_null<AllocaInst>(PtrOperand))
1088       return isInterestingAlloca(*AI) ? AI : nullptr;
1089
1090   return PtrOperand;
1091 }
1092
1093 static bool isPointerOperand(Value *V) {
1094   return V->getType()->isPointerTy() || isa<PtrToIntInst>(V);
1095 }
1096
1097 // This is a rough heuristic; it may cause both false positives and
1098 // false negatives. The proper implementation requires cooperation with
1099 // the frontend.
1100 static bool isInterestingPointerComparisonOrSubtraction(Instruction *I) {
1101   if (ICmpInst *Cmp = dyn_cast<ICmpInst>(I)) {
1102     if (!Cmp->isRelational()) return false;
1103   } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
1104     if (BO->getOpcode() != Instruction::Sub) return false;
1105   } else {
1106     return false;
1107   }
1108   return isPointerOperand(I->getOperand(0)) &&
1109          isPointerOperand(I->getOperand(1));
1110 }
1111
1112 bool AddressSanitizer::GlobalIsLinkerInitialized(GlobalVariable *G) {
1113   // If a global variable does not have dynamic initialization we don't
1114   // have to instrument it.  However, if a global does not have initializer
1115   // at all, we assume it has dynamic initializer (in other TU).
1116   return G->hasInitializer() && !GlobalsMD.get(G).IsDynInit;
1117 }
1118
1119 void AddressSanitizer::instrumentPointerComparisonOrSubtraction(
1120     Instruction *I) {
1121   IRBuilder<> IRB(I);
1122   Function *F = isa<ICmpInst>(I) ? AsanPtrCmpFunction : AsanPtrSubFunction;
1123   Value *Param[2] = {I->getOperand(0), I->getOperand(1)};
1124   for (Value *&i : Param) {
1125     if (i->getType()->isPointerTy())
1126       i = IRB.CreatePointerCast(i, IntptrTy);
1127   }
1128   IRB.CreateCall(F, Param);
1129 }
1130
1131 static void doInstrumentAddress(AddressSanitizer *Pass, Instruction *I,
1132                                 Instruction *InsertBefore, Value *Addr,
1133                                 unsigned Alignment, unsigned Granularity,
1134                                 uint32_t TypeSize, bool IsWrite,
1135                                 Value *SizeArgument, bool UseCalls,
1136                                 uint32_t Exp) {
1137   // Instrument a 1-, 2-, 4-, 8-, or 16- byte access with one check
1138   // if the data is properly aligned.
1139   if ((TypeSize == 8 || TypeSize == 16 || TypeSize == 32 || TypeSize == 64 ||
1140        TypeSize == 128) &&
1141       (Alignment >= Granularity || Alignment == 0 || Alignment >= TypeSize / 8))
1142     return Pass->instrumentAddress(I, InsertBefore, Addr, TypeSize, IsWrite,
1143                                    nullptr, UseCalls, Exp);
1144   Pass->instrumentUnusualSizeOrAlignment(I, InsertBefore, Addr, TypeSize,
1145                                          IsWrite, nullptr, UseCalls, Exp);
1146 }
1147
1148 static void instrumentMaskedLoadOrStore(AddressSanitizer *Pass,
1149                                         const DataLayout &DL, Type *IntptrTy,
1150                                         Value *Mask, Instruction *I,
1151                                         Value *Addr, unsigned Alignment,
1152                                         unsigned Granularity, uint32_t TypeSize,
1153                                         bool IsWrite, Value *SizeArgument,
1154                                         bool UseCalls, uint32_t Exp) {
1155   auto *VTy = cast<PointerType>(Addr->getType())->getElementType();
1156   uint64_t ElemTypeSize = DL.getTypeStoreSizeInBits(VTy->getScalarType());
1157   unsigned Num = VTy->getVectorNumElements();
1158   auto Zero = ConstantInt::get(IntptrTy, 0);
1159   for (unsigned Idx = 0; Idx < Num; ++Idx) {
1160     Value *InstrumentedAddress = nullptr;
1161     Instruction *InsertBefore = I;
1162     if (auto *Vector = dyn_cast<ConstantVector>(Mask)) {
1163       // dyn_cast as we might get UndefValue
1164       if (auto *Masked = dyn_cast<ConstantInt>(Vector->getOperand(Idx))) {
1165         if (Masked->isNullValue())
1166           // Mask is constant false, so no instrumentation needed.
1167           continue;
1168         // If we have a true or undef value, fall through to doInstrumentAddress
1169         // with InsertBefore == I
1170       }
1171     } else {
1172       IRBuilder<> IRB(I);
1173       Value *MaskElem = IRB.CreateExtractElement(Mask, Idx);
1174       TerminatorInst *ThenTerm = SplitBlockAndInsertIfThen(MaskElem, I, false);
1175       InsertBefore = ThenTerm;
1176     }
1177
1178     IRBuilder<> IRB(InsertBefore);
1179     InstrumentedAddress =
1180         IRB.CreateGEP(Addr, {Zero, ConstantInt::get(IntptrTy, Idx)});
1181     doInstrumentAddress(Pass, I, InsertBefore, InstrumentedAddress, Alignment,
1182                         Granularity, ElemTypeSize, IsWrite, SizeArgument,
1183                         UseCalls, Exp);
1184   }
1185 }
1186
1187 void AddressSanitizer::instrumentMop(ObjectSizeOffsetVisitor &ObjSizeVis,
1188                                      Instruction *I, bool UseCalls,
1189                                      const DataLayout &DL) {
1190   bool IsWrite = false;
1191   unsigned Alignment = 0;
1192   uint64_t TypeSize = 0;
1193   Value *MaybeMask = nullptr;
1194   Value *Addr =
1195       isInterestingMemoryAccess(I, &IsWrite, &TypeSize, &Alignment, &MaybeMask);
1196   assert(Addr);
1197
1198   // Optimization experiments.
1199   // The experiments can be used to evaluate potential optimizations that remove
1200   // instrumentation (assess false negatives). Instead of completely removing
1201   // some instrumentation, you set Exp to a non-zero value (mask of optimization
1202   // experiments that want to remove instrumentation of this instruction).
1203   // If Exp is non-zero, this pass will emit special calls into runtime
1204   // (e.g. __asan_report_exp_load1 instead of __asan_report_load1). These calls
1205   // make runtime terminate the program in a special way (with a different
1206   // exit status). Then you run the new compiler on a buggy corpus, collect
1207   // the special terminations (ideally, you don't see them at all -- no false
1208   // negatives) and make the decision on the optimization.
1209   uint32_t Exp = ClForceExperiment;
1210
1211   if (ClOpt && ClOptGlobals) {
1212     // If initialization order checking is disabled, a simple access to a
1213     // dynamically initialized global is always valid.
1214     GlobalVariable *G = dyn_cast<GlobalVariable>(GetUnderlyingObject(Addr, DL));
1215     if (G && (!ClInitializers || GlobalIsLinkerInitialized(G)) &&
1216         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1217       NumOptimizedAccessesToGlobalVar++;
1218       return;
1219     }
1220   }
1221
1222   if (ClOpt && ClOptStack) {
1223     // A direct inbounds access to a stack variable is always valid.
1224     if (isa<AllocaInst>(GetUnderlyingObject(Addr, DL)) &&
1225         isSafeAccess(ObjSizeVis, Addr, TypeSize)) {
1226       NumOptimizedAccessesToStackVar++;
1227       return;
1228     }
1229   }
1230
1231   if (IsWrite)
1232     NumInstrumentedWrites++;
1233   else
1234     NumInstrumentedReads++;
1235
1236   unsigned Granularity = 1 << Mapping.Scale;
1237   if (MaybeMask) {
1238     instrumentMaskedLoadOrStore(this, DL, IntptrTy, MaybeMask, I, Addr,
1239                                 Alignment, Granularity, TypeSize, IsWrite,
1240                                 nullptr, UseCalls, Exp);
1241   } else {
1242     doInstrumentAddress(this, I, I, Addr, Alignment, Granularity, TypeSize,
1243                         IsWrite, nullptr, UseCalls, Exp);
1244   }
1245 }
1246
1247 Instruction *AddressSanitizer::generateCrashCode(Instruction *InsertBefore,
1248                                                  Value *Addr, bool IsWrite,
1249                                                  size_t AccessSizeIndex,
1250                                                  Value *SizeArgument,
1251                                                  uint32_t Exp) {
1252   IRBuilder<> IRB(InsertBefore);
1253   Value *ExpVal = Exp == 0 ? nullptr : ConstantInt::get(IRB.getInt32Ty(), Exp);
1254   CallInst *Call = nullptr;
1255   if (SizeArgument) {
1256     if (Exp == 0)
1257       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][0],
1258                             {Addr, SizeArgument});
1259     else
1260       Call = IRB.CreateCall(AsanErrorCallbackSized[IsWrite][1],
1261                             {Addr, SizeArgument, ExpVal});
1262   } else {
1263     if (Exp == 0)
1264       Call =
1265           IRB.CreateCall(AsanErrorCallback[IsWrite][0][AccessSizeIndex], Addr);
1266     else
1267       Call = IRB.CreateCall(AsanErrorCallback[IsWrite][1][AccessSizeIndex],
1268                             {Addr, ExpVal});
1269   }
1270
1271   // We don't do Call->setDoesNotReturn() because the BB already has
1272   // UnreachableInst at the end.
1273   // This EmptyAsm is required to avoid callback merge.
1274   IRB.CreateCall(EmptyAsm, {});
1275   return Call;
1276 }
1277
1278 Value *AddressSanitizer::createSlowPathCmp(IRBuilder<> &IRB, Value *AddrLong,
1279                                            Value *ShadowValue,
1280                                            uint32_t TypeSize) {
1281   size_t Granularity = static_cast<size_t>(1) << Mapping.Scale;
1282   // Addr & (Granularity - 1)
1283   Value *LastAccessedByte =
1284       IRB.CreateAnd(AddrLong, ConstantInt::get(IntptrTy, Granularity - 1));
1285   // (Addr & (Granularity - 1)) + size - 1
1286   if (TypeSize / 8 > 1)
1287     LastAccessedByte = IRB.CreateAdd(
1288         LastAccessedByte, ConstantInt::get(IntptrTy, TypeSize / 8 - 1));
1289   // (uint8_t) ((Addr & (Granularity-1)) + size - 1)
1290   LastAccessedByte =
1291       IRB.CreateIntCast(LastAccessedByte, ShadowValue->getType(), false);
1292   // ((uint8_t) ((Addr & (Granularity-1)) + size - 1)) >= ShadowValue
1293   return IRB.CreateICmpSGE(LastAccessedByte, ShadowValue);
1294 }
1295
1296 void AddressSanitizer::instrumentAddress(Instruction *OrigIns,
1297                                          Instruction *InsertBefore, Value *Addr,
1298                                          uint32_t TypeSize, bool IsWrite,
1299                                          Value *SizeArgument, bool UseCalls,
1300                                          uint32_t Exp) {
1301   IRBuilder<> IRB(InsertBefore);
1302   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1303   size_t AccessSizeIndex = TypeSizeToSizeIndex(TypeSize);
1304
1305   if (UseCalls) {
1306     if (Exp == 0)
1307       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][0][AccessSizeIndex],
1308                      AddrLong);
1309     else
1310       IRB.CreateCall(AsanMemoryAccessCallback[IsWrite][1][AccessSizeIndex],
1311                      {AddrLong, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1312     return;
1313   }
1314
1315   Type *ShadowTy =
1316       IntegerType::get(*C, std::max(8U, TypeSize >> Mapping.Scale));
1317   Type *ShadowPtrTy = PointerType::get(ShadowTy, 0);
1318   Value *ShadowPtr = memToShadow(AddrLong, IRB);
1319   Value *CmpVal = Constant::getNullValue(ShadowTy);
1320   Value *ShadowValue =
1321       IRB.CreateLoad(IRB.CreateIntToPtr(ShadowPtr, ShadowPtrTy));
1322
1323   Value *Cmp = IRB.CreateICmpNE(ShadowValue, CmpVal);
1324   size_t Granularity = 1ULL << Mapping.Scale;
1325   TerminatorInst *CrashTerm = nullptr;
1326
1327   if (ClAlwaysSlowPath || (TypeSize < 8 * Granularity)) {
1328     // We use branch weights for the slow path check, to indicate that the slow
1329     // path is rarely taken. This seems to be the case for SPEC benchmarks.
1330     TerminatorInst *CheckTerm = SplitBlockAndInsertIfThen(
1331         Cmp, InsertBefore, false, MDBuilder(*C).createBranchWeights(1, 100000));
1332     assert(cast<BranchInst>(CheckTerm)->isUnconditional());
1333     BasicBlock *NextBB = CheckTerm->getSuccessor(0);
1334     IRB.SetInsertPoint(CheckTerm);
1335     Value *Cmp2 = createSlowPathCmp(IRB, AddrLong, ShadowValue, TypeSize);
1336     if (Recover) {
1337       CrashTerm = SplitBlockAndInsertIfThen(Cmp2, CheckTerm, false);
1338     } else {
1339       BasicBlock *CrashBlock =
1340         BasicBlock::Create(*C, "", NextBB->getParent(), NextBB);
1341       CrashTerm = new UnreachableInst(*C, CrashBlock);
1342       BranchInst *NewTerm = BranchInst::Create(CrashBlock, NextBB, Cmp2);
1343       ReplaceInstWithInst(CheckTerm, NewTerm);
1344     }
1345   } else {
1346     CrashTerm = SplitBlockAndInsertIfThen(Cmp, InsertBefore, !Recover);
1347   }
1348
1349   Instruction *Crash = generateCrashCode(CrashTerm, AddrLong, IsWrite,
1350                                          AccessSizeIndex, SizeArgument, Exp);
1351   Crash->setDebugLoc(OrigIns->getDebugLoc());
1352 }
1353
1354 // Instrument unusual size or unusual alignment.
1355 // We can not do it with a single check, so we do 1-byte check for the first
1356 // and the last bytes. We call __asan_report_*_n(addr, real_size) to be able
1357 // to report the actual access size.
1358 void AddressSanitizer::instrumentUnusualSizeOrAlignment(
1359     Instruction *I, Instruction *InsertBefore, Value *Addr, uint32_t TypeSize,
1360     bool IsWrite, Value *SizeArgument, bool UseCalls, uint32_t Exp) {
1361   IRBuilder<> IRB(InsertBefore);
1362   Value *Size = ConstantInt::get(IntptrTy, TypeSize / 8);
1363   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
1364   if (UseCalls) {
1365     if (Exp == 0)
1366       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][0],
1367                      {AddrLong, Size});
1368     else
1369       IRB.CreateCall(AsanMemoryAccessCallbackSized[IsWrite][1],
1370                      {AddrLong, Size, ConstantInt::get(IRB.getInt32Ty(), Exp)});
1371   } else {
1372     Value *LastByte = IRB.CreateIntToPtr(
1373         IRB.CreateAdd(AddrLong, ConstantInt::get(IntptrTy, TypeSize / 8 - 1)),
1374         Addr->getType());
1375     instrumentAddress(I, InsertBefore, Addr, 8, IsWrite, Size, false, Exp);
1376     instrumentAddress(I, InsertBefore, LastByte, 8, IsWrite, Size, false, Exp);
1377   }
1378 }
1379
1380 void AddressSanitizerModule::poisonOneInitializer(Function &GlobalInit,
1381                                                   GlobalValue *ModuleName) {
1382   // Set up the arguments to our poison/unpoison functions.
1383   IRBuilder<> IRB(&GlobalInit.front(),
1384                   GlobalInit.front().getFirstInsertionPt());
1385
1386   // Add a call to poison all external globals before the given function starts.
1387   Value *ModuleNameAddr = ConstantExpr::getPointerCast(ModuleName, IntptrTy);
1388   IRB.CreateCall(AsanPoisonGlobals, ModuleNameAddr);
1389
1390   // Add calls to unpoison all globals before each return instruction.
1391   for (auto &BB : GlobalInit.getBasicBlockList())
1392     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
1393       CallInst::Create(AsanUnpoisonGlobals, "", RI);
1394 }
1395
1396 void AddressSanitizerModule::createInitializerPoisonCalls(
1397     Module &M, GlobalValue *ModuleName) {
1398   GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1399
1400   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1401   for (Use &OP : CA->operands()) {
1402     if (isa<ConstantAggregateZero>(OP)) continue;
1403     ConstantStruct *CS = cast<ConstantStruct>(OP);
1404
1405     // Must have a function or null ptr.
1406     if (Function *F = dyn_cast<Function>(CS->getOperand(1))) {
1407       if (F->getName() == kAsanModuleCtorName) continue;
1408       ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
1409       // Don't instrument CTORs that will run before asan.module_ctor.
1410       if (Priority->getLimitedValue() <= kAsanCtorAndDtorPriority) continue;
1411       poisonOneInitializer(*F, ModuleName);
1412     }
1413   }
1414 }
1415
1416 bool AddressSanitizerModule::ShouldInstrumentGlobal(GlobalVariable *G) {
1417   Type *Ty = G->getValueType();
1418   DEBUG(dbgs() << "GLOBAL: " << *G << "\n");
1419
1420   if (GlobalsMD.get(G).IsBlacklisted) return false;
1421   if (!Ty->isSized()) return false;
1422   if (!G->hasInitializer()) return false;
1423   if (GlobalWasGeneratedByCompiler(G)) return false; // Our own globals.
1424   // Touch only those globals that will not be defined in other modules.
1425   // Don't handle ODR linkage types and COMDATs since other modules may be built
1426   // without ASan.
1427   if (G->getLinkage() != GlobalVariable::ExternalLinkage &&
1428       G->getLinkage() != GlobalVariable::PrivateLinkage &&
1429       G->getLinkage() != GlobalVariable::InternalLinkage)
1430     return false;
1431   if (G->hasComdat()) return false;
1432   // Two problems with thread-locals:
1433   //   - The address of the main thread's copy can't be computed at link-time.
1434   //   - Need to poison all copies, not just the main thread's one.
1435   if (G->isThreadLocal()) return false;
1436   // For now, just ignore this Global if the alignment is large.
1437   if (G->getAlignment() > MinRedzoneSizeForGlobal()) return false;
1438
1439   if (G->hasSection()) {
1440     StringRef Section = G->getSection();
1441
1442     // Globals from llvm.metadata aren't emitted, do not instrument them.
1443     if (Section == "llvm.metadata") return false;
1444     // Do not instrument globals from special LLVM sections.
1445     if (Section.find("__llvm") != StringRef::npos || Section.find("__LLVM") != StringRef::npos) return false;
1446
1447     // Do not instrument function pointers to initialization and termination
1448     // routines: dynamic linker will not properly handle redzones.
1449     if (Section.startswith(".preinit_array") ||
1450         Section.startswith(".init_array") ||
1451         Section.startswith(".fini_array")) {
1452       return false;
1453     }
1454
1455     // Callbacks put into the CRT initializer/terminator sections
1456     // should not be instrumented.
1457     // See https://code.google.com/p/address-sanitizer/issues/detail?id=305
1458     // and http://msdn.microsoft.com/en-US/en-en/library/bb918180(v=vs.120).aspx
1459     if (Section.startswith(".CRT")) {
1460       DEBUG(dbgs() << "Ignoring a global initializer callback: " << *G << "\n");
1461       return false;
1462     }
1463
1464     if (TargetTriple.isOSBinFormatMachO()) {
1465       StringRef ParsedSegment, ParsedSection;
1466       unsigned TAA = 0, StubSize = 0;
1467       bool TAAParsed;
1468       std::string ErrorCode = MCSectionMachO::ParseSectionSpecifier(
1469           Section, ParsedSegment, ParsedSection, TAA, TAAParsed, StubSize);
1470       assert(ErrorCode.empty() && "Invalid section specifier.");
1471
1472       // Ignore the globals from the __OBJC section. The ObjC runtime assumes
1473       // those conform to /usr/lib/objc/runtime.h, so we can't add redzones to
1474       // them.
1475       if (ParsedSegment == "__OBJC" ||
1476           (ParsedSegment == "__DATA" && ParsedSection.startswith("__objc_"))) {
1477         DEBUG(dbgs() << "Ignoring ObjC runtime global: " << *G << "\n");
1478         return false;
1479       }
1480       // See http://code.google.com/p/address-sanitizer/issues/detail?id=32
1481       // Constant CFString instances are compiled in the following way:
1482       //  -- the string buffer is emitted into
1483       //     __TEXT,__cstring,cstring_literals
1484       //  -- the constant NSConstantString structure referencing that buffer
1485       //     is placed into __DATA,__cfstring
1486       // Therefore there's no point in placing redzones into __DATA,__cfstring.
1487       // Moreover, it causes the linker to crash on OS X 10.7
1488       if (ParsedSegment == "__DATA" && ParsedSection == "__cfstring") {
1489         DEBUG(dbgs() << "Ignoring CFString: " << *G << "\n");
1490         return false;
1491       }
1492       // The linker merges the contents of cstring_literals and removes the
1493       // trailing zeroes.
1494       if (ParsedSegment == "__TEXT" && (TAA & MachO::S_CSTRING_LITERALS)) {
1495         DEBUG(dbgs() << "Ignoring a cstring literal: " << *G << "\n");
1496         return false;
1497       }
1498     }
1499   }
1500
1501   return true;
1502 }
1503
1504 // On Mach-O platforms, we emit global metadata in a separate section of the
1505 // binary in order to allow the linker to properly dead strip. This is only
1506 // supported on recent versions of ld64.
1507 bool AddressSanitizerModule::ShouldUseMachOGlobalsSection() const {
1508   if (!ClUseMachOGlobalsSection)
1509     return false;
1510
1511   if (!TargetTriple.isOSBinFormatMachO())
1512     return false;
1513
1514   if (TargetTriple.isMacOSX() && !TargetTriple.isMacOSXVersionLT(10, 11))
1515     return true;
1516   if (TargetTriple.isiOS() /* or tvOS */ && !TargetTriple.isOSVersionLT(9))
1517     return true;
1518   if (TargetTriple.isWatchOS() && !TargetTriple.isOSVersionLT(2))
1519     return true;
1520
1521   return false;
1522 }
1523
1524 StringRef AddressSanitizerModule::getGlobalMetadataSection() const {
1525   switch (TargetTriple.getObjectFormat()) {
1526   case Triple::COFF:  return ".ASAN$GL";
1527   case Triple::ELF:   return "asan_globals";
1528   case Triple::MachO: return "__DATA,__asan_globals,regular";
1529   default: break;
1530   }
1531   llvm_unreachable("unsupported object format");
1532 }
1533
1534 void AddressSanitizerModule::initializeCallbacks(Module &M) {
1535   IRBuilder<> IRB(*C);
1536
1537   // Declare our poisoning and unpoisoning functions.
1538   AsanPoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1539       kAsanPoisonGlobalsName, IRB.getVoidTy(), IntptrTy, nullptr));
1540   AsanPoisonGlobals->setLinkage(Function::ExternalLinkage);
1541   AsanUnpoisonGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1542       kAsanUnpoisonGlobalsName, IRB.getVoidTy(), nullptr));
1543   AsanUnpoisonGlobals->setLinkage(Function::ExternalLinkage);
1544
1545   // Declare functions that register/unregister globals.
1546   AsanRegisterGlobals = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1547       kAsanRegisterGlobalsName, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1548   AsanRegisterGlobals->setLinkage(Function::ExternalLinkage);
1549   AsanUnregisterGlobals = checkSanitizerInterfaceFunction(
1550       M.getOrInsertFunction(kAsanUnregisterGlobalsName, IRB.getVoidTy(),
1551                             IntptrTy, IntptrTy, nullptr));
1552   AsanUnregisterGlobals->setLinkage(Function::ExternalLinkage);
1553
1554   // Declare the functions that find globals in a shared object and then invoke
1555   // the (un)register function on them.
1556   AsanRegisterImageGlobals = checkSanitizerInterfaceFunction(
1557       M.getOrInsertFunction(kAsanRegisterImageGlobalsName,
1558       IRB.getVoidTy(), IntptrTy, nullptr));
1559   AsanRegisterImageGlobals->setLinkage(Function::ExternalLinkage);
1560
1561   AsanUnregisterImageGlobals = checkSanitizerInterfaceFunction(
1562       M.getOrInsertFunction(kAsanUnregisterImageGlobalsName,
1563       IRB.getVoidTy(), IntptrTy, nullptr));
1564   AsanUnregisterImageGlobals->setLinkage(Function::ExternalLinkage);
1565 }
1566
1567 // This function replaces all global variables with new variables that have
1568 // trailing redzones. It also creates a function that poisons
1569 // redzones and inserts this function into llvm.global_ctors.
1570 bool AddressSanitizerModule::InstrumentGlobals(IRBuilder<> &IRB, Module &M) {
1571   GlobalsMD.init(M);
1572
1573   SmallVector<GlobalVariable *, 16> GlobalsToChange;
1574
1575   for (auto &G : M.globals()) {
1576     if (ShouldInstrumentGlobal(&G)) GlobalsToChange.push_back(&G);
1577   }
1578
1579   size_t n = GlobalsToChange.size();
1580   if (n == 0) return false;
1581
1582   auto &DL = M.getDataLayout();
1583   bool UseComdatMetadata = TargetTriple.isOSBinFormatCOFF();
1584   bool UseMachOGlobalsSection = ShouldUseMachOGlobalsSection();
1585   bool UseMetadataArray = !(UseComdatMetadata || UseMachOGlobalsSection);
1586
1587   // A global is described by a structure
1588   //   size_t beg;
1589   //   size_t size;
1590   //   size_t size_with_redzone;
1591   //   const char *name;
1592   //   const char *module_name;
1593   //   size_t has_dynamic_init;
1594   //   void *source_location;
1595   //   size_t odr_indicator;
1596   // We initialize an array of such structures and pass it to a run-time call.
1597   StructType *GlobalStructTy =
1598       StructType::get(IntptrTy, IntptrTy, IntptrTy, IntptrTy, IntptrTy,
1599                       IntptrTy, IntptrTy, IntptrTy, nullptr);
1600   unsigned SizeOfGlobalStruct = DL.getTypeAllocSize(GlobalStructTy);
1601   assert((isPowerOf2_32(SizeOfGlobalStruct) ||
1602           !TargetTriple.isOSBinFormatCOFF()) &&
1603          "global metadata will not be padded appropriately");
1604   SmallVector<Constant *, 16> Initializers(UseMetadataArray ? n : 0);
1605
1606   // On recent Mach-O platforms, use a structure which binds the liveness of
1607   // the global variable to the metadata struct. Keep the list of "Liveness" GV
1608   // created to be added to llvm.compiler.used
1609   StructType *LivenessTy  = nullptr;
1610   if (UseMachOGlobalsSection)
1611     LivenessTy = StructType::get(IntptrTy, IntptrTy, nullptr);
1612   SmallVector<GlobalValue *, 16> LivenessGlobals(
1613       UseMachOGlobalsSection ? n : 0);
1614
1615   bool HasDynamicallyInitializedGlobals = false;
1616
1617   // We shouldn't merge same module names, as this string serves as unique
1618   // module ID in runtime.
1619   GlobalVariable *ModuleName = createPrivateGlobalForString(
1620       M, M.getModuleIdentifier(), /*AllowMerging*/ false);
1621
1622   for (size_t i = 0; i < n; i++) {
1623     static const uint64_t kMaxGlobalRedzone = 1 << 18;
1624     GlobalVariable *G = GlobalsToChange[i];
1625
1626     auto MD = GlobalsMD.get(G);
1627     StringRef NameForGlobal = G->getName();
1628     // Create string holding the global name (use global name from metadata
1629     // if it's available, otherwise just write the name of global variable).
1630     GlobalVariable *Name = createPrivateGlobalForString(
1631         M, MD.Name.empty() ? NameForGlobal : MD.Name,
1632         /*AllowMerging*/ true);
1633
1634     Type *Ty = G->getValueType();
1635     uint64_t SizeInBytes = DL.getTypeAllocSize(Ty);
1636     uint64_t MinRZ = MinRedzoneSizeForGlobal();
1637     // MinRZ <= RZ <= kMaxGlobalRedzone
1638     // and trying to make RZ to be ~ 1/4 of SizeInBytes.
1639     uint64_t RZ = std::max(
1640         MinRZ, std::min(kMaxGlobalRedzone, (SizeInBytes / MinRZ / 4) * MinRZ));
1641     uint64_t RightRedzoneSize = RZ;
1642     // Round up to MinRZ
1643     if (SizeInBytes % MinRZ) RightRedzoneSize += MinRZ - (SizeInBytes % MinRZ);
1644     assert(((RightRedzoneSize + SizeInBytes) % MinRZ) == 0);
1645     Type *RightRedZoneTy = ArrayType::get(IRB.getInt8Ty(), RightRedzoneSize);
1646
1647     StructType *NewTy = StructType::get(Ty, RightRedZoneTy, nullptr);
1648     Constant *NewInitializer =
1649         ConstantStruct::get(NewTy, G->getInitializer(),
1650                             Constant::getNullValue(RightRedZoneTy), nullptr);
1651
1652     // Create a new global variable with enough space for a redzone.
1653     GlobalValue::LinkageTypes Linkage = G->getLinkage();
1654     if (G->isConstant() && Linkage == GlobalValue::PrivateLinkage)
1655       Linkage = GlobalValue::InternalLinkage;
1656     GlobalVariable *NewGlobal =
1657         new GlobalVariable(M, NewTy, G->isConstant(), Linkage, NewInitializer,
1658                            "", G, G->getThreadLocalMode());
1659     NewGlobal->copyAttributesFrom(G);
1660     NewGlobal->setAlignment(MinRZ);
1661
1662     // Move null-terminated C strings to "__asan_cstring" section on Darwin.
1663     if (TargetTriple.isOSBinFormatMachO() && !G->hasSection() &&
1664         G->isConstant()) {
1665       auto Seq = dyn_cast<ConstantDataSequential>(G->getInitializer());
1666       if (Seq && Seq->isCString())
1667         NewGlobal->setSection("__TEXT,__asan_cstring,regular");
1668     }
1669
1670     // Transfer the debug info.  The payload starts at offset zero so we can
1671     // copy the debug info over as is.
1672     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1673     G->getDebugInfo(GVs);
1674     for (auto *GV : GVs)
1675       NewGlobal->addDebugInfo(GV);
1676
1677     Value *Indices2[2];
1678     Indices2[0] = IRB.getInt32(0);
1679     Indices2[1] = IRB.getInt32(0);
1680
1681     G->replaceAllUsesWith(
1682         ConstantExpr::getGetElementPtr(NewTy, NewGlobal, Indices2, true));
1683     NewGlobal->takeName(G);
1684     G->eraseFromParent();
1685     G = NewGlobal;
1686
1687     if (UseComdatMetadata) {
1688       // Get or create a COMDAT for G so that we can use it with our metadata.
1689       Comdat *C = G->getComdat();
1690       if (!C) {
1691         if (!G->hasName()) {
1692           // If G is unnamed, it must be internal. Give it an artificial name
1693           // so we can put it in a comdat.
1694           assert(G->hasLocalLinkage());
1695           G->setName(Twine(kAsanGenPrefix) + "_anon_global");
1696         }
1697         C = M.getOrInsertComdat(G->getName());
1698         // Make this IMAGE_COMDAT_SELECT_NODUPLICATES on COFF.
1699         if (TargetTriple.isOSBinFormatCOFF())
1700           C->setSelectionKind(Comdat::NoDuplicates);
1701         G->setComdat(C);
1702       }
1703     }
1704
1705     Constant *SourceLoc;
1706     if (!MD.SourceLoc.empty()) {
1707       auto SourceLocGlobal = createPrivateGlobalForSourceLoc(M, MD.SourceLoc);
1708       SourceLoc = ConstantExpr::getPointerCast(SourceLocGlobal, IntptrTy);
1709     } else {
1710       SourceLoc = ConstantInt::get(IntptrTy, 0);
1711     }
1712
1713     Constant *ODRIndicator = ConstantExpr::getNullValue(IRB.getInt8PtrTy());
1714     GlobalValue *InstrumentedGlobal = NewGlobal;
1715
1716     bool CanUsePrivateAliases =
1717         TargetTriple.isOSBinFormatELF() || TargetTriple.isOSBinFormatMachO();
1718     if (CanUsePrivateAliases && ClUsePrivateAliasForGlobals) {
1719       // Create local alias for NewGlobal to avoid crash on ODR between
1720       // instrumented and non-instrumented libraries.
1721       auto *GA = GlobalAlias::create(GlobalValue::InternalLinkage,
1722                                      NameForGlobal + M.getName(), NewGlobal);
1723
1724       // With local aliases, we need to provide another externally visible
1725       // symbol __odr_asan_XXX to detect ODR violation.
1726       auto *ODRIndicatorSym =
1727           new GlobalVariable(M, IRB.getInt8Ty(), false, Linkage,
1728                              Constant::getNullValue(IRB.getInt8Ty()),
1729                              kODRGenPrefix + NameForGlobal, nullptr,
1730                              NewGlobal->getThreadLocalMode());
1731
1732       // Set meaningful attributes for indicator symbol.
1733       ODRIndicatorSym->setVisibility(NewGlobal->getVisibility());
1734       ODRIndicatorSym->setDLLStorageClass(NewGlobal->getDLLStorageClass());
1735       ODRIndicatorSym->setAlignment(1);
1736       ODRIndicator = ODRIndicatorSym;
1737       InstrumentedGlobal = GA;
1738     }
1739
1740     Constant *Initializer = ConstantStruct::get(
1741         GlobalStructTy,
1742         ConstantExpr::getPointerCast(InstrumentedGlobal, IntptrTy),
1743         ConstantInt::get(IntptrTy, SizeInBytes),
1744         ConstantInt::get(IntptrTy, SizeInBytes + RightRedzoneSize),
1745         ConstantExpr::getPointerCast(Name, IntptrTy),
1746         ConstantExpr::getPointerCast(ModuleName, IntptrTy),
1747         ConstantInt::get(IntptrTy, MD.IsDynInit), SourceLoc,
1748         ConstantExpr::getPointerCast(ODRIndicator, IntptrTy), nullptr);
1749
1750     if (ClInitializers && MD.IsDynInit) HasDynamicallyInitializedGlobals = true;
1751
1752     DEBUG(dbgs() << "NEW GLOBAL: " << *NewGlobal << "\n");
1753
1754     // If we aren't using separate metadata globals, add it to the initializer
1755     // list and continue.
1756     if (UseMetadataArray) {
1757       Initializers[i] = Initializer;
1758       continue;
1759     }
1760
1761     // Create a separate metadata global and put it in the appropriate ASan
1762     // global registration section.
1763     GlobalVariable *Metadata = new GlobalVariable(
1764         M, GlobalStructTy, false, GlobalVariable::InternalLinkage,
1765         Initializer, Twine("__asan_global_") +
1766                              GlobalValue::getRealLinkageName(G->getName()));
1767     Metadata->setSection(getGlobalMetadataSection());
1768
1769     // The MSVC linker always inserts padding when linking incrementally. We
1770     // cope with that by aligning each struct to its size, which must be a power
1771     // of two.
1772     if (TargetTriple.isOSBinFormatCOFF())
1773       Metadata->setAlignment(SizeOfGlobalStruct);
1774     else
1775       Metadata->setAlignment(1); // Don't leave padding in between.
1776
1777     // On platforms that support comdats, put the metadata and the
1778     // instrumented global in the same group. This ensures that the metadata
1779     // is discarded if the instrumented global is discarded.
1780     if (UseComdatMetadata) {
1781       assert(G->hasComdat());
1782       Metadata->setComdat(G->getComdat());
1783       continue;
1784     }
1785     assert(UseMachOGlobalsSection);
1786
1787     // On recent Mach-O platforms, we emit the global metadata in a way that
1788     // allows the linker to properly strip dead globals.
1789     auto LivenessBinder = ConstantStruct::get(
1790         LivenessTy, Initializer->getAggregateElement(0u),
1791         ConstantExpr::getPointerCast(Metadata, IntptrTy), nullptr);
1792     GlobalVariable *Liveness = new GlobalVariable(
1793         M, LivenessTy, false, GlobalVariable::InternalLinkage, LivenessBinder,
1794         Twine("__asan_binder_") + G->getName());
1795     Liveness->setSection("__DATA,__asan_liveness,regular,live_support");
1796     LivenessGlobals[i] = Liveness;
1797   }
1798
1799   // Create calls for poisoning before initializers run and unpoisoning after.
1800   if (HasDynamicallyInitializedGlobals)
1801     createInitializerPoisonCalls(M, ModuleName);
1802
1803   // Platforms with a dedicated metadata section don't need to emit any more
1804   // code.
1805   if (UseComdatMetadata)
1806     return true;
1807
1808   GlobalVariable *AllGlobals = nullptr;
1809   GlobalVariable *RegisteredFlag = nullptr;
1810
1811   if (UseMachOGlobalsSection) {
1812     // RegisteredFlag serves two purposes. First, we can pass it to dladdr()
1813     // to look up the loaded image that contains it. Second, we can store in it
1814     // whether registration has already occurred, to prevent duplicate
1815     // registration.
1816     //
1817     // common linkage ensures that there is only one global per shared library.
1818     RegisteredFlag = new GlobalVariable(
1819         M, IntptrTy, false, GlobalVariable::CommonLinkage,
1820         ConstantInt::get(IntptrTy, 0), kAsanGlobalsRegisteredFlagName);
1821
1822     // Update llvm.compiler.used, adding the new liveness globals. This is
1823     // needed so that during LTO these variables stay alive. The alternative
1824     // would be to have the linker handling the LTO symbols, but libLTO
1825     // current API does not expose access to the section for each symbol.
1826     if (!LivenessGlobals.empty())
1827       appendToCompilerUsed(M, LivenessGlobals);
1828   } else if (UseMetadataArray) {
1829     // On platforms that don't have a custom metadata section, we emit an array
1830     // of global metadata structures.
1831     ArrayType *ArrayOfGlobalStructTy = ArrayType::get(GlobalStructTy, n);
1832     AllGlobals = new GlobalVariable(
1833         M, ArrayOfGlobalStructTy, false, GlobalVariable::InternalLinkage,
1834         ConstantArray::get(ArrayOfGlobalStructTy, Initializers), "");
1835   }
1836
1837   // Create a call to register the globals with the runtime.
1838   if (UseMachOGlobalsSection) {
1839     IRB.CreateCall(AsanRegisterImageGlobals,
1840                    {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1841   } else {
1842     IRB.CreateCall(AsanRegisterGlobals,
1843                    {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1844                     ConstantInt::get(IntptrTy, n)});
1845   }
1846
1847   // We also need to unregister globals at the end, e.g., when a shared library
1848   // gets closed.
1849   Function *AsanDtorFunction =
1850       Function::Create(FunctionType::get(Type::getVoidTy(*C), false),
1851                        GlobalValue::InternalLinkage, kAsanModuleDtorName, &M);
1852   BasicBlock *AsanDtorBB = BasicBlock::Create(*C, "", AsanDtorFunction);
1853   IRBuilder<> IRB_Dtor(ReturnInst::Create(*C, AsanDtorBB));
1854
1855   if (UseMachOGlobalsSection) {
1856     IRB_Dtor.CreateCall(AsanUnregisterImageGlobals,
1857                         {IRB.CreatePointerCast(RegisteredFlag, IntptrTy)});
1858   } else {
1859     IRB_Dtor.CreateCall(AsanUnregisterGlobals,
1860                         {IRB.CreatePointerCast(AllGlobals, IntptrTy),
1861                          ConstantInt::get(IntptrTy, n)});
1862   }
1863
1864   appendToGlobalDtors(M, AsanDtorFunction, kAsanCtorAndDtorPriority);
1865
1866   DEBUG(dbgs() << M);
1867   return true;
1868 }
1869
1870 bool AddressSanitizerModule::runOnModule(Module &M) {
1871   C = &(M.getContext());
1872   int LongSize = M.getDataLayout().getPointerSizeInBits();
1873   IntptrTy = Type::getIntNTy(*C, LongSize);
1874   TargetTriple = Triple(M.getTargetTriple());
1875   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1876   initializeCallbacks(M);
1877
1878   bool Changed = false;
1879
1880   // TODO(glider): temporarily disabled globals instrumentation for KASan.
1881   if (ClGlobals && !CompileKernel) {
1882     Function *CtorFunc = M.getFunction(kAsanModuleCtorName);
1883     assert(CtorFunc);
1884     IRBuilder<> IRB(CtorFunc->getEntryBlock().getTerminator());
1885     Changed |= InstrumentGlobals(IRB, M);
1886   }
1887
1888   return Changed;
1889 }
1890
1891 void AddressSanitizer::initializeCallbacks(Module &M) {
1892   IRBuilder<> IRB(*C);
1893   // Create __asan_report* callbacks.
1894   // IsWrite, TypeSize and Exp are encoded in the function name.
1895   for (int Exp = 0; Exp < 2; Exp++) {
1896     for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
1897       const std::string TypeStr = AccessIsWrite ? "store" : "load";
1898       const std::string ExpStr = Exp ? "exp_" : "";
1899       const std::string SuffixStr = CompileKernel ? "N" : "_n";
1900       const std::string EndingStr = Recover ? "_noabort" : "";
1901       Type *ExpType = Exp ? Type::getInt32Ty(*C) : nullptr;
1902       AsanErrorCallbackSized[AccessIsWrite][Exp] =
1903           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1904               kAsanReportErrorTemplate + ExpStr + TypeStr + SuffixStr + EndingStr,
1905               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1906       AsanMemoryAccessCallbackSized[AccessIsWrite][Exp] =
1907           checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1908               ClMemoryAccessCallbackPrefix + ExpStr + TypeStr + "N" + EndingStr,
1909               IRB.getVoidTy(), IntptrTy, IntptrTy, ExpType, nullptr));
1910       for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
1911            AccessSizeIndex++) {
1912         const std::string Suffix = TypeStr + itostr(1ULL << AccessSizeIndex);
1913         AsanErrorCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1914             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1915                 kAsanReportErrorTemplate + ExpStr + Suffix + EndingStr,
1916                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1917         AsanMemoryAccessCallback[AccessIsWrite][Exp][AccessSizeIndex] =
1918             checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1919                 ClMemoryAccessCallbackPrefix + ExpStr + Suffix + EndingStr,
1920                 IRB.getVoidTy(), IntptrTy, ExpType, nullptr));
1921       }
1922     }
1923   }
1924
1925   const std::string MemIntrinCallbackPrefix =
1926       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
1927   AsanMemmove = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1928       MemIntrinCallbackPrefix + "memmove", IRB.getInt8PtrTy(),
1929       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1930   AsanMemcpy = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1931       MemIntrinCallbackPrefix + "memcpy", IRB.getInt8PtrTy(),
1932       IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IntptrTy, nullptr));
1933   AsanMemset = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1934       MemIntrinCallbackPrefix + "memset", IRB.getInt8PtrTy(),
1935       IRB.getInt8PtrTy(), IRB.getInt32Ty(), IntptrTy, nullptr));
1936
1937   AsanHandleNoReturnFunc = checkSanitizerInterfaceFunction(
1938       M.getOrInsertFunction(kAsanHandleNoReturnName, IRB.getVoidTy(), nullptr));
1939
1940   AsanPtrCmpFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1941       kAsanPtrCmp, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1942   AsanPtrSubFunction = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
1943       kAsanPtrSub, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
1944   // We insert an empty inline asm after __asan_report* to avoid callback merge.
1945   EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
1946                             StringRef(""), StringRef(""),
1947                             /*hasSideEffects=*/true);
1948 }
1949
1950 // virtual
1951 bool AddressSanitizer::doInitialization(Module &M) {
1952   // Initialize the private fields. No one has accessed them before.
1953
1954   GlobalsMD.init(M);
1955
1956   C = &(M.getContext());
1957   LongSize = M.getDataLayout().getPointerSizeInBits();
1958   IntptrTy = Type::getIntNTy(*C, LongSize);
1959   TargetTriple = Triple(M.getTargetTriple());
1960
1961   if (!CompileKernel) {
1962     std::tie(AsanCtorFunction, AsanInitFunction) =
1963         createSanitizerCtorAndInitFunctions(
1964             M, kAsanModuleCtorName, kAsanInitName,
1965             /*InitArgTypes=*/{}, /*InitArgs=*/{}, kAsanVersionCheckName);
1966     appendToGlobalCtors(M, AsanCtorFunction, kAsanCtorAndDtorPriority);
1967   }
1968   Mapping = getShadowMapping(TargetTriple, LongSize, CompileKernel);
1969   return true;
1970 }
1971
1972 bool AddressSanitizer::doFinalization(Module &M) {
1973   GlobalsMD.reset();
1974   return false;
1975 }
1976
1977 bool AddressSanitizer::maybeInsertAsanInitAtFunctionEntry(Function &F) {
1978   // For each NSObject descendant having a +load method, this method is invoked
1979   // by the ObjC runtime before any of the static constructors is called.
1980   // Therefore we need to instrument such methods with a call to __asan_init
1981   // at the beginning in order to initialize our runtime before any access to
1982   // the shadow memory.
1983   // We cannot just ignore these methods, because they may call other
1984   // instrumented functions.
1985   if (F.getName().find(" load]") != std::string::npos) {
1986     IRBuilder<> IRB(&F.front(), F.front().begin());
1987     IRB.CreateCall(AsanInitFunction, {});
1988     return true;
1989   }
1990   return false;
1991 }
1992
1993 void AddressSanitizer::maybeInsertDynamicShadowAtFunctionEntry(Function &F) {
1994   // Generate code only when dynamic addressing is needed.
1995   if (Mapping.Offset != kDynamicShadowSentinel)
1996     return;
1997
1998   IRBuilder<> IRB(&F.front().front());
1999   Value *GlobalDynamicAddress = F.getParent()->getOrInsertGlobal(
2000       kAsanShadowMemoryDynamicAddress, IntptrTy);
2001   LocalDynamicShadow = IRB.CreateLoad(GlobalDynamicAddress);
2002 }
2003
2004 void AddressSanitizer::markEscapedLocalAllocas(Function &F) {
2005   // Find the one possible call to llvm.localescape and pre-mark allocas passed
2006   // to it as uninteresting. This assumes we haven't started processing allocas
2007   // yet. This check is done up front because iterating the use list in
2008   // isInterestingAlloca would be algorithmically slower.
2009   assert(ProcessedAllocas.empty() && "must process localescape before allocas");
2010
2011   // Try to get the declaration of llvm.localescape. If it's not in the module,
2012   // we can exit early.
2013   if (!F.getParent()->getFunction("llvm.localescape")) return;
2014
2015   // Look for a call to llvm.localescape call in the entry block. It can't be in
2016   // any other block.
2017   for (Instruction &I : F.getEntryBlock()) {
2018     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
2019     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
2020       // We found a call. Mark all the allocas passed in as uninteresting.
2021       for (Value *Arg : II->arg_operands()) {
2022         AllocaInst *AI = dyn_cast<AllocaInst>(Arg->stripPointerCasts());
2023         assert(AI && AI->isStaticAlloca() &&
2024                "non-static alloca arg to localescape");
2025         ProcessedAllocas[AI] = false;
2026       }
2027       break;
2028     }
2029   }
2030 }
2031
2032 bool AddressSanitizer::runOnFunction(Function &F) {
2033   if (&F == AsanCtorFunction) return false;
2034   if (F.getLinkage() == GlobalValue::AvailableExternallyLinkage) return false;
2035   if (!ClDebugFunc.empty() && ClDebugFunc == F.getName()) return false;
2036   if (F.getName().startswith("__asan_")) return false;
2037
2038   bool FunctionModified = false;
2039
2040   // If needed, insert __asan_init before checking for SanitizeAddress attr.
2041   // This function needs to be called even if the function body is not
2042   // instrumented.  
2043   if (maybeInsertAsanInitAtFunctionEntry(F))
2044     FunctionModified = true;
2045   
2046   // Leave if the function doesn't need instrumentation.
2047   if (!F.hasFnAttribute(Attribute::SanitizeAddress)) return FunctionModified;
2048
2049   DEBUG(dbgs() << "ASAN instrumenting:\n" << F << "\n");
2050
2051   initializeCallbacks(*F.getParent());
2052   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2053
2054   FunctionStateRAII CleanupObj(this);
2055
2056   maybeInsertDynamicShadowAtFunctionEntry(F);
2057
2058   // We can't instrument allocas used with llvm.localescape. Only static allocas
2059   // can be passed to that intrinsic.
2060   markEscapedLocalAllocas(F);
2061
2062   // We want to instrument every address only once per basic block (unless there
2063   // are calls between uses).
2064   SmallSet<Value *, 16> TempsToInstrument;
2065   SmallVector<Instruction *, 16> ToInstrument;
2066   SmallVector<Instruction *, 8> NoReturnCalls;
2067   SmallVector<BasicBlock *, 16> AllBlocks;
2068   SmallVector<Instruction *, 16> PointerComparisonsOrSubtracts;
2069   int NumAllocas = 0;
2070   bool IsWrite;
2071   unsigned Alignment;
2072   uint64_t TypeSize;
2073   const TargetLibraryInfo *TLI =
2074       &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
2075
2076   // Fill the set of memory operations to instrument.
2077   for (auto &BB : F) {
2078     AllBlocks.push_back(&BB);
2079     TempsToInstrument.clear();
2080     int NumInsnsPerBB = 0;
2081     for (auto &Inst : BB) {
2082       if (LooksLikeCodeInBug11395(&Inst)) return false;
2083       Value *MaybeMask = nullptr;
2084       if (Value *Addr = isInterestingMemoryAccess(&Inst, &IsWrite, &TypeSize,
2085                                                   &Alignment, &MaybeMask)) {
2086         if (ClOpt && ClOptSameTemp) {
2087           // If we have a mask, skip instrumentation if we've already
2088           // instrumented the full object. But don't add to TempsToInstrument
2089           // because we might get another load/store with a different mask.
2090           if (MaybeMask) {
2091             if (TempsToInstrument.count(Addr))
2092               continue; // We've seen this (whole) temp in the current BB.
2093           } else {
2094             if (!TempsToInstrument.insert(Addr).second)
2095               continue; // We've seen this temp in the current BB.
2096           }
2097         }
2098       } else if (ClInvalidPointerPairs &&
2099                  isInterestingPointerComparisonOrSubtraction(&Inst)) {
2100         PointerComparisonsOrSubtracts.push_back(&Inst);
2101         continue;
2102       } else if (isa<MemIntrinsic>(Inst)) {
2103         // ok, take it.
2104       } else {
2105         if (isa<AllocaInst>(Inst)) NumAllocas++;
2106         CallSite CS(&Inst);
2107         if (CS) {
2108           // A call inside BB.
2109           TempsToInstrument.clear();
2110           if (CS.doesNotReturn()) NoReturnCalls.push_back(CS.getInstruction());
2111         }
2112         if (CallInst *CI = dyn_cast<CallInst>(&Inst))
2113           maybeMarkSanitizerLibraryCallNoBuiltin(CI, TLI);
2114         continue;
2115       }
2116       ToInstrument.push_back(&Inst);
2117       NumInsnsPerBB++;
2118       if (NumInsnsPerBB >= ClMaxInsnsToInstrumentPerBB) break;
2119     }
2120   }
2121
2122   bool UseCalls =
2123       CompileKernel ||
2124       (ClInstrumentationWithCallsThreshold >= 0 &&
2125        ToInstrument.size() > (unsigned)ClInstrumentationWithCallsThreshold);
2126   const DataLayout &DL = F.getParent()->getDataLayout();
2127   ObjectSizeOffsetVisitor ObjSizeVis(DL, TLI, F.getContext(),
2128                                      /*RoundToAlign=*/true);
2129
2130   // Instrument.
2131   int NumInstrumented = 0;
2132   for (auto Inst : ToInstrument) {
2133     if (ClDebugMin < 0 || ClDebugMax < 0 ||
2134         (NumInstrumented >= ClDebugMin && NumInstrumented <= ClDebugMax)) {
2135       if (isInterestingMemoryAccess(Inst, &IsWrite, &TypeSize, &Alignment))
2136         instrumentMop(ObjSizeVis, Inst, UseCalls,
2137                       F.getParent()->getDataLayout());
2138       else
2139         instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
2140     }
2141     NumInstrumented++;
2142   }
2143
2144   FunctionStackPoisoner FSP(F, *this);
2145   bool ChangedStack = FSP.runOnFunction();
2146
2147   // We must unpoison the stack before every NoReturn call (throw, _exit, etc).
2148   // See e.g. http://code.google.com/p/address-sanitizer/issues/detail?id=37
2149   for (auto CI : NoReturnCalls) {
2150     IRBuilder<> IRB(CI);
2151     IRB.CreateCall(AsanHandleNoReturnFunc, {});
2152   }
2153
2154   for (auto Inst : PointerComparisonsOrSubtracts) {
2155     instrumentPointerComparisonOrSubtraction(Inst);
2156     NumInstrumented++;
2157   }
2158
2159   if (NumInstrumented > 0 || ChangedStack || !NoReturnCalls.empty())
2160     FunctionModified = true;
2161
2162   DEBUG(dbgs() << "ASAN done instrumenting: " << FunctionModified << " "
2163                << F << "\n");
2164
2165   return FunctionModified;
2166 }
2167
2168 // Workaround for bug 11395: we don't want to instrument stack in functions
2169 // with large assembly blobs (32-bit only), otherwise reg alloc may crash.
2170 // FIXME: remove once the bug 11395 is fixed.
2171 bool AddressSanitizer::LooksLikeCodeInBug11395(Instruction *I) {
2172   if (LongSize != 32) return false;
2173   CallInst *CI = dyn_cast<CallInst>(I);
2174   if (!CI || !CI->isInlineAsm()) return false;
2175   if (CI->getNumArgOperands() <= 5) return false;
2176   // We have inline assembly with quite a few arguments.
2177   return true;
2178 }
2179
2180 void FunctionStackPoisoner::initializeCallbacks(Module &M) {
2181   IRBuilder<> IRB(*C);
2182   for (int i = 0; i <= kMaxAsanStackMallocSizeClass; i++) {
2183     std::string Suffix = itostr(i);
2184     AsanStackMallocFunc[i] = checkSanitizerInterfaceFunction(
2185         M.getOrInsertFunction(kAsanStackMallocNameTemplate + Suffix, IntptrTy,
2186                               IntptrTy, nullptr));
2187     AsanStackFreeFunc[i] = checkSanitizerInterfaceFunction(
2188         M.getOrInsertFunction(kAsanStackFreeNameTemplate + Suffix,
2189                               IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2190   }
2191   if (ASan.UseAfterScope) {
2192     AsanPoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2193         M.getOrInsertFunction(kAsanPoisonStackMemoryName, IRB.getVoidTy(),
2194                               IntptrTy, IntptrTy, nullptr));
2195     AsanUnpoisonStackMemoryFunc = checkSanitizerInterfaceFunction(
2196         M.getOrInsertFunction(kAsanUnpoisonStackMemoryName, IRB.getVoidTy(),
2197                               IntptrTy, IntptrTy, nullptr));
2198   }
2199
2200   for (size_t Val : {0x00, 0xf1, 0xf2, 0xf3, 0xf5, 0xf8}) {
2201     std::ostringstream Name;
2202     Name << kAsanSetShadowPrefix;
2203     Name << std::setw(2) << std::setfill('0') << std::hex << Val;
2204     AsanSetShadowFunc[Val] =
2205         checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2206             Name.str(), IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2207   }
2208
2209   AsanAllocaPoisonFunc = checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2210       kAsanAllocaPoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2211   AsanAllocasUnpoisonFunc =
2212       checkSanitizerInterfaceFunction(M.getOrInsertFunction(
2213           kAsanAllocasUnpoison, IRB.getVoidTy(), IntptrTy, IntptrTy, nullptr));
2214 }
2215
2216 void FunctionStackPoisoner::copyToShadowInline(ArrayRef<uint8_t> ShadowMask,
2217                                                ArrayRef<uint8_t> ShadowBytes,
2218                                                size_t Begin, size_t End,
2219                                                IRBuilder<> &IRB,
2220                                                Value *ShadowBase) {
2221   if (Begin >= End)
2222     return;
2223
2224   const size_t LargestStoreSizeInBytes =
2225       std::min<size_t>(sizeof(uint64_t), ASan.LongSize / 8);
2226
2227   const bool IsLittleEndian = F.getParent()->getDataLayout().isLittleEndian();
2228
2229   // Poison given range in shadow using larges store size with out leading and
2230   // trailing zeros in ShadowMask. Zeros never change, so they need neither
2231   // poisoning nor up-poisoning. Still we don't mind if some of them get into a
2232   // middle of a store.
2233   for (size_t i = Begin; i < End;) {
2234     if (!ShadowMask[i]) {
2235       assert(!ShadowBytes[i]);
2236       ++i;
2237       continue;
2238     }
2239
2240     size_t StoreSizeInBytes = LargestStoreSizeInBytes;
2241     // Fit store size into the range.
2242     while (StoreSizeInBytes > End - i)
2243       StoreSizeInBytes /= 2;
2244
2245     // Minimize store size by trimming trailing zeros.
2246     for (size_t j = StoreSizeInBytes - 1; j && !ShadowMask[i + j]; --j) {
2247       while (j <= StoreSizeInBytes / 2)
2248         StoreSizeInBytes /= 2;
2249     }
2250
2251     uint64_t Val = 0;
2252     for (size_t j = 0; j < StoreSizeInBytes; j++) {
2253       if (IsLittleEndian)
2254         Val |= (uint64_t)ShadowBytes[i + j] << (8 * j);
2255       else
2256         Val = (Val << 8) | ShadowBytes[i + j];
2257     }
2258
2259     Value *Ptr = IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i));
2260     Value *Poison = IRB.getIntN(StoreSizeInBytes * 8, Val);
2261     IRB.CreateAlignedStore(
2262         Poison, IRB.CreateIntToPtr(Ptr, Poison->getType()->getPointerTo()), 1);
2263
2264     i += StoreSizeInBytes;
2265   }
2266 }
2267
2268 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2269                                          ArrayRef<uint8_t> ShadowBytes,
2270                                          IRBuilder<> &IRB, Value *ShadowBase) {
2271   copyToShadow(ShadowMask, ShadowBytes, 0, ShadowMask.size(), IRB, ShadowBase);
2272 }
2273
2274 void FunctionStackPoisoner::copyToShadow(ArrayRef<uint8_t> ShadowMask,
2275                                          ArrayRef<uint8_t> ShadowBytes,
2276                                          size_t Begin, size_t End,
2277                                          IRBuilder<> &IRB, Value *ShadowBase) {
2278   assert(ShadowMask.size() == ShadowBytes.size());
2279   size_t Done = Begin;
2280   for (size_t i = Begin, j = Begin + 1; i < End; i = j++) {
2281     if (!ShadowMask[i]) {
2282       assert(!ShadowBytes[i]);
2283       continue;
2284     }
2285     uint8_t Val = ShadowBytes[i];
2286     if (!AsanSetShadowFunc[Val])
2287       continue;
2288
2289     // Skip same values.
2290     for (; j < End && ShadowMask[j] && Val == ShadowBytes[j]; ++j) {
2291     }
2292
2293     if (j - i >= ClMaxInlinePoisoningSize) {
2294       copyToShadowInline(ShadowMask, ShadowBytes, Done, i, IRB, ShadowBase);
2295       IRB.CreateCall(AsanSetShadowFunc[Val],
2296                      {IRB.CreateAdd(ShadowBase, ConstantInt::get(IntptrTy, i)),
2297                       ConstantInt::get(IntptrTy, j - i)});
2298       Done = j;
2299     }
2300   }
2301
2302   copyToShadowInline(ShadowMask, ShadowBytes, Done, End, IRB, ShadowBase);
2303 }
2304
2305 // Fake stack allocator (asan_fake_stack.h) has 11 size classes
2306 // for every power of 2 from kMinStackMallocSize to kMaxAsanStackMallocSizeClass
2307 static int StackMallocSizeClass(uint64_t LocalStackSize) {
2308   assert(LocalStackSize <= kMaxStackMallocSize);
2309   uint64_t MaxSize = kMinStackMallocSize;
2310   for (int i = 0;; i++, MaxSize *= 2)
2311     if (LocalStackSize <= MaxSize) return i;
2312   llvm_unreachable("impossible LocalStackSize");
2313 }
2314
2315 PHINode *FunctionStackPoisoner::createPHI(IRBuilder<> &IRB, Value *Cond,
2316                                           Value *ValueIfTrue,
2317                                           Instruction *ThenTerm,
2318                                           Value *ValueIfFalse) {
2319   PHINode *PHI = IRB.CreatePHI(IntptrTy, 2);
2320   BasicBlock *CondBlock = cast<Instruction>(Cond)->getParent();
2321   PHI->addIncoming(ValueIfFalse, CondBlock);
2322   BasicBlock *ThenBlock = ThenTerm->getParent();
2323   PHI->addIncoming(ValueIfTrue, ThenBlock);
2324   return PHI;
2325 }
2326
2327 Value *FunctionStackPoisoner::createAllocaForLayout(
2328     IRBuilder<> &IRB, const ASanStackFrameLayout &L, bool Dynamic) {
2329   AllocaInst *Alloca;
2330   if (Dynamic) {
2331     Alloca = IRB.CreateAlloca(IRB.getInt8Ty(),
2332                               ConstantInt::get(IRB.getInt64Ty(), L.FrameSize),
2333                               "MyAlloca");
2334   } else {
2335     Alloca = IRB.CreateAlloca(ArrayType::get(IRB.getInt8Ty(), L.FrameSize),
2336                               nullptr, "MyAlloca");
2337     assert(Alloca->isStaticAlloca());
2338   }
2339   assert((ClRealignStack & (ClRealignStack - 1)) == 0);
2340   size_t FrameAlignment = std::max(L.FrameAlignment, (size_t)ClRealignStack);
2341   Alloca->setAlignment(FrameAlignment);
2342   return IRB.CreatePointerCast(Alloca, IntptrTy);
2343 }
2344
2345 void FunctionStackPoisoner::createDynamicAllocasInitStorage() {
2346   BasicBlock &FirstBB = *F.begin();
2347   IRBuilder<> IRB(dyn_cast<Instruction>(FirstBB.begin()));
2348   DynamicAllocaLayout = IRB.CreateAlloca(IntptrTy, nullptr);
2349   IRB.CreateStore(Constant::getNullValue(IntptrTy), DynamicAllocaLayout);
2350   DynamicAllocaLayout->setAlignment(32);
2351 }
2352
2353 void FunctionStackPoisoner::processDynamicAllocas() {
2354   if (!ClInstrumentDynamicAllocas || DynamicAllocaVec.empty()) {
2355     assert(DynamicAllocaPoisonCallVec.empty());
2356     return;
2357   }
2358
2359   // Insert poison calls for lifetime intrinsics for dynamic allocas.
2360   for (const auto &APC : DynamicAllocaPoisonCallVec) {
2361     assert(APC.InsBefore);
2362     assert(APC.AI);
2363     assert(ASan.isInterestingAlloca(*APC.AI));
2364     assert(!APC.AI->isStaticAlloca());
2365
2366     IRBuilder<> IRB(APC.InsBefore);
2367     poisonAlloca(APC.AI, APC.Size, IRB, APC.DoPoison);
2368     // Dynamic allocas will be unpoisoned unconditionally below in
2369     // unpoisonDynamicAllocas.
2370     // Flag that we need unpoison static allocas.
2371   }
2372
2373   // Handle dynamic allocas.
2374   createDynamicAllocasInitStorage();
2375   for (auto &AI : DynamicAllocaVec)
2376     handleDynamicAllocaCall(AI);
2377   unpoisonDynamicAllocas();
2378 }
2379
2380 void FunctionStackPoisoner::processStaticAllocas() {
2381   if (AllocaVec.empty()) {
2382     assert(StaticAllocaPoisonCallVec.empty());
2383     return;
2384   }
2385
2386   int StackMallocIdx = -1;
2387   DebugLoc EntryDebugLocation;
2388   if (auto SP = F.getSubprogram())
2389     EntryDebugLocation = DebugLoc::get(SP->getScopeLine(), 0, SP);
2390
2391   Instruction *InsBefore = AllocaVec[0];
2392   IRBuilder<> IRB(InsBefore);
2393   IRB.SetCurrentDebugLocation(EntryDebugLocation);
2394
2395   // Make sure non-instrumented allocas stay in the entry block. Otherwise,
2396   // debug info is broken, because only entry-block allocas are treated as
2397   // regular stack slots.
2398   auto InsBeforeB = InsBefore->getParent();
2399   assert(InsBeforeB == &F.getEntryBlock());
2400   for (auto *AI : StaticAllocasToMoveUp)
2401     if (AI->getParent() == InsBeforeB)
2402       AI->moveBefore(InsBefore);
2403
2404   // If we have a call to llvm.localescape, keep it in the entry block.
2405   if (LocalEscapeCall) LocalEscapeCall->moveBefore(InsBefore);
2406
2407   SmallVector<ASanStackVariableDescription, 16> SVD;
2408   SVD.reserve(AllocaVec.size());
2409   for (AllocaInst *AI : AllocaVec) {
2410     ASanStackVariableDescription D = {AI->getName().data(),
2411                                       ASan.getAllocaSizeInBytes(*AI),
2412                                       0,
2413                                       AI->getAlignment(),
2414                                       AI,
2415                                       0,
2416                                       0};
2417     SVD.push_back(D);
2418   }
2419
2420   // Minimal header size (left redzone) is 4 pointers,
2421   // i.e. 32 bytes on 64-bit platforms and 16 bytes in 32-bit platforms.
2422   size_t MinHeaderSize = ASan.LongSize / 2;
2423   const ASanStackFrameLayout &L =
2424       ComputeASanStackFrameLayout(SVD, 1ULL << Mapping.Scale, MinHeaderSize);
2425
2426   // Build AllocaToSVDMap for ASanStackVariableDescription lookup.
2427   DenseMap<const AllocaInst *, ASanStackVariableDescription *> AllocaToSVDMap;
2428   for (auto &Desc : SVD)
2429     AllocaToSVDMap[Desc.AI] = &Desc;
2430
2431   // Update SVD with information from lifetime intrinsics.
2432   for (const auto &APC : StaticAllocaPoisonCallVec) {
2433     assert(APC.InsBefore);
2434     assert(APC.AI);
2435     assert(ASan.isInterestingAlloca(*APC.AI));
2436     assert(APC.AI->isStaticAlloca());
2437
2438     ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2439     Desc.LifetimeSize = Desc.Size;
2440     if (const DILocation *FnLoc = EntryDebugLocation.get()) {
2441       if (const DILocation *LifetimeLoc = APC.InsBefore->getDebugLoc().get()) {
2442         if (LifetimeLoc->getFile() == FnLoc->getFile())
2443           if (unsigned Line = LifetimeLoc->getLine())
2444             Desc.Line = std::min(Desc.Line ? Desc.Line : Line, Line);
2445       }
2446     }
2447   }
2448
2449   auto DescriptionString = ComputeASanStackFrameDescription(SVD);
2450   DEBUG(dbgs() << DescriptionString << " --- " << L.FrameSize << "\n");
2451   uint64_t LocalStackSize = L.FrameSize;
2452   bool DoStackMalloc = ClUseAfterReturn && !ASan.CompileKernel &&
2453                        LocalStackSize <= kMaxStackMallocSize;
2454   bool DoDynamicAlloca = ClDynamicAllocaStack;
2455   // Don't do dynamic alloca or stack malloc if:
2456   // 1) There is inline asm: too often it makes assumptions on which registers
2457   //    are available.
2458   // 2) There is a returns_twice call (typically setjmp), which is
2459   //    optimization-hostile, and doesn't play well with introduced indirect
2460   //    register-relative calculation of local variable addresses.
2461   DoDynamicAlloca &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2462   DoStackMalloc &= !HasNonEmptyInlineAsm && !HasReturnsTwiceCall;
2463
2464   Value *StaticAlloca =
2465       DoDynamicAlloca ? nullptr : createAllocaForLayout(IRB, L, false);
2466
2467   Value *FakeStack;
2468   Value *LocalStackBase;
2469
2470   if (DoStackMalloc) {
2471     // void *FakeStack = __asan_option_detect_stack_use_after_return
2472     //     ? __asan_stack_malloc_N(LocalStackSize)
2473     //     : nullptr;
2474     // void *LocalStackBase = (FakeStack) ? FakeStack : alloca(LocalStackSize);
2475     Constant *OptionDetectUseAfterReturn = F.getParent()->getOrInsertGlobal(
2476         kAsanOptionDetectUseAfterReturn, IRB.getInt32Ty());
2477     Value *UseAfterReturnIsEnabled =
2478         IRB.CreateICmpNE(IRB.CreateLoad(OptionDetectUseAfterReturn),
2479                          Constant::getNullValue(IRB.getInt32Ty()));
2480     Instruction *Term =
2481         SplitBlockAndInsertIfThen(UseAfterReturnIsEnabled, InsBefore, false);
2482     IRBuilder<> IRBIf(Term);
2483     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2484     StackMallocIdx = StackMallocSizeClass(LocalStackSize);
2485     assert(StackMallocIdx <= kMaxAsanStackMallocSizeClass);
2486     Value *FakeStackValue =
2487         IRBIf.CreateCall(AsanStackMallocFunc[StackMallocIdx],
2488                          ConstantInt::get(IntptrTy, LocalStackSize));
2489     IRB.SetInsertPoint(InsBefore);
2490     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2491     FakeStack = createPHI(IRB, UseAfterReturnIsEnabled, FakeStackValue, Term,
2492                           ConstantInt::get(IntptrTy, 0));
2493
2494     Value *NoFakeStack =
2495         IRB.CreateICmpEQ(FakeStack, Constant::getNullValue(IntptrTy));
2496     Term = SplitBlockAndInsertIfThen(NoFakeStack, InsBefore, false);
2497     IRBIf.SetInsertPoint(Term);
2498     IRBIf.SetCurrentDebugLocation(EntryDebugLocation);
2499     Value *AllocaValue =
2500         DoDynamicAlloca ? createAllocaForLayout(IRBIf, L, true) : StaticAlloca;
2501     IRB.SetInsertPoint(InsBefore);
2502     IRB.SetCurrentDebugLocation(EntryDebugLocation);
2503     LocalStackBase = createPHI(IRB, NoFakeStack, AllocaValue, Term, FakeStack);
2504   } else {
2505     // void *FakeStack = nullptr;
2506     // void *LocalStackBase = alloca(LocalStackSize);
2507     FakeStack = ConstantInt::get(IntptrTy, 0);
2508     LocalStackBase =
2509         DoDynamicAlloca ? createAllocaForLayout(IRB, L, true) : StaticAlloca;
2510   }
2511
2512   // Replace Alloca instructions with base+offset.
2513   for (const auto &Desc : SVD) {
2514     AllocaInst *AI = Desc.AI;
2515     Value *NewAllocaPtr = IRB.CreateIntToPtr(
2516         IRB.CreateAdd(LocalStackBase, ConstantInt::get(IntptrTy, Desc.Offset)),
2517         AI->getType());
2518     replaceDbgDeclareForAlloca(AI, NewAllocaPtr, DIB, /*Deref=*/true);
2519     AI->replaceAllUsesWith(NewAllocaPtr);
2520   }
2521
2522   // The left-most redzone has enough space for at least 4 pointers.
2523   // Write the Magic value to redzone[0].
2524   Value *BasePlus0 = IRB.CreateIntToPtr(LocalStackBase, IntptrPtrTy);
2525   IRB.CreateStore(ConstantInt::get(IntptrTy, kCurrentStackFrameMagic),
2526                   BasePlus0);
2527   // Write the frame description constant to redzone[1].
2528   Value *BasePlus1 = IRB.CreateIntToPtr(
2529       IRB.CreateAdd(LocalStackBase,
2530                     ConstantInt::get(IntptrTy, ASan.LongSize / 8)),
2531       IntptrPtrTy);
2532   GlobalVariable *StackDescriptionGlobal =
2533       createPrivateGlobalForString(*F.getParent(), DescriptionString,
2534                                    /*AllowMerging*/ true);
2535   Value *Description = IRB.CreatePointerCast(StackDescriptionGlobal, IntptrTy);
2536   IRB.CreateStore(Description, BasePlus1);
2537   // Write the PC to redzone[2].
2538   Value *BasePlus2 = IRB.CreateIntToPtr(
2539       IRB.CreateAdd(LocalStackBase,
2540                     ConstantInt::get(IntptrTy, 2 * ASan.LongSize / 8)),
2541       IntptrPtrTy);
2542   IRB.CreateStore(IRB.CreatePointerCast(&F, IntptrTy), BasePlus2);
2543
2544   const auto &ShadowAfterScope = GetShadowBytesAfterScope(SVD, L);
2545
2546   // Poison the stack red zones at the entry.
2547   Value *ShadowBase = ASan.memToShadow(LocalStackBase, IRB);
2548   // As mask we must use most poisoned case: red zones and after scope.
2549   // As bytes we can use either the same or just red zones only.
2550   copyToShadow(ShadowAfterScope, ShadowAfterScope, IRB, ShadowBase);
2551
2552   if (!StaticAllocaPoisonCallVec.empty()) {
2553     const auto &ShadowInScope = GetShadowBytes(SVD, L);
2554
2555     // Poison static allocas near lifetime intrinsics.
2556     for (const auto &APC : StaticAllocaPoisonCallVec) {
2557       const ASanStackVariableDescription &Desc = *AllocaToSVDMap[APC.AI];
2558       assert(Desc.Offset % L.Granularity == 0);
2559       size_t Begin = Desc.Offset / L.Granularity;
2560       size_t End = Begin + (APC.Size + L.Granularity - 1) / L.Granularity;
2561
2562       IRBuilder<> IRB(APC.InsBefore);
2563       copyToShadow(ShadowAfterScope,
2564                    APC.DoPoison ? ShadowAfterScope : ShadowInScope, Begin, End,
2565                    IRB, ShadowBase);
2566     }
2567   }
2568
2569   SmallVector<uint8_t, 64> ShadowClean(ShadowAfterScope.size(), 0);
2570   SmallVector<uint8_t, 64> ShadowAfterReturn;
2571
2572   // (Un)poison the stack before all ret instructions.
2573   for (auto Ret : RetVec) {
2574     IRBuilder<> IRBRet(Ret);
2575     // Mark the current frame as retired.
2576     IRBRet.CreateStore(ConstantInt::get(IntptrTy, kRetiredStackFrameMagic),
2577                        BasePlus0);
2578     if (DoStackMalloc) {
2579       assert(StackMallocIdx >= 0);
2580       // if FakeStack != 0  // LocalStackBase == FakeStack
2581       //     // In use-after-return mode, poison the whole stack frame.
2582       //     if StackMallocIdx <= 4
2583       //         // For small sizes inline the whole thing:
2584       //         memset(ShadowBase, kAsanStackAfterReturnMagic, ShadowSize);
2585       //         **SavedFlagPtr(FakeStack) = 0
2586       //     else
2587       //         __asan_stack_free_N(FakeStack, LocalStackSize)
2588       // else
2589       //     <This is not a fake stack; unpoison the redzones>
2590       Value *Cmp =
2591           IRBRet.CreateICmpNE(FakeStack, Constant::getNullValue(IntptrTy));
2592       TerminatorInst *ThenTerm, *ElseTerm;
2593       SplitBlockAndInsertIfThenElse(Cmp, Ret, &ThenTerm, &ElseTerm);
2594
2595       IRBuilder<> IRBPoison(ThenTerm);
2596       if (StackMallocIdx <= 4) {
2597         int ClassSize = kMinStackMallocSize << StackMallocIdx;
2598         ShadowAfterReturn.resize(ClassSize / L.Granularity,
2599                                  kAsanStackUseAfterReturnMagic);
2600         copyToShadow(ShadowAfterReturn, ShadowAfterReturn, IRBPoison,
2601                      ShadowBase);
2602         Value *SavedFlagPtrPtr = IRBPoison.CreateAdd(
2603             FakeStack,
2604             ConstantInt::get(IntptrTy, ClassSize - ASan.LongSize / 8));
2605         Value *SavedFlagPtr = IRBPoison.CreateLoad(
2606             IRBPoison.CreateIntToPtr(SavedFlagPtrPtr, IntptrPtrTy));
2607         IRBPoison.CreateStore(
2608             Constant::getNullValue(IRBPoison.getInt8Ty()),
2609             IRBPoison.CreateIntToPtr(SavedFlagPtr, IRBPoison.getInt8PtrTy()));
2610       } else {
2611         // For larger frames call __asan_stack_free_*.
2612         IRBPoison.CreateCall(
2613             AsanStackFreeFunc[StackMallocIdx],
2614             {FakeStack, ConstantInt::get(IntptrTy, LocalStackSize)});
2615       }
2616
2617       IRBuilder<> IRBElse(ElseTerm);
2618       copyToShadow(ShadowAfterScope, ShadowClean, IRBElse, ShadowBase);
2619     } else {
2620       copyToShadow(ShadowAfterScope, ShadowClean, IRBRet, ShadowBase);
2621     }
2622   }
2623
2624   // We are done. Remove the old unused alloca instructions.
2625   for (auto AI : AllocaVec) AI->eraseFromParent();
2626 }
2627
2628 void FunctionStackPoisoner::poisonAlloca(Value *V, uint64_t Size,
2629                                          IRBuilder<> &IRB, bool DoPoison) {
2630   // For now just insert the call to ASan runtime.
2631   Value *AddrArg = IRB.CreatePointerCast(V, IntptrTy);
2632   Value *SizeArg = ConstantInt::get(IntptrTy, Size);
2633   IRB.CreateCall(
2634       DoPoison ? AsanPoisonStackMemoryFunc : AsanUnpoisonStackMemoryFunc,
2635       {AddrArg, SizeArg});
2636 }
2637
2638 // Handling llvm.lifetime intrinsics for a given %alloca:
2639 // (1) collect all llvm.lifetime.xxx(%size, %value) describing the alloca.
2640 // (2) if %size is constant, poison memory for llvm.lifetime.end (to detect
2641 //     invalid accesses) and unpoison it for llvm.lifetime.start (the memory
2642 //     could be poisoned by previous llvm.lifetime.end instruction, as the
2643 //     variable may go in and out of scope several times, e.g. in loops).
2644 // (3) if we poisoned at least one %alloca in a function,
2645 //     unpoison the whole stack frame at function exit.
2646
2647 AllocaInst *FunctionStackPoisoner::findAllocaForValue(Value *V) {
2648   if (AllocaInst *AI = dyn_cast<AllocaInst>(V))
2649     // We're interested only in allocas we can handle.
2650     return ASan.isInterestingAlloca(*AI) ? AI : nullptr;
2651   // See if we've already calculated (or started to calculate) alloca for a
2652   // given value.
2653   AllocaForValueMapTy::iterator I = AllocaForValue.find(V);
2654   if (I != AllocaForValue.end()) return I->second;
2655   // Store 0 while we're calculating alloca for value V to avoid
2656   // infinite recursion if the value references itself.
2657   AllocaForValue[V] = nullptr;
2658   AllocaInst *Res = nullptr;
2659   if (CastInst *CI = dyn_cast<CastInst>(V))
2660     Res = findAllocaForValue(CI->getOperand(0));
2661   else if (PHINode *PN = dyn_cast<PHINode>(V)) {
2662     for (Value *IncValue : PN->incoming_values()) {
2663       // Allow self-referencing phi-nodes.
2664       if (IncValue == PN) continue;
2665       AllocaInst *IncValueAI = findAllocaForValue(IncValue);
2666       // AI for incoming values should exist and should all be equal.
2667       if (IncValueAI == nullptr || (Res != nullptr && IncValueAI != Res))
2668         return nullptr;
2669       Res = IncValueAI;
2670     }
2671   } else if (GetElementPtrInst *EP = dyn_cast<GetElementPtrInst>(V)) {
2672     Res = findAllocaForValue(EP->getPointerOperand());
2673   } else {
2674     DEBUG(dbgs() << "Alloca search canceled on unknown instruction: " << *V << "\n");
2675   }
2676   if (Res) AllocaForValue[V] = Res;
2677   return Res;
2678 }
2679
2680 void FunctionStackPoisoner::handleDynamicAllocaCall(AllocaInst *AI) {
2681   IRBuilder<> IRB(AI);
2682
2683   const unsigned Align = std::max(kAllocaRzSize, AI->getAlignment());
2684   const uint64_t AllocaRedzoneMask = kAllocaRzSize - 1;
2685
2686   Value *Zero = Constant::getNullValue(IntptrTy);
2687   Value *AllocaRzSize = ConstantInt::get(IntptrTy, kAllocaRzSize);
2688   Value *AllocaRzMask = ConstantInt::get(IntptrTy, AllocaRedzoneMask);
2689
2690   // Since we need to extend alloca with additional memory to locate
2691   // redzones, and OldSize is number of allocated blocks with
2692   // ElementSize size, get allocated memory size in bytes by
2693   // OldSize * ElementSize.
2694   const unsigned ElementSize =
2695       F.getParent()->getDataLayout().getTypeAllocSize(AI->getAllocatedType());
2696   Value *OldSize =
2697       IRB.CreateMul(IRB.CreateIntCast(AI->getArraySize(), IntptrTy, false),
2698                     ConstantInt::get(IntptrTy, ElementSize));
2699
2700   // PartialSize = OldSize % 32
2701   Value *PartialSize = IRB.CreateAnd(OldSize, AllocaRzMask);
2702
2703   // Misalign = kAllocaRzSize - PartialSize;
2704   Value *Misalign = IRB.CreateSub(AllocaRzSize, PartialSize);
2705
2706   // PartialPadding = Misalign != kAllocaRzSize ? Misalign : 0;
2707   Value *Cond = IRB.CreateICmpNE(Misalign, AllocaRzSize);
2708   Value *PartialPadding = IRB.CreateSelect(Cond, Misalign, Zero);
2709
2710   // AdditionalChunkSize = Align + PartialPadding + kAllocaRzSize
2711   // Align is added to locate left redzone, PartialPadding for possible
2712   // partial redzone and kAllocaRzSize for right redzone respectively.
2713   Value *AdditionalChunkSize = IRB.CreateAdd(
2714       ConstantInt::get(IntptrTy, Align + kAllocaRzSize), PartialPadding);
2715
2716   Value *NewSize = IRB.CreateAdd(OldSize, AdditionalChunkSize);
2717
2718   // Insert new alloca with new NewSize and Align params.
2719   AllocaInst *NewAlloca = IRB.CreateAlloca(IRB.getInt8Ty(), NewSize);
2720   NewAlloca->setAlignment(Align);
2721
2722   // NewAddress = Address + Align
2723   Value *NewAddress = IRB.CreateAdd(IRB.CreatePtrToInt(NewAlloca, IntptrTy),
2724                                     ConstantInt::get(IntptrTy, Align));
2725
2726   // Insert __asan_alloca_poison call for new created alloca.
2727   IRB.CreateCall(AsanAllocaPoisonFunc, {NewAddress, OldSize});
2728
2729   // Store the last alloca's address to DynamicAllocaLayout. We'll need this
2730   // for unpoisoning stuff.
2731   IRB.CreateStore(IRB.CreatePtrToInt(NewAlloca, IntptrTy), DynamicAllocaLayout);
2732
2733   Value *NewAddressPtr = IRB.CreateIntToPtr(NewAddress, AI->getType());
2734
2735   // Replace all uses of AddessReturnedByAlloca with NewAddressPtr.
2736   AI->replaceAllUsesWith(NewAddressPtr);
2737
2738   // We are done. Erase old alloca from parent.
2739   AI->eraseFromParent();
2740 }
2741
2742 // isSafeAccess returns true if Addr is always inbounds with respect to its
2743 // base object. For example, it is a field access or an array access with
2744 // constant inbounds index.
2745 bool AddressSanitizer::isSafeAccess(ObjectSizeOffsetVisitor &ObjSizeVis,
2746                                     Value *Addr, uint64_t TypeSize) const {
2747   SizeOffsetType SizeOffset = ObjSizeVis.compute(Addr);
2748   if (!ObjSizeVis.bothKnown(SizeOffset)) return false;
2749   uint64_t Size = SizeOffset.first.getZExtValue();
2750   int64_t Offset = SizeOffset.second.getSExtValue();
2751   // Three checks are required to ensure safety:
2752   // . Offset >= 0  (since the offset is given from the base ptr)
2753   // . Size >= Offset  (unsigned)
2754   // . Size - Offset >= NeededSize  (unsigned)
2755   return Offset >= 0 && Size >= uint64_t(Offset) &&
2756          Size - uint64_t(Offset) >= TypeSize / 8;
2757 }