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