1 //===- HWAddressSanitizer.cpp - detector of uninitialized reads -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// This file is a part of HWAddressSanitizer, an address basic correctness
11 /// checker based on tagged addressing.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
15 #include "llvm/ADT/MapVector.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/PostDominators.h"
22 #include "llvm/Analysis/StackSafetyAnalysis.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/BinaryFormat/Dwarf.h"
25 #include "llvm/BinaryFormat/ELF.h"
26 #include "llvm/IR/Attributes.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/Constant.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfoMetadata.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Dominators.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/InlineAsm.h"
37 #include "llvm/IR/InstIterator.h"
38 #include "llvm/IR/InstVisitor.h"
39 #include "llvm/IR/Instruction.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/IntrinsicInst.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/LLVMContext.h"
44 #include "llvm/IR/MDBuilder.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/Value.h"
48 #include "llvm/InitializePasses.h"
49 #include "llvm/Pass.h"
50 #include "llvm/PassRegistry.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/raw_ostream.h"
55 #include "llvm/Transforms/Instrumentation.h"
56 #include "llvm/Transforms/Instrumentation/AddressSanitizerCommon.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
58 #include "llvm/Transforms/Utils/MemoryTaggingSupport.h"
59 #include "llvm/Transforms/Utils/ModuleUtils.h"
60 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
61 #include <sstream>
62 
63 using namespace llvm;
64 
65 #define DEBUG_TYPE "hwasan"
66 
67 const char kHwasanModuleCtorName[] = "hwasan.module_ctor";
68 const char kHwasanNoteName[] = "hwasan.note";
69 const char kHwasanInitName[] = "__hwasan_init";
70 const char kHwasanPersonalityThunkName[] = "__hwasan_personality_thunk";
71 
72 const char kHwasanShadowMemoryDynamicAddress[] =
73     "__hwasan_shadow_memory_dynamic_address";
74 
75 // Accesses sizes are powers of two: 1, 2, 4, 8, 16.
76 static const size_t kNumberOfAccessSizes = 5;
77 
78 static const size_t kDefaultShadowScale = 4;
79 static const uint64_t kDynamicShadowSentinel =
80     std::numeric_limits<uint64_t>::max();
81 
82 static const unsigned kShadowBaseAlignment = 32;
83 
84 static cl::opt<std::string>
85     ClMemoryAccessCallbackPrefix("hwasan-memory-access-callback-prefix",
86                                  cl::desc("Prefix for memory access callbacks"),
87                                  cl::Hidden, cl::init("__hwasan_"));
88 
89 static cl::opt<bool> ClInstrumentWithCalls(
90     "hwasan-instrument-with-calls",
91     cl::desc("instrument reads and writes with callbacks"), cl::Hidden,
92     cl::init(false));
93 
94 static cl::opt<bool> ClInstrumentReads("hwasan-instrument-reads",
95                                        cl::desc("instrument read instructions"),
96                                        cl::Hidden, cl::init(true));
97 
98 static cl::opt<bool>
99     ClInstrumentWrites("hwasan-instrument-writes",
100                        cl::desc("instrument write instructions"), cl::Hidden,
101                        cl::init(true));
102 
103 static cl::opt<bool> ClInstrumentAtomics(
104     "hwasan-instrument-atomics",
105     cl::desc("instrument atomic instructions (rmw, cmpxchg)"), cl::Hidden,
106     cl::init(true));
107 
108 static cl::opt<bool> ClInstrumentByval("hwasan-instrument-byval",
109                                        cl::desc("instrument byval arguments"),
110                                        cl::Hidden, cl::init(true));
111 
112 static cl::opt<bool>
113     ClRecover("hwasan-recover",
114               cl::desc("Enable recovery mode (continue-after-error)."),
115               cl::Hidden, cl::init(false));
116 
117 static cl::opt<bool> ClInstrumentStack("hwasan-instrument-stack",
118                                        cl::desc("instrument stack (allocas)"),
119                                        cl::Hidden, cl::init(true));
120 
121 static cl::opt<bool>
122     ClUseStackSafety("hwasan-use-stack-safety", cl::Hidden, cl::init(true),
123                      cl::Hidden, cl::desc("Use Stack Safety analysis results"),
124                      cl::Optional);
125 
126 static cl::opt<size_t> ClMaxLifetimes(
127     "hwasan-max-lifetimes-for-alloca", cl::Hidden, cl::init(3),
128     cl::ReallyHidden,
129     cl::desc("How many lifetime ends to handle for a single alloca."),
130     cl::Optional);
131 
132 static cl::opt<bool>
133     ClUseAfterScope("hwasan-use-after-scope",
134                     cl::desc("detect use after scope within function"),
135                     cl::Hidden, cl::init(false));
136 
137 static cl::opt<bool> ClUARRetagToZero(
138     "hwasan-uar-retag-to-zero",
139     cl::desc("Clear alloca tags before returning from the function to allow "
140              "non-instrumented and instrumented function calls mix. When set "
141              "to false, allocas are retagged before returning from the "
142              "function to detect use after return."),
143     cl::Hidden, cl::init(true));
144 
145 static cl::opt<bool> ClGenerateTagsWithCalls(
146     "hwasan-generate-tags-with-calls",
147     cl::desc("generate new tags with runtime library calls"), cl::Hidden,
148     cl::init(false));
149 
150 static cl::opt<bool> ClGlobals("hwasan-globals", cl::desc("Instrument globals"),
151                                cl::Hidden, cl::init(false), cl::ZeroOrMore);
152 
153 static cl::opt<int> ClMatchAllTag(
154     "hwasan-match-all-tag",
155     cl::desc("don't report bad accesses via pointers with this tag"),
156     cl::Hidden, cl::init(-1));
157 
158 static cl::opt<bool>
159     ClEnableKhwasan("hwasan-kernel",
160                     cl::desc("Enable KernelHWAddressSanitizer instrumentation"),
161                     cl::Hidden, cl::init(false));
162 
163 // These flags allow to change the shadow mapping and control how shadow memory
164 // is accessed. The shadow mapping looks like:
165 //    Shadow = (Mem >> scale) + offset
166 
167 static cl::opt<uint64_t>
168     ClMappingOffset("hwasan-mapping-offset",
169                     cl::desc("HWASan shadow mapping offset [EXPERIMENTAL]"),
170                     cl::Hidden, cl::init(0));
171 
172 static cl::opt<bool>
173     ClWithIfunc("hwasan-with-ifunc",
174                 cl::desc("Access dynamic shadow through an ifunc global on "
175                          "platforms that support this"),
176                 cl::Hidden, cl::init(false));
177 
178 static cl::opt<bool> ClWithTls(
179     "hwasan-with-tls",
180     cl::desc("Access dynamic shadow through an thread-local pointer on "
181              "platforms that support this"),
182     cl::Hidden, cl::init(true));
183 
184 static cl::opt<bool>
185     ClRecordStackHistory("hwasan-record-stack-history",
186                          cl::desc("Record stack frames with tagged allocations "
187                                   "in a thread-local ring buffer"),
188                          cl::Hidden, cl::init(true));
189 static cl::opt<bool>
190     ClInstrumentMemIntrinsics("hwasan-instrument-mem-intrinsics",
191                               cl::desc("instrument memory intrinsics"),
192                               cl::Hidden, cl::init(true));
193 
194 static cl::opt<bool>
195     ClInstrumentLandingPads("hwasan-instrument-landing-pads",
196                             cl::desc("instrument landing pads"), cl::Hidden,
197                             cl::init(false), cl::ZeroOrMore);
198 
199 static cl::opt<bool> ClUseShortGranules(
200     "hwasan-use-short-granules",
201     cl::desc("use short granules in allocas and outlined checks"), cl::Hidden,
202     cl::init(false), cl::ZeroOrMore);
203 
204 static cl::opt<bool> ClInstrumentPersonalityFunctions(
205     "hwasan-instrument-personality-functions",
206     cl::desc("instrument personality functions"), cl::Hidden, cl::init(false),
207     cl::ZeroOrMore);
208 
209 static cl::opt<bool> ClInlineAllChecks("hwasan-inline-all-checks",
210                                        cl::desc("inline all checks"),
211                                        cl::Hidden, cl::init(false));
212 
213 // Enabled from clang by "-fsanitize-hwaddress-experimental-aliasing".
214 static cl::opt<bool> ClUsePageAliases("hwasan-experimental-use-page-aliases",
215                                       cl::desc("Use page aliasing in HWASan"),
216                                       cl::Hidden, cl::init(false));
217 
218 namespace {
219 
220 bool shouldUsePageAliases(const Triple &TargetTriple) {
221   return ClUsePageAliases && TargetTriple.getArch() == Triple::x86_64;
222 }
223 
224 bool shouldInstrumentStack(const Triple &TargetTriple) {
225   return !shouldUsePageAliases(TargetTriple) && ClInstrumentStack;
226 }
227 
228 bool shouldInstrumentWithCalls(const Triple &TargetTriple) {
229   return ClInstrumentWithCalls || TargetTriple.getArch() == Triple::x86_64;
230 }
231 
232 bool mightUseStackSafetyAnalysis(bool DisableOptimization) {
233   return ClUseStackSafety.getNumOccurrences() ? ClUseStackSafety
234                                               : !DisableOptimization;
235 }
236 
237 bool shouldUseStackSafetyAnalysis(const Triple &TargetTriple,
238                                   bool DisableOptimization) {
239   return shouldInstrumentStack(TargetTriple) &&
240          mightUseStackSafetyAnalysis(DisableOptimization);
241 }
242 
243 bool shouldDetectUseAfterScope(const Triple &TargetTriple) {
244   return ClUseAfterScope && shouldInstrumentStack(TargetTriple);
245 }
246 
247 /// An instrumentation pass implementing detection of addressability bugs
248 /// using tagged pointers.
249 class HWAddressSanitizer {
250 private:
251   struct AllocaInfo {
252     AllocaInst *AI;
253     SmallVector<IntrinsicInst *, 2> LifetimeStart;
254     SmallVector<IntrinsicInst *, 2> LifetimeEnd;
255   };
256 
257 public:
258   HWAddressSanitizer(Module &M, bool CompileKernel, bool Recover,
259                      const StackSafetyGlobalInfo *SSI)
260       : M(M), SSI(SSI) {
261     this->Recover = ClRecover.getNumOccurrences() > 0 ? ClRecover : Recover;
262     this->CompileKernel = ClEnableKhwasan.getNumOccurrences() > 0
263                               ? ClEnableKhwasan
264                               : CompileKernel;
265 
266     initializeModule();
267   }
268 
269   void setSSI(const StackSafetyGlobalInfo *S) { SSI = S; }
270 
271   DenseMap<AllocaInst *, AllocaInst *> padInterestingAllocas(
272       const MapVector<AllocaInst *, AllocaInfo> &AllocasToInstrument);
273   bool sanitizeFunction(Function &F,
274                         llvm::function_ref<const DominatorTree &()> GetDT,
275                         llvm::function_ref<const PostDominatorTree &()> GetPDT);
276   void initializeModule();
277   void createHwasanCtorComdat();
278 
279   void initializeCallbacks(Module &M);
280 
281   Value *getOpaqueNoopCast(IRBuilder<> &IRB, Value *Val);
282 
283   Value *getDynamicShadowIfunc(IRBuilder<> &IRB);
284   Value *getShadowNonTls(IRBuilder<> &IRB);
285 
286   void untagPointerOperand(Instruction *I, Value *Addr);
287   Value *memToShadow(Value *Shadow, IRBuilder<> &IRB);
288 
289   int64_t getAccessInfo(bool IsWrite, unsigned AccessSizeIndex);
290   void instrumentMemAccessOutline(Value *Ptr, bool IsWrite,
291                                   unsigned AccessSizeIndex,
292                                   Instruction *InsertBefore);
293   void instrumentMemAccessInline(Value *Ptr, bool IsWrite,
294                                  unsigned AccessSizeIndex,
295                                  Instruction *InsertBefore);
296   bool ignoreMemIntrinsic(MemIntrinsic *MI);
297   void instrumentMemIntrinsic(MemIntrinsic *MI);
298   bool instrumentMemAccess(InterestingMemoryOperand &O);
299   bool ignoreAccess(Instruction *Inst, Value *Ptr);
300   void getInterestingMemoryOperands(
301       Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting);
302 
303   bool isInterestingAlloca(const AllocaInst &AI);
304   void tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, Value *Tag, size_t Size);
305   Value *tagPointer(IRBuilder<> &IRB, Type *Ty, Value *PtrLong, Value *Tag);
306   Value *untagPointer(IRBuilder<> &IRB, Value *PtrLong);
307   bool instrumentStack(
308       bool ShouldDetectUseAfterScope,
309       MapVector<AllocaInst *, AllocaInfo> &AllocasToInstrument,
310       SmallVector<Instruction *, 4> &UnrecognizedLifetimes,
311       DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
312       SmallVectorImpl<Instruction *> &RetVec, Value *StackTag,
313       llvm::function_ref<const DominatorTree &()> GetDT,
314       llvm::function_ref<const PostDominatorTree &()> GetPDT);
315   Value *readRegister(IRBuilder<> &IRB, StringRef Name);
316   bool instrumentLandingPads(SmallVectorImpl<Instruction *> &RetVec);
317   Value *getNextTagWithCall(IRBuilder<> &IRB);
318   Value *getStackBaseTag(IRBuilder<> &IRB);
319   Value *getAllocaTag(IRBuilder<> &IRB, Value *StackTag, AllocaInst *AI,
320                       unsigned AllocaNo);
321   Value *getUARTag(IRBuilder<> &IRB, Value *StackTag);
322 
323   Value *getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty);
324   Value *applyTagMask(IRBuilder<> &IRB, Value *OldTag);
325   unsigned retagMask(unsigned AllocaNo);
326 
327   void emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord);
328 
329   void instrumentGlobal(GlobalVariable *GV, uint8_t Tag);
330   void instrumentGlobals();
331 
332   void instrumentPersonalityFunctions();
333 
334 private:
335   LLVMContext *C;
336   Module &M;
337   const StackSafetyGlobalInfo *SSI;
338   Triple TargetTriple;
339   FunctionCallee HWAsanMemmove, HWAsanMemcpy, HWAsanMemset;
340   FunctionCallee HWAsanHandleVfork;
341 
342   /// This struct defines the shadow mapping using the rule:
343   ///   shadow = (mem >> Scale) + Offset.
344   /// If InGlobal is true, then
345   ///   extern char __hwasan_shadow[];
346   ///   shadow = (mem >> Scale) + &__hwasan_shadow
347   /// If InTls is true, then
348   ///   extern char *__hwasan_tls;
349   ///   shadow = (mem>>Scale) + align_up(__hwasan_shadow, kShadowBaseAlignment)
350   ///
351   /// If WithFrameRecord is true, then __hwasan_tls will be used to access the
352   /// ring buffer for storing stack allocations on targets that support it.
353   struct ShadowMapping {
354     int Scale;
355     uint64_t Offset;
356     bool InGlobal;
357     bool InTls;
358     bool WithFrameRecord;
359 
360     void init(Triple &TargetTriple, bool InstrumentWithCalls);
361     uint64_t getObjectAlignment() const { return 1ULL << Scale; }
362   };
363 
364   ShadowMapping Mapping;
365 
366   Type *VoidTy = Type::getVoidTy(M.getContext());
367   Type *IntptrTy;
368   Type *Int8PtrTy;
369   Type *Int8Ty;
370   Type *Int32Ty;
371   Type *Int64Ty = Type::getInt64Ty(M.getContext());
372 
373   bool CompileKernel;
374   bool Recover;
375   bool OutlinedChecks;
376   bool UseShortGranules;
377   bool InstrumentLandingPads;
378   bool InstrumentWithCalls;
379   bool InstrumentStack;
380   bool DetectUseAfterScope;
381   bool UsePageAliases;
382 
383   bool HasMatchAllTag = false;
384   uint8_t MatchAllTag = 0;
385 
386   unsigned PointerTagShift;
387   uint64_t TagMaskByte;
388 
389   Function *HwasanCtorFunction;
390 
391   FunctionCallee HwasanMemoryAccessCallback[2][kNumberOfAccessSizes];
392   FunctionCallee HwasanMemoryAccessCallbackSized[2];
393 
394   FunctionCallee HwasanTagMemoryFunc;
395   FunctionCallee HwasanGenerateTagFunc;
396 
397   Constant *ShadowGlobal;
398 
399   Value *ShadowBase = nullptr;
400   Value *StackBaseTag = nullptr;
401   GlobalValue *ThreadPtrGlobal = nullptr;
402 };
403 
404 class HWAddressSanitizerLegacyPass : public FunctionPass {
405 public:
406   // Pass identification, replacement for typeid.
407   static char ID;
408 
409   explicit HWAddressSanitizerLegacyPass(bool CompileKernel = false,
410                                         bool Recover = false,
411                                         bool DisableOptimization = false)
412       : FunctionPass(ID), CompileKernel(CompileKernel), Recover(Recover),
413         DisableOptimization(DisableOptimization) {
414     initializeHWAddressSanitizerLegacyPassPass(
415         *PassRegistry::getPassRegistry());
416   }
417 
418   StringRef getPassName() const override { return "HWAddressSanitizer"; }
419 
420   bool doInitialization(Module &M) override {
421     HWASan = std::make_unique<HWAddressSanitizer>(M, CompileKernel, Recover,
422                                                   /*SSI=*/nullptr);
423     return true;
424   }
425 
426   bool runOnFunction(Function &F) override {
427     auto TargetTriple = Triple(F.getParent()->getTargetTriple());
428     if (shouldUseStackSafetyAnalysis(TargetTriple, DisableOptimization)) {
429       // We cannot call getAnalysis in doInitialization, that would cause a
430       // crash as the required analyses are not initialized yet.
431       HWASan->setSSI(
432           &getAnalysis<StackSafetyGlobalInfoWrapperPass>().getResult());
433     }
434     return HWASan->sanitizeFunction(
435         F,
436         [&]() -> const DominatorTree & {
437           return getAnalysis<DominatorTreeWrapperPass>().getDomTree();
438         },
439         [&]() -> const PostDominatorTree & {
440           return getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
441         });
442   }
443 
444   bool doFinalization(Module &M) override {
445     HWASan.reset();
446     return false;
447   }
448 
449   void getAnalysisUsage(AnalysisUsage &AU) const override {
450     // This is an over-estimation of, in case we are building for an
451     // architecture that doesn't allow stack tagging we will still load the
452     // analysis.
453     // This is so we don't need to plumb TargetTriple all the way to here.
454     if (mightUseStackSafetyAnalysis(DisableOptimization))
455       AU.addRequired<StackSafetyGlobalInfoWrapperPass>();
456     AU.addRequired<DominatorTreeWrapperPass>();
457     AU.addRequired<PostDominatorTreeWrapperPass>();
458   }
459 
460 private:
461   std::unique_ptr<HWAddressSanitizer> HWASan;
462   bool CompileKernel;
463   bool Recover;
464   bool DisableOptimization;
465 };
466 
467 } // end anonymous namespace
468 
469 char HWAddressSanitizerLegacyPass::ID = 0;
470 
471 INITIALIZE_PASS_BEGIN(
472     HWAddressSanitizerLegacyPass, "hwasan",
473     "HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
474     false)
475 INITIALIZE_PASS_DEPENDENCY(StackSafetyGlobalInfoWrapperPass)
476 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
477 INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
478 INITIALIZE_PASS_END(
479     HWAddressSanitizerLegacyPass, "hwasan",
480     "HWAddressSanitizer: detect memory bugs using tagged addressing.", false,
481     false)
482 
483 FunctionPass *
484 llvm::createHWAddressSanitizerLegacyPassPass(bool CompileKernel, bool Recover,
485                                              bool DisableOptimization) {
486   assert(!CompileKernel || Recover);
487   return new HWAddressSanitizerLegacyPass(CompileKernel, Recover,
488                                           DisableOptimization);
489 }
490 
491 PreservedAnalyses HWAddressSanitizerPass::run(Module &M,
492                                               ModuleAnalysisManager &MAM) {
493   const StackSafetyGlobalInfo *SSI = nullptr;
494   auto TargetTriple = llvm::Triple(M.getTargetTriple());
495   if (shouldUseStackSafetyAnalysis(TargetTriple, Options.DisableOptimization))
496     SSI = &MAM.getResult<StackSafetyGlobalAnalysis>(M);
497 
498   HWAddressSanitizer HWASan(M, Options.CompileKernel, Options.Recover, SSI);
499   bool Modified = false;
500   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
501   for (Function &F : M) {
502     Modified |= HWASan.sanitizeFunction(
503         F,
504         [&]() -> const DominatorTree & {
505           return FAM.getResult<DominatorTreeAnalysis>(F);
506         },
507         [&]() -> const PostDominatorTree & {
508           return FAM.getResult<PostDominatorTreeAnalysis>(F);
509         });
510   }
511   if (Modified)
512     return PreservedAnalyses::none();
513   return PreservedAnalyses::all();
514 }
515 void HWAddressSanitizerPass::printPipeline(
516     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
517   static_cast<PassInfoMixin<HWAddressSanitizerPass> *>(this)->printPipeline(
518       OS, MapClassName2PassName);
519   OS << "<";
520   if (Options.CompileKernel)
521     OS << "kernel;";
522   if (Options.Recover)
523     OS << "recover";
524   OS << ">";
525 }
526 
527 void HWAddressSanitizer::createHwasanCtorComdat() {
528   std::tie(HwasanCtorFunction, std::ignore) =
529       getOrCreateSanitizerCtorAndInitFunctions(
530           M, kHwasanModuleCtorName, kHwasanInitName,
531           /*InitArgTypes=*/{},
532           /*InitArgs=*/{},
533           // This callback is invoked when the functions are created the first
534           // time. Hook them into the global ctors list in that case:
535           [&](Function *Ctor, FunctionCallee) {
536             Comdat *CtorComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
537             Ctor->setComdat(CtorComdat);
538             appendToGlobalCtors(M, Ctor, 0, Ctor);
539           });
540 
541   // Create a note that contains pointers to the list of global
542   // descriptors. Adding a note to the output file will cause the linker to
543   // create a PT_NOTE program header pointing to the note that we can use to
544   // find the descriptor list starting from the program headers. A function
545   // provided by the runtime initializes the shadow memory for the globals by
546   // accessing the descriptor list via the note. The dynamic loader needs to
547   // call this function whenever a library is loaded.
548   //
549   // The reason why we use a note for this instead of a more conventional
550   // approach of having a global constructor pass a descriptor list pointer to
551   // the runtime is because of an order of initialization problem. With
552   // constructors we can encounter the following problematic scenario:
553   //
554   // 1) library A depends on library B and also interposes one of B's symbols
555   // 2) B's constructors are called before A's (as required for correctness)
556   // 3) during construction, B accesses one of its "own" globals (actually
557   //    interposed by A) and triggers a HWASAN failure due to the initialization
558   //    for A not having happened yet
559   //
560   // Even without interposition it is possible to run into similar situations in
561   // cases where two libraries mutually depend on each other.
562   //
563   // We only need one note per binary, so put everything for the note in a
564   // comdat. This needs to be a comdat with an .init_array section to prevent
565   // newer versions of lld from discarding the note.
566   //
567   // Create the note even if we aren't instrumenting globals. This ensures that
568   // binaries linked from object files with both instrumented and
569   // non-instrumented globals will end up with a note, even if a comdat from an
570   // object file with non-instrumented globals is selected. The note is harmless
571   // if the runtime doesn't support it, since it will just be ignored.
572   Comdat *NoteComdat = M.getOrInsertComdat(kHwasanModuleCtorName);
573 
574   Type *Int8Arr0Ty = ArrayType::get(Int8Ty, 0);
575   auto Start =
576       new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
577                          nullptr, "__start_hwasan_globals");
578   Start->setVisibility(GlobalValue::HiddenVisibility);
579   Start->setDSOLocal(true);
580   auto Stop =
581       new GlobalVariable(M, Int8Arr0Ty, true, GlobalVariable::ExternalLinkage,
582                          nullptr, "__stop_hwasan_globals");
583   Stop->setVisibility(GlobalValue::HiddenVisibility);
584   Stop->setDSOLocal(true);
585 
586   // Null-terminated so actually 8 bytes, which are required in order to align
587   // the note properly.
588   auto *Name = ConstantDataArray::get(*C, "LLVM\0\0\0");
589 
590   auto *NoteTy = StructType::get(Int32Ty, Int32Ty, Int32Ty, Name->getType(),
591                                  Int32Ty, Int32Ty);
592   auto *Note =
593       new GlobalVariable(M, NoteTy, /*isConstant=*/true,
594                          GlobalValue::PrivateLinkage, nullptr, kHwasanNoteName);
595   Note->setSection(".note.hwasan.globals");
596   Note->setComdat(NoteComdat);
597   Note->setAlignment(Align(4));
598   Note->setDSOLocal(true);
599 
600   // The pointers in the note need to be relative so that the note ends up being
601   // placed in rodata, which is the standard location for notes.
602   auto CreateRelPtr = [&](Constant *Ptr) {
603     return ConstantExpr::getTrunc(
604         ConstantExpr::getSub(ConstantExpr::getPtrToInt(Ptr, Int64Ty),
605                              ConstantExpr::getPtrToInt(Note, Int64Ty)),
606         Int32Ty);
607   };
608   Note->setInitializer(ConstantStruct::getAnon(
609       {ConstantInt::get(Int32Ty, 8),                           // n_namesz
610        ConstantInt::get(Int32Ty, 8),                           // n_descsz
611        ConstantInt::get(Int32Ty, ELF::NT_LLVM_HWASAN_GLOBALS), // n_type
612        Name, CreateRelPtr(Start), CreateRelPtr(Stop)}));
613   appendToCompilerUsed(M, Note);
614 
615   // Create a zero-length global in hwasan_globals so that the linker will
616   // always create start and stop symbols.
617   auto Dummy = new GlobalVariable(
618       M, Int8Arr0Ty, /*isConstantGlobal*/ true, GlobalVariable::PrivateLinkage,
619       Constant::getNullValue(Int8Arr0Ty), "hwasan.dummy.global");
620   Dummy->setSection("hwasan_globals");
621   Dummy->setComdat(NoteComdat);
622   Dummy->setMetadata(LLVMContext::MD_associated,
623                      MDNode::get(*C, ValueAsMetadata::get(Note)));
624   appendToCompilerUsed(M, Dummy);
625 }
626 
627 /// Module-level initialization.
628 ///
629 /// inserts a call to __hwasan_init to the module's constructor list.
630 void HWAddressSanitizer::initializeModule() {
631   LLVM_DEBUG(dbgs() << "Init " << M.getName() << "\n");
632   auto &DL = M.getDataLayout();
633 
634   TargetTriple = Triple(M.getTargetTriple());
635 
636   // x86_64 currently has two modes:
637   // - Intel LAM (default)
638   // - pointer aliasing (heap only)
639   bool IsX86_64 = TargetTriple.getArch() == Triple::x86_64;
640   UsePageAliases = shouldUsePageAliases(TargetTriple);
641   InstrumentWithCalls = shouldInstrumentWithCalls(TargetTriple);
642   InstrumentStack = shouldInstrumentStack(TargetTriple);
643   DetectUseAfterScope = shouldDetectUseAfterScope(TargetTriple);
644   PointerTagShift = IsX86_64 ? 57 : 56;
645   TagMaskByte = IsX86_64 ? 0x3F : 0xFF;
646 
647   Mapping.init(TargetTriple, InstrumentWithCalls);
648 
649   C = &(M.getContext());
650   IRBuilder<> IRB(*C);
651   IntptrTy = IRB.getIntPtrTy(DL);
652   Int8PtrTy = IRB.getInt8PtrTy();
653   Int8Ty = IRB.getInt8Ty();
654   Int32Ty = IRB.getInt32Ty();
655 
656   HwasanCtorFunction = nullptr;
657 
658   // Older versions of Android do not have the required runtime support for
659   // short granules, global or personality function instrumentation. On other
660   // platforms we currently require using the latest version of the runtime.
661   bool NewRuntime =
662       !TargetTriple.isAndroid() || !TargetTriple.isAndroidVersionLT(30);
663 
664   UseShortGranules =
665       ClUseShortGranules.getNumOccurrences() ? ClUseShortGranules : NewRuntime;
666   OutlinedChecks =
667       TargetTriple.isAArch64() && TargetTriple.isOSBinFormatELF() &&
668       (ClInlineAllChecks.getNumOccurrences() ? !ClInlineAllChecks : !Recover);
669 
670   if (ClMatchAllTag.getNumOccurrences()) {
671     if (ClMatchAllTag != -1) {
672       HasMatchAllTag = true;
673       MatchAllTag = ClMatchAllTag & 0xFF;
674     }
675   } else if (CompileKernel) {
676     HasMatchAllTag = true;
677     MatchAllTag = 0xFF;
678   }
679 
680   // If we don't have personality function support, fall back to landing pads.
681   InstrumentLandingPads = ClInstrumentLandingPads.getNumOccurrences()
682                               ? ClInstrumentLandingPads
683                               : !NewRuntime;
684 
685   if (!CompileKernel) {
686     createHwasanCtorComdat();
687     bool InstrumentGlobals =
688         ClGlobals.getNumOccurrences() ? ClGlobals : NewRuntime;
689 
690     if (InstrumentGlobals && !UsePageAliases)
691       instrumentGlobals();
692 
693     bool InstrumentPersonalityFunctions =
694         ClInstrumentPersonalityFunctions.getNumOccurrences()
695             ? ClInstrumentPersonalityFunctions
696             : NewRuntime;
697     if (InstrumentPersonalityFunctions)
698       instrumentPersonalityFunctions();
699   }
700 
701   if (!TargetTriple.isAndroid()) {
702     Constant *C = M.getOrInsertGlobal("__hwasan_tls", IntptrTy, [&] {
703       auto *GV = new GlobalVariable(M, IntptrTy, /*isConstant=*/false,
704                                     GlobalValue::ExternalLinkage, nullptr,
705                                     "__hwasan_tls", nullptr,
706                                     GlobalVariable::InitialExecTLSModel);
707       appendToCompilerUsed(M, GV);
708       return GV;
709     });
710     ThreadPtrGlobal = cast<GlobalVariable>(C);
711   }
712 }
713 
714 void HWAddressSanitizer::initializeCallbacks(Module &M) {
715   IRBuilder<> IRB(*C);
716   for (size_t AccessIsWrite = 0; AccessIsWrite <= 1; AccessIsWrite++) {
717     const std::string TypeStr = AccessIsWrite ? "store" : "load";
718     const std::string EndingStr = Recover ? "_noabort" : "";
719 
720     HwasanMemoryAccessCallbackSized[AccessIsWrite] = M.getOrInsertFunction(
721         ClMemoryAccessCallbackPrefix + TypeStr + "N" + EndingStr,
722         FunctionType::get(IRB.getVoidTy(), {IntptrTy, IntptrTy}, false));
723 
724     for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
725          AccessSizeIndex++) {
726       HwasanMemoryAccessCallback[AccessIsWrite][AccessSizeIndex] =
727           M.getOrInsertFunction(
728               ClMemoryAccessCallbackPrefix + TypeStr +
729                   itostr(1ULL << AccessSizeIndex) + EndingStr,
730               FunctionType::get(IRB.getVoidTy(), {IntptrTy}, false));
731     }
732   }
733 
734   HwasanTagMemoryFunc = M.getOrInsertFunction(
735       "__hwasan_tag_memory", IRB.getVoidTy(), Int8PtrTy, Int8Ty, IntptrTy);
736   HwasanGenerateTagFunc =
737       M.getOrInsertFunction("__hwasan_generate_tag", Int8Ty);
738 
739   ShadowGlobal = M.getOrInsertGlobal("__hwasan_shadow",
740                                      ArrayType::get(IRB.getInt8Ty(), 0));
741 
742   const std::string MemIntrinCallbackPrefix =
743       CompileKernel ? std::string("") : ClMemoryAccessCallbackPrefix;
744   HWAsanMemmove = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memmove",
745                                         IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
746                                         IRB.getInt8PtrTy(), IntptrTy);
747   HWAsanMemcpy = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memcpy",
748                                        IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
749                                        IRB.getInt8PtrTy(), IntptrTy);
750   HWAsanMemset = M.getOrInsertFunction(MemIntrinCallbackPrefix + "memset",
751                                        IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
752                                        IRB.getInt32Ty(), IntptrTy);
753 
754   HWAsanHandleVfork =
755       M.getOrInsertFunction("__hwasan_handle_vfork", IRB.getVoidTy(), IntptrTy);
756 }
757 
758 Value *HWAddressSanitizer::getOpaqueNoopCast(IRBuilder<> &IRB, Value *Val) {
759   // An empty inline asm with input reg == output reg.
760   // An opaque no-op cast, basically.
761   // This prevents code bloat as a result of rematerializing trivial definitions
762   // such as constants or global addresses at every load and store.
763   InlineAsm *Asm =
764       InlineAsm::get(FunctionType::get(Int8PtrTy, {Val->getType()}, false),
765                      StringRef(""), StringRef("=r,0"),
766                      /*hasSideEffects=*/false);
767   return IRB.CreateCall(Asm, {Val}, ".hwasan.shadow");
768 }
769 
770 Value *HWAddressSanitizer::getDynamicShadowIfunc(IRBuilder<> &IRB) {
771   return getOpaqueNoopCast(IRB, ShadowGlobal);
772 }
773 
774 Value *HWAddressSanitizer::getShadowNonTls(IRBuilder<> &IRB) {
775   if (Mapping.Offset != kDynamicShadowSentinel)
776     return getOpaqueNoopCast(
777         IRB, ConstantExpr::getIntToPtr(
778                  ConstantInt::get(IntptrTy, Mapping.Offset), Int8PtrTy));
779 
780   if (Mapping.InGlobal) {
781     return getDynamicShadowIfunc(IRB);
782   } else {
783     Value *GlobalDynamicAddress =
784         IRB.GetInsertBlock()->getParent()->getParent()->getOrInsertGlobal(
785             kHwasanShadowMemoryDynamicAddress, Int8PtrTy);
786     return IRB.CreateLoad(Int8PtrTy, GlobalDynamicAddress);
787   }
788 }
789 
790 bool HWAddressSanitizer::ignoreAccess(Instruction *Inst, Value *Ptr) {
791   // Do not instrument acesses from different address spaces; we cannot deal
792   // with them.
793   Type *PtrTy = cast<PointerType>(Ptr->getType()->getScalarType());
794   if (PtrTy->getPointerAddressSpace() != 0)
795     return true;
796 
797   // Ignore swifterror addresses.
798   // swifterror memory addresses are mem2reg promoted by instruction
799   // selection. As such they cannot have regular uses like an instrumentation
800   // function and it makes no sense to track them as memory.
801   if (Ptr->isSwiftError())
802     return true;
803 
804   if (findAllocaForValue(Ptr)) {
805     if (!InstrumentStack)
806       return true;
807     if (SSI && SSI->stackAccessIsSafe(*Inst))
808       return true;
809   }
810   return false;
811 }
812 
813 void HWAddressSanitizer::getInterestingMemoryOperands(
814     Instruction *I, SmallVectorImpl<InterestingMemoryOperand> &Interesting) {
815   // Skip memory accesses inserted by another instrumentation.
816   if (I->hasMetadata("nosanitize"))
817     return;
818 
819   // Do not instrument the load fetching the dynamic shadow address.
820   if (ShadowBase == I)
821     return;
822 
823   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
824     if (!ClInstrumentReads || ignoreAccess(I, LI->getPointerOperand()))
825       return;
826     Interesting.emplace_back(I, LI->getPointerOperandIndex(), false,
827                              LI->getType(), LI->getAlign());
828   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
829     if (!ClInstrumentWrites || ignoreAccess(I, SI->getPointerOperand()))
830       return;
831     Interesting.emplace_back(I, SI->getPointerOperandIndex(), true,
832                              SI->getValueOperand()->getType(), SI->getAlign());
833   } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
834     if (!ClInstrumentAtomics || ignoreAccess(I, RMW->getPointerOperand()))
835       return;
836     Interesting.emplace_back(I, RMW->getPointerOperandIndex(), true,
837                              RMW->getValOperand()->getType(), None);
838   } else if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I)) {
839     if (!ClInstrumentAtomics || ignoreAccess(I, XCHG->getPointerOperand()))
840       return;
841     Interesting.emplace_back(I, XCHG->getPointerOperandIndex(), true,
842                              XCHG->getCompareOperand()->getType(), None);
843   } else if (auto CI = dyn_cast<CallInst>(I)) {
844     for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ArgNo++) {
845       if (!ClInstrumentByval || !CI->isByValArgument(ArgNo) ||
846           ignoreAccess(I, CI->getArgOperand(ArgNo)))
847         continue;
848       Type *Ty = CI->getParamByValType(ArgNo);
849       Interesting.emplace_back(I, ArgNo, false, Ty, Align(1));
850     }
851   }
852 }
853 
854 static unsigned getPointerOperandIndex(Instruction *I) {
855   if (LoadInst *LI = dyn_cast<LoadInst>(I))
856     return LI->getPointerOperandIndex();
857   if (StoreInst *SI = dyn_cast<StoreInst>(I))
858     return SI->getPointerOperandIndex();
859   if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I))
860     return RMW->getPointerOperandIndex();
861   if (AtomicCmpXchgInst *XCHG = dyn_cast<AtomicCmpXchgInst>(I))
862     return XCHG->getPointerOperandIndex();
863   report_fatal_error("Unexpected instruction");
864   return -1;
865 }
866 
867 static size_t TypeSizeToSizeIndex(uint32_t TypeSize) {
868   size_t Res = countTrailingZeros(TypeSize / 8);
869   assert(Res < kNumberOfAccessSizes);
870   return Res;
871 }
872 
873 void HWAddressSanitizer::untagPointerOperand(Instruction *I, Value *Addr) {
874   if (TargetTriple.isAArch64() || TargetTriple.getArch() == Triple::x86_64)
875     return;
876 
877   IRBuilder<> IRB(I);
878   Value *AddrLong = IRB.CreatePointerCast(Addr, IntptrTy);
879   Value *UntaggedPtr =
880       IRB.CreateIntToPtr(untagPointer(IRB, AddrLong), Addr->getType());
881   I->setOperand(getPointerOperandIndex(I), UntaggedPtr);
882 }
883 
884 Value *HWAddressSanitizer::memToShadow(Value *Mem, IRBuilder<> &IRB) {
885   // Mem >> Scale
886   Value *Shadow = IRB.CreateLShr(Mem, Mapping.Scale);
887   if (Mapping.Offset == 0)
888     return IRB.CreateIntToPtr(Shadow, Int8PtrTy);
889   // (Mem >> Scale) + Offset
890   return IRB.CreateGEP(Int8Ty, ShadowBase, Shadow);
891 }
892 
893 int64_t HWAddressSanitizer::getAccessInfo(bool IsWrite,
894                                           unsigned AccessSizeIndex) {
895   return (CompileKernel << HWASanAccessInfo::CompileKernelShift) +
896          (HasMatchAllTag << HWASanAccessInfo::HasMatchAllShift) +
897          (MatchAllTag << HWASanAccessInfo::MatchAllShift) +
898          (Recover << HWASanAccessInfo::RecoverShift) +
899          (IsWrite << HWASanAccessInfo::IsWriteShift) +
900          (AccessSizeIndex << HWASanAccessInfo::AccessSizeShift);
901 }
902 
903 void HWAddressSanitizer::instrumentMemAccessOutline(Value *Ptr, bool IsWrite,
904                                                     unsigned AccessSizeIndex,
905                                                     Instruction *InsertBefore) {
906   assert(!UsePageAliases);
907   const int64_t AccessInfo = getAccessInfo(IsWrite, AccessSizeIndex);
908   IRBuilder<> IRB(InsertBefore);
909   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
910   Ptr = IRB.CreateBitCast(Ptr, Int8PtrTy);
911   IRB.CreateCall(Intrinsic::getDeclaration(
912                      M, UseShortGranules
913                             ? Intrinsic::hwasan_check_memaccess_shortgranules
914                             : Intrinsic::hwasan_check_memaccess),
915                  {ShadowBase, Ptr, ConstantInt::get(Int32Ty, AccessInfo)});
916 }
917 
918 void HWAddressSanitizer::instrumentMemAccessInline(Value *Ptr, bool IsWrite,
919                                                    unsigned AccessSizeIndex,
920                                                    Instruction *InsertBefore) {
921   assert(!UsePageAliases);
922   const int64_t AccessInfo = getAccessInfo(IsWrite, AccessSizeIndex);
923   IRBuilder<> IRB(InsertBefore);
924 
925   Value *PtrLong = IRB.CreatePointerCast(Ptr, IntptrTy);
926   Value *PtrTag = IRB.CreateTrunc(IRB.CreateLShr(PtrLong, PointerTagShift),
927                                   IRB.getInt8Ty());
928   Value *AddrLong = untagPointer(IRB, PtrLong);
929   Value *Shadow = memToShadow(AddrLong, IRB);
930   Value *MemTag = IRB.CreateLoad(Int8Ty, Shadow);
931   Value *TagMismatch = IRB.CreateICmpNE(PtrTag, MemTag);
932 
933   if (HasMatchAllTag) {
934     Value *TagNotIgnored = IRB.CreateICmpNE(
935         PtrTag, ConstantInt::get(PtrTag->getType(), MatchAllTag));
936     TagMismatch = IRB.CreateAnd(TagMismatch, TagNotIgnored);
937   }
938 
939   Instruction *CheckTerm =
940       SplitBlockAndInsertIfThen(TagMismatch, InsertBefore, false,
941                                 MDBuilder(*C).createBranchWeights(1, 100000));
942 
943   IRB.SetInsertPoint(CheckTerm);
944   Value *OutOfShortGranuleTagRange =
945       IRB.CreateICmpUGT(MemTag, ConstantInt::get(Int8Ty, 15));
946   Instruction *CheckFailTerm =
947       SplitBlockAndInsertIfThen(OutOfShortGranuleTagRange, CheckTerm, !Recover,
948                                 MDBuilder(*C).createBranchWeights(1, 100000));
949 
950   IRB.SetInsertPoint(CheckTerm);
951   Value *PtrLowBits = IRB.CreateTrunc(IRB.CreateAnd(PtrLong, 15), Int8Ty);
952   PtrLowBits = IRB.CreateAdd(
953       PtrLowBits, ConstantInt::get(Int8Ty, (1 << AccessSizeIndex) - 1));
954   Value *PtrLowBitsOOB = IRB.CreateICmpUGE(PtrLowBits, MemTag);
955   SplitBlockAndInsertIfThen(PtrLowBitsOOB, CheckTerm, false,
956                             MDBuilder(*C).createBranchWeights(1, 100000),
957                             (DomTreeUpdater *)nullptr, nullptr,
958                             CheckFailTerm->getParent());
959 
960   IRB.SetInsertPoint(CheckTerm);
961   Value *InlineTagAddr = IRB.CreateOr(AddrLong, 15);
962   InlineTagAddr = IRB.CreateIntToPtr(InlineTagAddr, Int8PtrTy);
963   Value *InlineTag = IRB.CreateLoad(Int8Ty, InlineTagAddr);
964   Value *InlineTagMismatch = IRB.CreateICmpNE(PtrTag, InlineTag);
965   SplitBlockAndInsertIfThen(InlineTagMismatch, CheckTerm, false,
966                             MDBuilder(*C).createBranchWeights(1, 100000),
967                             (DomTreeUpdater *)nullptr, nullptr,
968                             CheckFailTerm->getParent());
969 
970   IRB.SetInsertPoint(CheckFailTerm);
971   InlineAsm *Asm;
972   switch (TargetTriple.getArch()) {
973   case Triple::x86_64:
974     // The signal handler will find the data address in rdi.
975     Asm = InlineAsm::get(
976         FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
977         "int3\nnopl " +
978             itostr(0x40 + (AccessInfo & HWASanAccessInfo::RuntimeMask)) +
979             "(%rax)",
980         "{rdi}",
981         /*hasSideEffects=*/true);
982     break;
983   case Triple::aarch64:
984   case Triple::aarch64_be:
985     // The signal handler will find the data address in x0.
986     Asm = InlineAsm::get(
987         FunctionType::get(IRB.getVoidTy(), {PtrLong->getType()}, false),
988         "brk #" + itostr(0x900 + (AccessInfo & HWASanAccessInfo::RuntimeMask)),
989         "{x0}",
990         /*hasSideEffects=*/true);
991     break;
992   default:
993     report_fatal_error("unsupported architecture");
994   }
995   IRB.CreateCall(Asm, PtrLong);
996   if (Recover)
997     cast<BranchInst>(CheckFailTerm)->setSuccessor(0, CheckTerm->getParent());
998 }
999 
1000 bool HWAddressSanitizer::ignoreMemIntrinsic(MemIntrinsic *MI) {
1001   if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1002     return (!ClInstrumentWrites || ignoreAccess(MTI, MTI->getDest())) &&
1003            (!ClInstrumentReads || ignoreAccess(MTI, MTI->getSource()));
1004   }
1005   if (isa<MemSetInst>(MI))
1006     return !ClInstrumentWrites || ignoreAccess(MI, MI->getDest());
1007   return false;
1008 }
1009 
1010 void HWAddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
1011   IRBuilder<> IRB(MI);
1012   if (isa<MemTransferInst>(MI)) {
1013     IRB.CreateCall(
1014         isa<MemMoveInst>(MI) ? HWAsanMemmove : HWAsanMemcpy,
1015         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1016          IRB.CreatePointerCast(MI->getOperand(1), IRB.getInt8PtrTy()),
1017          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1018   } else if (isa<MemSetInst>(MI)) {
1019     IRB.CreateCall(
1020         HWAsanMemset,
1021         {IRB.CreatePointerCast(MI->getOperand(0), IRB.getInt8PtrTy()),
1022          IRB.CreateIntCast(MI->getOperand(1), IRB.getInt32Ty(), false),
1023          IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
1024   }
1025   MI->eraseFromParent();
1026 }
1027 
1028 bool HWAddressSanitizer::instrumentMemAccess(InterestingMemoryOperand &O) {
1029   Value *Addr = O.getPtr();
1030 
1031   LLVM_DEBUG(dbgs() << "Instrumenting: " << O.getInsn() << "\n");
1032 
1033   if (O.MaybeMask)
1034     return false; // FIXME
1035 
1036   IRBuilder<> IRB(O.getInsn());
1037   if (isPowerOf2_64(O.TypeSize) &&
1038       (O.TypeSize / 8 <= (1ULL << (kNumberOfAccessSizes - 1))) &&
1039       (!O.Alignment || *O.Alignment >= (1ULL << Mapping.Scale) ||
1040        *O.Alignment >= O.TypeSize / 8)) {
1041     size_t AccessSizeIndex = TypeSizeToSizeIndex(O.TypeSize);
1042     if (InstrumentWithCalls) {
1043       IRB.CreateCall(HwasanMemoryAccessCallback[O.IsWrite][AccessSizeIndex],
1044                      IRB.CreatePointerCast(Addr, IntptrTy));
1045     } else if (OutlinedChecks) {
1046       instrumentMemAccessOutline(Addr, O.IsWrite, AccessSizeIndex, O.getInsn());
1047     } else {
1048       instrumentMemAccessInline(Addr, O.IsWrite, AccessSizeIndex, O.getInsn());
1049     }
1050   } else {
1051     IRB.CreateCall(HwasanMemoryAccessCallbackSized[O.IsWrite],
1052                    {IRB.CreatePointerCast(Addr, IntptrTy),
1053                     ConstantInt::get(IntptrTy, O.TypeSize / 8)});
1054   }
1055   untagPointerOperand(O.getInsn(), Addr);
1056 
1057   return true;
1058 }
1059 
1060 static uint64_t getAllocaSizeInBytes(const AllocaInst &AI) {
1061   auto DL = AI.getModule()->getDataLayout();
1062   return AI.getAllocationSizeInBits(DL).getValue() / 8;
1063 }
1064 
1065 void HWAddressSanitizer::tagAlloca(IRBuilder<> &IRB, AllocaInst *AI, Value *Tag,
1066                                    size_t Size) {
1067   size_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
1068   if (!UseShortGranules)
1069     Size = AlignedSize;
1070 
1071   Value *JustTag = IRB.CreateTrunc(Tag, IRB.getInt8Ty());
1072   if (InstrumentWithCalls) {
1073     IRB.CreateCall(HwasanTagMemoryFunc,
1074                    {IRB.CreatePointerCast(AI, Int8PtrTy), JustTag,
1075                     ConstantInt::get(IntptrTy, AlignedSize)});
1076   } else {
1077     size_t ShadowSize = Size >> Mapping.Scale;
1078     Value *ShadowPtr = memToShadow(IRB.CreatePointerCast(AI, IntptrTy), IRB);
1079     // If this memset is not inlined, it will be intercepted in the hwasan
1080     // runtime library. That's OK, because the interceptor skips the checks if
1081     // the address is in the shadow region.
1082     // FIXME: the interceptor is not as fast as real memset. Consider lowering
1083     // llvm.memset right here into either a sequence of stores, or a call to
1084     // hwasan_tag_memory.
1085     if (ShadowSize)
1086       IRB.CreateMemSet(ShadowPtr, JustTag, ShadowSize, Align(1));
1087     if (Size != AlignedSize) {
1088       IRB.CreateStore(
1089           ConstantInt::get(Int8Ty, Size % Mapping.getObjectAlignment()),
1090           IRB.CreateConstGEP1_32(Int8Ty, ShadowPtr, ShadowSize));
1091       IRB.CreateStore(JustTag, IRB.CreateConstGEP1_32(
1092                                    Int8Ty, IRB.CreateBitCast(AI, Int8PtrTy),
1093                                    AlignedSize - 1));
1094     }
1095   }
1096 }
1097 
1098 unsigned HWAddressSanitizer::retagMask(unsigned AllocaNo) {
1099   if (TargetTriple.getArch() == Triple::x86_64)
1100     return AllocaNo & TagMaskByte;
1101 
1102   // A list of 8-bit numbers that have at most one run of non-zero bits.
1103   // x = x ^ (mask << 56) can be encoded as a single armv8 instruction for these
1104   // masks.
1105   // The list does not include the value 255, which is used for UAR.
1106   //
1107   // Because we are more likely to use earlier elements of this list than later
1108   // ones, it is sorted in increasing order of probability of collision with a
1109   // mask allocated (temporally) nearby. The program that generated this list
1110   // can be found at:
1111   // https://github.com/google/sanitizers/blob/master/hwaddress-sanitizer/sort_masks.py
1112   static unsigned FastMasks[] = {0,  128, 64,  192, 32,  96,  224, 112, 240,
1113                                  48, 16,  120, 248, 56,  24,  8,   124, 252,
1114                                  60, 28,  12,  4,   126, 254, 62,  30,  14,
1115                                  6,  2,   127, 63,  31,  15,  7,   3,   1};
1116   return FastMasks[AllocaNo % (sizeof(FastMasks) / sizeof(FastMasks[0]))];
1117 }
1118 
1119 Value *HWAddressSanitizer::applyTagMask(IRBuilder<> &IRB, Value *OldTag) {
1120   if (TargetTriple.getArch() == Triple::x86_64) {
1121     Constant *TagMask = ConstantInt::get(IntptrTy, TagMaskByte);
1122     Value *NewTag = IRB.CreateAnd(OldTag, TagMask);
1123     return NewTag;
1124   }
1125   // aarch64 uses 8-bit tags, so no mask is needed.
1126   return OldTag;
1127 }
1128 
1129 Value *HWAddressSanitizer::getNextTagWithCall(IRBuilder<> &IRB) {
1130   return IRB.CreateZExt(IRB.CreateCall(HwasanGenerateTagFunc), IntptrTy);
1131 }
1132 
1133 Value *HWAddressSanitizer::getStackBaseTag(IRBuilder<> &IRB) {
1134   if (ClGenerateTagsWithCalls)
1135     return getNextTagWithCall(IRB);
1136   if (StackBaseTag)
1137     return StackBaseTag;
1138   // FIXME: use addressofreturnaddress (but implement it in aarch64 backend
1139   // first).
1140   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1141   auto GetStackPointerFn = Intrinsic::getDeclaration(
1142       M, Intrinsic::frameaddress,
1143       IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
1144   Value *StackPointer = IRB.CreateCall(
1145       GetStackPointerFn, {Constant::getNullValue(IRB.getInt32Ty())});
1146 
1147   // Extract some entropy from the stack pointer for the tags.
1148   // Take bits 20..28 (ASLR entropy) and xor with bits 0..8 (these differ
1149   // between functions).
1150   Value *StackPointerLong = IRB.CreatePointerCast(StackPointer, IntptrTy);
1151   Value *StackTag =
1152       applyTagMask(IRB, IRB.CreateXor(StackPointerLong,
1153                                       IRB.CreateLShr(StackPointerLong, 20)));
1154   StackTag->setName("hwasan.stack.base.tag");
1155   return StackTag;
1156 }
1157 
1158 Value *HWAddressSanitizer::getAllocaTag(IRBuilder<> &IRB, Value *StackTag,
1159                                         AllocaInst *AI, unsigned AllocaNo) {
1160   if (ClGenerateTagsWithCalls)
1161     return getNextTagWithCall(IRB);
1162   return IRB.CreateXor(StackTag,
1163                        ConstantInt::get(IntptrTy, retagMask(AllocaNo)));
1164 }
1165 
1166 Value *HWAddressSanitizer::getUARTag(IRBuilder<> &IRB, Value *StackTag) {
1167   if (ClUARRetagToZero)
1168     return ConstantInt::get(IntptrTy, 0);
1169   if (ClGenerateTagsWithCalls)
1170     return getNextTagWithCall(IRB);
1171   return IRB.CreateXor(StackTag, ConstantInt::get(IntptrTy, TagMaskByte));
1172 }
1173 
1174 // Add a tag to an address.
1175 Value *HWAddressSanitizer::tagPointer(IRBuilder<> &IRB, Type *Ty,
1176                                       Value *PtrLong, Value *Tag) {
1177   assert(!UsePageAliases);
1178   Value *TaggedPtrLong;
1179   if (CompileKernel) {
1180     // Kernel addresses have 0xFF in the most significant byte.
1181     Value *ShiftedTag =
1182         IRB.CreateOr(IRB.CreateShl(Tag, PointerTagShift),
1183                      ConstantInt::get(IntptrTy, (1ULL << PointerTagShift) - 1));
1184     TaggedPtrLong = IRB.CreateAnd(PtrLong, ShiftedTag);
1185   } else {
1186     // Userspace can simply do OR (tag << PointerTagShift);
1187     Value *ShiftedTag = IRB.CreateShl(Tag, PointerTagShift);
1188     TaggedPtrLong = IRB.CreateOr(PtrLong, ShiftedTag);
1189   }
1190   return IRB.CreateIntToPtr(TaggedPtrLong, Ty);
1191 }
1192 
1193 // Remove tag from an address.
1194 Value *HWAddressSanitizer::untagPointer(IRBuilder<> &IRB, Value *PtrLong) {
1195   assert(!UsePageAliases);
1196   Value *UntaggedPtrLong;
1197   if (CompileKernel) {
1198     // Kernel addresses have 0xFF in the most significant byte.
1199     UntaggedPtrLong =
1200         IRB.CreateOr(PtrLong, ConstantInt::get(PtrLong->getType(),
1201                                                0xFFULL << PointerTagShift));
1202   } else {
1203     // Userspace addresses have 0x00.
1204     UntaggedPtrLong =
1205         IRB.CreateAnd(PtrLong, ConstantInt::get(PtrLong->getType(),
1206                                                 ~(0xFFULL << PointerTagShift)));
1207   }
1208   return UntaggedPtrLong;
1209 }
1210 
1211 Value *HWAddressSanitizer::getHwasanThreadSlotPtr(IRBuilder<> &IRB, Type *Ty) {
1212   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1213   if (TargetTriple.isAArch64() && TargetTriple.isAndroid()) {
1214     // Android provides a fixed TLS slot for sanitizers. See TLS_SLOT_SANITIZER
1215     // in Bionic's libc/private/bionic_tls.h.
1216     Function *ThreadPointerFunc =
1217         Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
1218     Value *SlotPtr = IRB.CreatePointerCast(
1219         IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
1220                                IRB.CreateCall(ThreadPointerFunc), 0x30),
1221         Ty->getPointerTo(0));
1222     return SlotPtr;
1223   }
1224   if (ThreadPtrGlobal)
1225     return ThreadPtrGlobal;
1226 
1227   return nullptr;
1228 }
1229 
1230 void HWAddressSanitizer::emitPrologue(IRBuilder<> &IRB, bool WithFrameRecord) {
1231   if (!Mapping.InTls)
1232     ShadowBase = getShadowNonTls(IRB);
1233   else if (!WithFrameRecord && TargetTriple.isAndroid())
1234     ShadowBase = getDynamicShadowIfunc(IRB);
1235 
1236   if (!WithFrameRecord && ShadowBase)
1237     return;
1238 
1239   Value *SlotPtr = getHwasanThreadSlotPtr(IRB, IntptrTy);
1240   assert(SlotPtr);
1241 
1242   Value *ThreadLong = IRB.CreateLoad(IntptrTy, SlotPtr);
1243   // Extract the address field from ThreadLong. Unnecessary on AArch64 with TBI.
1244   Value *ThreadLongMaybeUntagged =
1245       TargetTriple.isAArch64() ? ThreadLong : untagPointer(IRB, ThreadLong);
1246 
1247   if (WithFrameRecord) {
1248     Function *F = IRB.GetInsertBlock()->getParent();
1249     StackBaseTag = IRB.CreateAShr(ThreadLong, 3);
1250 
1251     // Prepare ring buffer data.
1252     Value *PC;
1253     if (TargetTriple.getArch() == Triple::aarch64)
1254       PC = readRegister(IRB, "pc");
1255     else
1256       PC = IRB.CreatePtrToInt(F, IntptrTy);
1257     Module *M = F->getParent();
1258     auto GetStackPointerFn = Intrinsic::getDeclaration(
1259         M, Intrinsic::frameaddress,
1260         IRB.getInt8PtrTy(M->getDataLayout().getAllocaAddrSpace()));
1261     Value *SP = IRB.CreatePtrToInt(
1262         IRB.CreateCall(GetStackPointerFn,
1263                        {Constant::getNullValue(IRB.getInt32Ty())}),
1264         IntptrTy);
1265     // Mix SP and PC.
1266     // Assumptions:
1267     // PC is 0x0000PPPPPPPPPPPP  (48 bits are meaningful, others are zero)
1268     // SP is 0xsssssssssssSSSS0  (4 lower bits are zero)
1269     // We only really need ~20 lower non-zero bits (SSSS), so we mix like this:
1270     //       0xSSSSPPPPPPPPPPPP
1271     SP = IRB.CreateShl(SP, 44);
1272 
1273     // Store data to ring buffer.
1274     Value *RecordPtr =
1275         IRB.CreateIntToPtr(ThreadLongMaybeUntagged, IntptrTy->getPointerTo(0));
1276     IRB.CreateStore(IRB.CreateOr(PC, SP), RecordPtr);
1277 
1278     // Update the ring buffer. Top byte of ThreadLong defines the size of the
1279     // buffer in pages, it must be a power of two, and the start of the buffer
1280     // must be aligned by twice that much. Therefore wrap around of the ring
1281     // buffer is simply Addr &= ~((ThreadLong >> 56) << 12).
1282     // The use of AShr instead of LShr is due to
1283     //   https://bugs.llvm.org/show_bug.cgi?id=39030
1284     // Runtime library makes sure not to use the highest bit.
1285     Value *WrapMask = IRB.CreateXor(
1286         IRB.CreateShl(IRB.CreateAShr(ThreadLong, 56), 12, "", true, true),
1287         ConstantInt::get(IntptrTy, (uint64_t)-1));
1288     Value *ThreadLongNew = IRB.CreateAnd(
1289         IRB.CreateAdd(ThreadLong, ConstantInt::get(IntptrTy, 8)), WrapMask);
1290     IRB.CreateStore(ThreadLongNew, SlotPtr);
1291   }
1292 
1293   if (!ShadowBase) {
1294     // Get shadow base address by aligning RecordPtr up.
1295     // Note: this is not correct if the pointer is already aligned.
1296     // Runtime library will make sure this never happens.
1297     ShadowBase = IRB.CreateAdd(
1298         IRB.CreateOr(
1299             ThreadLongMaybeUntagged,
1300             ConstantInt::get(IntptrTy, (1ULL << kShadowBaseAlignment) - 1)),
1301         ConstantInt::get(IntptrTy, 1), "hwasan.shadow");
1302     ShadowBase = IRB.CreateIntToPtr(ShadowBase, Int8PtrTy);
1303   }
1304 }
1305 
1306 Value *HWAddressSanitizer::readRegister(IRBuilder<> &IRB, StringRef Name) {
1307   Module *M = IRB.GetInsertBlock()->getParent()->getParent();
1308   Function *ReadRegister =
1309       Intrinsic::getDeclaration(M, Intrinsic::read_register, IntptrTy);
1310   MDNode *MD = MDNode::get(*C, {MDString::get(*C, Name)});
1311   Value *Args[] = {MetadataAsValue::get(*C, MD)};
1312   return IRB.CreateCall(ReadRegister, Args);
1313 }
1314 
1315 bool HWAddressSanitizer::instrumentLandingPads(
1316     SmallVectorImpl<Instruction *> &LandingPadVec) {
1317   for (auto *LP : LandingPadVec) {
1318     IRBuilder<> IRB(LP->getNextNode());
1319     IRB.CreateCall(
1320         HWAsanHandleVfork,
1321         {readRegister(IRB, (TargetTriple.getArch() == Triple::x86_64) ? "rsp"
1322                                                                       : "sp")});
1323   }
1324   return true;
1325 }
1326 
1327 bool HWAddressSanitizer::instrumentStack(
1328     bool ShouldDetectUseAfterScope,
1329     MapVector<AllocaInst *, AllocaInfo> &AllocasToInstrument,
1330     SmallVector<Instruction *, 4> &UnrecognizedLifetimes,
1331     DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> &AllocaDbgMap,
1332     SmallVectorImpl<Instruction *> &RetVec, Value *StackTag,
1333     llvm::function_ref<const DominatorTree &()> GetDT,
1334     llvm::function_ref<const PostDominatorTree &()> GetPDT) {
1335   // Ideally, we want to calculate tagged stack base pointer, and rewrite all
1336   // alloca addresses using that. Unfortunately, offsets are not known yet
1337   // (unless we use ASan-style mega-alloca). Instead we keep the base tag in a
1338   // temp, shift-OR it into each alloca address and xor with the retag mask.
1339   // This generates one extra instruction per alloca use.
1340   unsigned int I = 0;
1341 
1342   for (auto &KV : AllocasToInstrument) {
1343     auto N = I++;
1344     auto *AI = KV.first;
1345     AllocaInfo &Info = KV.second;
1346     IRBuilder<> IRB(AI->getNextNode());
1347 
1348     // Replace uses of the alloca with tagged address.
1349     Value *Tag = getAllocaTag(IRB, StackTag, AI, N);
1350     Value *AILong = IRB.CreatePointerCast(AI, IntptrTy);
1351     Value *Replacement = tagPointer(IRB, AI->getType(), AILong, Tag);
1352     std::string Name =
1353         AI->hasName() ? AI->getName().str() : "alloca." + itostr(N);
1354     Replacement->setName(Name + ".hwasan");
1355 
1356     AI->replaceUsesWithIf(Replacement,
1357                           [AILong](Use &U) { return U.getUser() != AILong; });
1358 
1359     for (auto *DDI : AllocaDbgMap.lookup(AI)) {
1360       // Prepend "tag_offset, N" to the dwarf expression.
1361       // Tag offset logically applies to the alloca pointer, and it makes sense
1362       // to put it at the beginning of the expression.
1363       SmallVector<uint64_t, 8> NewOps = {dwarf::DW_OP_LLVM_tag_offset,
1364                                          retagMask(N)};
1365       for (size_t LocNo = 0; LocNo < DDI->getNumVariableLocationOps(); ++LocNo)
1366         if (DDI->getVariableLocationOp(LocNo) == AI)
1367           DDI->setExpression(DIExpression::appendOpsToArg(DDI->getExpression(),
1368                                                           NewOps, LocNo));
1369     }
1370 
1371     size_t Size = getAllocaSizeInBytes(*AI);
1372     size_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
1373     auto TagEnd = [&](Instruction *Node) {
1374       IRB.SetInsertPoint(Node);
1375       Value *UARTag = getUARTag(IRB, StackTag);
1376       tagAlloca(IRB, AI, UARTag, AlignedSize);
1377     };
1378     bool StandardLifetime =
1379         UnrecognizedLifetimes.empty() &&
1380         isStandardLifetime(Info.LifetimeStart, Info.LifetimeEnd, &GetDT(),
1381                            ClMaxLifetimes);
1382     if (ShouldDetectUseAfterScope && StandardLifetime) {
1383       IntrinsicInst *Start = Info.LifetimeStart[0];
1384       IRB.SetInsertPoint(Start->getNextNode());
1385       tagAlloca(IRB, AI, Tag, Size);
1386       if (!forAllReachableExits(GetDT(), GetPDT(), Start, Info.LifetimeEnd,
1387                                 RetVec, TagEnd)) {
1388         for (auto *End : Info.LifetimeEnd)
1389           End->eraseFromParent();
1390       }
1391     } else {
1392       tagAlloca(IRB, AI, Tag, Size);
1393       for (auto *RI : RetVec)
1394         TagEnd(RI);
1395       if (!StandardLifetime) {
1396         for (auto &II : Info.LifetimeStart)
1397           II->eraseFromParent();
1398         for (auto &II : Info.LifetimeEnd)
1399           II->eraseFromParent();
1400       }
1401     }
1402   }
1403   for (auto &I : UnrecognizedLifetimes)
1404     I->eraseFromParent();
1405   return true;
1406 }
1407 
1408 bool HWAddressSanitizer::isInterestingAlloca(const AllocaInst &AI) {
1409   return (AI.getAllocatedType()->isSized() &&
1410           // FIXME: instrument dynamic allocas, too
1411           AI.isStaticAlloca() &&
1412           // alloca() may be called with 0 size, ignore it.
1413           getAllocaSizeInBytes(AI) > 0 &&
1414           // We are only interested in allocas not promotable to registers.
1415           // Promotable allocas are common under -O0.
1416           !isAllocaPromotable(&AI) &&
1417           // inalloca allocas are not treated as static, and we don't want
1418           // dynamic alloca instrumentation for them as well.
1419           !AI.isUsedWithInAlloca() &&
1420           // swifterror allocas are register promoted by ISel
1421           !AI.isSwiftError()) &&
1422          // safe allocas are not interesting
1423          !(SSI && SSI->isSafe(AI));
1424 }
1425 
1426 DenseMap<AllocaInst *, AllocaInst *> HWAddressSanitizer::padInterestingAllocas(
1427     const MapVector<AllocaInst *, AllocaInfo> &AllocasToInstrument) {
1428   DenseMap<AllocaInst *, AllocaInst *> AllocaToPaddedAllocaMap;
1429   for (auto &KV : AllocasToInstrument) {
1430     AllocaInst *AI = KV.first;
1431     uint64_t Size = getAllocaSizeInBytes(*AI);
1432     uint64_t AlignedSize = alignTo(Size, Mapping.getObjectAlignment());
1433     AI->setAlignment(
1434         Align(std::max(AI->getAlignment(), Mapping.getObjectAlignment())));
1435     if (Size != AlignedSize) {
1436       Type *AllocatedType = AI->getAllocatedType();
1437       if (AI->isArrayAllocation()) {
1438         uint64_t ArraySize =
1439             cast<ConstantInt>(AI->getArraySize())->getZExtValue();
1440         AllocatedType = ArrayType::get(AllocatedType, ArraySize);
1441       }
1442       Type *TypeWithPadding = StructType::get(
1443           AllocatedType, ArrayType::get(Int8Ty, AlignedSize - Size));
1444       auto *NewAI = new AllocaInst(
1445           TypeWithPadding, AI->getType()->getAddressSpace(), nullptr, "", AI);
1446       NewAI->takeName(AI);
1447       NewAI->setAlignment(AI->getAlign());
1448       NewAI->setUsedWithInAlloca(AI->isUsedWithInAlloca());
1449       NewAI->setSwiftError(AI->isSwiftError());
1450       NewAI->copyMetadata(*AI);
1451       auto *Bitcast = new BitCastInst(NewAI, AI->getType(), "", AI);
1452       AI->replaceAllUsesWith(Bitcast);
1453       AllocaToPaddedAllocaMap[AI] = NewAI;
1454     }
1455   }
1456   return AllocaToPaddedAllocaMap;
1457 }
1458 
1459 bool HWAddressSanitizer::sanitizeFunction(
1460     Function &F, llvm::function_ref<const DominatorTree &()> GetDT,
1461     llvm::function_ref<const PostDominatorTree &()> GetPDT) {
1462   if (&F == HwasanCtorFunction)
1463     return false;
1464 
1465   if (!F.hasFnAttribute(Attribute::SanitizeHWAddress))
1466     return false;
1467 
1468   LLVM_DEBUG(dbgs() << "Function: " << F.getName() << "\n");
1469 
1470   SmallVector<InterestingMemoryOperand, 16> OperandsToInstrument;
1471   SmallVector<MemIntrinsic *, 16> IntrinToInstrument;
1472   MapVector<AllocaInst *, AllocaInfo> AllocasToInstrument;
1473   SmallVector<Instruction *, 8> RetVec;
1474   SmallVector<Instruction *, 8> LandingPadVec;
1475   SmallVector<Instruction *, 4> UnrecognizedLifetimes;
1476   DenseMap<AllocaInst *, std::vector<DbgVariableIntrinsic *>> AllocaDbgMap;
1477   bool CallsReturnTwice = false;
1478   for (auto &Inst : instructions(F)) {
1479     if (CallInst *CI = dyn_cast<CallInst>(&Inst)) {
1480       if (CI->canReturnTwice()) {
1481         CallsReturnTwice = true;
1482       }
1483     }
1484     if (InstrumentStack) {
1485       if (AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
1486         if (isInterestingAlloca(*AI))
1487           AllocasToInstrument.insert({AI, {}});
1488         continue;
1489       }
1490       auto *II = dyn_cast<IntrinsicInst>(&Inst);
1491       if (II && (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1492                  II->getIntrinsicID() == Intrinsic::lifetime_end)) {
1493         AllocaInst *AI = findAllocaForValue(II->getArgOperand(1));
1494         if (!AI) {
1495           UnrecognizedLifetimes.push_back(&Inst);
1496           continue;
1497         }
1498         if (!isInterestingAlloca(*AI))
1499           continue;
1500         if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1501           AllocasToInstrument[AI].LifetimeStart.push_back(II);
1502         else
1503           AllocasToInstrument[AI].LifetimeEnd.push_back(II);
1504         continue;
1505       }
1506     }
1507 
1508     Instruction *ExitUntag = getUntagLocationIfFunctionExit(Inst);
1509     if (ExitUntag)
1510       RetVec.push_back(ExitUntag);
1511 
1512     if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst)) {
1513       for (Value *V : DVI->location_ops()) {
1514         if (auto *Alloca = dyn_cast_or_null<AllocaInst>(V))
1515           if (!AllocaDbgMap.count(Alloca) || AllocaDbgMap[Alloca].back() != DVI)
1516             AllocaDbgMap[Alloca].push_back(DVI);
1517       }
1518     }
1519 
1520     if (InstrumentLandingPads && isa<LandingPadInst>(Inst))
1521       LandingPadVec.push_back(&Inst);
1522 
1523     getInterestingMemoryOperands(&Inst, OperandsToInstrument);
1524 
1525     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&Inst))
1526       if (!ignoreMemIntrinsic(MI))
1527         IntrinToInstrument.push_back(MI);
1528   }
1529 
1530   initializeCallbacks(*F.getParent());
1531 
1532   bool Changed = false;
1533 
1534   if (!LandingPadVec.empty())
1535     Changed |= instrumentLandingPads(LandingPadVec);
1536 
1537   if (AllocasToInstrument.empty() && F.hasPersonalityFn() &&
1538       F.getPersonalityFn()->getName() == kHwasanPersonalityThunkName) {
1539     // __hwasan_personality_thunk is a no-op for functions without an
1540     // instrumented stack, so we can drop it.
1541     F.setPersonalityFn(nullptr);
1542     Changed = true;
1543   }
1544 
1545   if (AllocasToInstrument.empty() && OperandsToInstrument.empty() &&
1546       IntrinToInstrument.empty())
1547     return Changed;
1548 
1549   assert(!ShadowBase);
1550 
1551   Instruction *InsertPt = &*F.getEntryBlock().begin();
1552   IRBuilder<> EntryIRB(InsertPt);
1553   emitPrologue(EntryIRB,
1554                /*WithFrameRecord*/ ClRecordStackHistory &&
1555                    Mapping.WithFrameRecord && !AllocasToInstrument.empty());
1556 
1557   if (!AllocasToInstrument.empty()) {
1558     Value *StackTag =
1559         ClGenerateTagsWithCalls ? nullptr : getStackBaseTag(EntryIRB);
1560     // Calls to functions that may return twice (e.g. setjmp) confuse the
1561     // postdominator analysis, and will leave us to keep memory tagged after
1562     // function return. Work around this by always untagging at every return
1563     // statement if return_twice functions are called.
1564     instrumentStack(DetectUseAfterScope && !CallsReturnTwice,
1565                     AllocasToInstrument, UnrecognizedLifetimes, AllocaDbgMap,
1566                     RetVec, StackTag, GetDT, GetPDT);
1567   }
1568   // Pad and align each of the allocas that we instrumented to stop small
1569   // uninteresting allocas from hiding in instrumented alloca's padding and so
1570   // that we have enough space to store real tags for short granules.
1571   DenseMap<AllocaInst *, AllocaInst *> AllocaToPaddedAllocaMap =
1572       padInterestingAllocas(AllocasToInstrument);
1573 
1574   if (!AllocaToPaddedAllocaMap.empty()) {
1575     for (auto &Inst : instructions(F)) {
1576       if (auto *DVI = dyn_cast<DbgVariableIntrinsic>(&Inst)) {
1577         SmallDenseSet<Value *> LocationOps(DVI->location_ops().begin(),
1578                                            DVI->location_ops().end());
1579         for (Value *V : LocationOps) {
1580           if (auto *AI = dyn_cast_or_null<AllocaInst>(V)) {
1581             if (auto *NewAI = AllocaToPaddedAllocaMap.lookup(AI))
1582               DVI->replaceVariableLocationOp(V, NewAI);
1583           }
1584         }
1585       }
1586     }
1587     for (auto &P : AllocaToPaddedAllocaMap)
1588       P.first->eraseFromParent();
1589   }
1590 
1591   // If we split the entry block, move any allocas that were originally in the
1592   // entry block back into the entry block so that they aren't treated as
1593   // dynamic allocas.
1594   if (EntryIRB.GetInsertBlock() != &F.getEntryBlock()) {
1595     InsertPt = &*F.getEntryBlock().begin();
1596     for (Instruction &I :
1597          llvm::make_early_inc_range(*EntryIRB.GetInsertBlock())) {
1598       if (auto *AI = dyn_cast<AllocaInst>(&I))
1599         if (isa<ConstantInt>(AI->getArraySize()))
1600           I.moveBefore(InsertPt);
1601     }
1602   }
1603 
1604   for (auto &Operand : OperandsToInstrument)
1605     instrumentMemAccess(Operand);
1606 
1607   if (ClInstrumentMemIntrinsics && !IntrinToInstrument.empty()) {
1608     for (auto Inst : IntrinToInstrument)
1609       instrumentMemIntrinsic(cast<MemIntrinsic>(Inst));
1610   }
1611 
1612   ShadowBase = nullptr;
1613   StackBaseTag = nullptr;
1614 
1615   return true;
1616 }
1617 
1618 void HWAddressSanitizer::instrumentGlobal(GlobalVariable *GV, uint8_t Tag) {
1619   assert(!UsePageAliases);
1620   Constant *Initializer = GV->getInitializer();
1621   uint64_t SizeInBytes =
1622       M.getDataLayout().getTypeAllocSize(Initializer->getType());
1623   uint64_t NewSize = alignTo(SizeInBytes, Mapping.getObjectAlignment());
1624   if (SizeInBytes != NewSize) {
1625     // Pad the initializer out to the next multiple of 16 bytes and add the
1626     // required short granule tag.
1627     std::vector<uint8_t> Init(NewSize - SizeInBytes, 0);
1628     Init.back() = Tag;
1629     Constant *Padding = ConstantDataArray::get(*C, Init);
1630     Initializer = ConstantStruct::getAnon({Initializer, Padding});
1631   }
1632 
1633   auto *NewGV = new GlobalVariable(M, Initializer->getType(), GV->isConstant(),
1634                                    GlobalValue::ExternalLinkage, Initializer,
1635                                    GV->getName() + ".hwasan");
1636   NewGV->copyAttributesFrom(GV);
1637   NewGV->setLinkage(GlobalValue::PrivateLinkage);
1638   NewGV->copyMetadata(GV, 0);
1639   NewGV->setAlignment(
1640       MaybeAlign(std::max(GV->getAlignment(), Mapping.getObjectAlignment())));
1641 
1642   // It is invalid to ICF two globals that have different tags. In the case
1643   // where the size of the global is a multiple of the tag granularity the
1644   // contents of the globals may be the same but the tags (i.e. symbol values)
1645   // may be different, and the symbols are not considered during ICF. In the
1646   // case where the size is not a multiple of the granularity, the short granule
1647   // tags would discriminate two globals with different tags, but there would
1648   // otherwise be nothing stopping such a global from being incorrectly ICF'd
1649   // with an uninstrumented (i.e. tag 0) global that happened to have the short
1650   // granule tag in the last byte.
1651   NewGV->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
1652 
1653   // Descriptor format (assuming little-endian):
1654   // bytes 0-3: relative address of global
1655   // bytes 4-6: size of global (16MB ought to be enough for anyone, but in case
1656   // it isn't, we create multiple descriptors)
1657   // byte 7: tag
1658   auto *DescriptorTy = StructType::get(Int32Ty, Int32Ty);
1659   const uint64_t MaxDescriptorSize = 0xfffff0;
1660   for (uint64_t DescriptorPos = 0; DescriptorPos < SizeInBytes;
1661        DescriptorPos += MaxDescriptorSize) {
1662     auto *Descriptor =
1663         new GlobalVariable(M, DescriptorTy, true, GlobalValue::PrivateLinkage,
1664                            nullptr, GV->getName() + ".hwasan.descriptor");
1665     auto *GVRelPtr = ConstantExpr::getTrunc(
1666         ConstantExpr::getAdd(
1667             ConstantExpr::getSub(
1668                 ConstantExpr::getPtrToInt(NewGV, Int64Ty),
1669                 ConstantExpr::getPtrToInt(Descriptor, Int64Ty)),
1670             ConstantInt::get(Int64Ty, DescriptorPos)),
1671         Int32Ty);
1672     uint32_t Size = std::min(SizeInBytes - DescriptorPos, MaxDescriptorSize);
1673     auto *SizeAndTag = ConstantInt::get(Int32Ty, Size | (uint32_t(Tag) << 24));
1674     Descriptor->setComdat(NewGV->getComdat());
1675     Descriptor->setInitializer(ConstantStruct::getAnon({GVRelPtr, SizeAndTag}));
1676     Descriptor->setSection("hwasan_globals");
1677     Descriptor->setMetadata(LLVMContext::MD_associated,
1678                             MDNode::get(*C, ValueAsMetadata::get(NewGV)));
1679     appendToCompilerUsed(M, Descriptor);
1680   }
1681 
1682   Constant *Aliasee = ConstantExpr::getIntToPtr(
1683       ConstantExpr::getAdd(
1684           ConstantExpr::getPtrToInt(NewGV, Int64Ty),
1685           ConstantInt::get(Int64Ty, uint64_t(Tag) << PointerTagShift)),
1686       GV->getType());
1687   auto *Alias = GlobalAlias::create(GV->getValueType(), GV->getAddressSpace(),
1688                                     GV->getLinkage(), "", Aliasee, &M);
1689   Alias->setVisibility(GV->getVisibility());
1690   Alias->takeName(GV);
1691   GV->replaceAllUsesWith(Alias);
1692   GV->eraseFromParent();
1693 }
1694 
1695 static DenseSet<GlobalVariable *> getExcludedGlobals(Module &M) {
1696   NamedMDNode *Globals = M.getNamedMetadata("llvm.asan.globals");
1697   if (!Globals)
1698     return DenseSet<GlobalVariable *>();
1699   DenseSet<GlobalVariable *> Excluded(Globals->getNumOperands());
1700   for (auto MDN : Globals->operands()) {
1701     // Metadata node contains the global and the fields of "Entry".
1702     assert(MDN->getNumOperands() == 5);
1703     auto *V = mdconst::extract_or_null<Constant>(MDN->getOperand(0));
1704     // The optimizer may optimize away a global entirely.
1705     if (!V)
1706       continue;
1707     auto *StrippedV = V->stripPointerCasts();
1708     auto *GV = dyn_cast<GlobalVariable>(StrippedV);
1709     if (!GV)
1710       continue;
1711     ConstantInt *IsExcluded = mdconst::extract<ConstantInt>(MDN->getOperand(4));
1712     if (IsExcluded->isOne())
1713       Excluded.insert(GV);
1714   }
1715   return Excluded;
1716 }
1717 
1718 void HWAddressSanitizer::instrumentGlobals() {
1719   std::vector<GlobalVariable *> Globals;
1720   auto ExcludedGlobals = getExcludedGlobals(M);
1721   for (GlobalVariable &GV : M.globals()) {
1722     if (ExcludedGlobals.count(&GV))
1723       continue;
1724 
1725     if (GV.isDeclarationForLinker() || GV.getName().startswith("llvm.") ||
1726         GV.isThreadLocal())
1727       continue;
1728 
1729     // Common symbols can't have aliases point to them, so they can't be tagged.
1730     if (GV.hasCommonLinkage())
1731       continue;
1732 
1733     // Globals with custom sections may be used in __start_/__stop_ enumeration,
1734     // which would be broken both by adding tags and potentially by the extra
1735     // padding/alignment that we insert.
1736     if (GV.hasSection())
1737       continue;
1738 
1739     Globals.push_back(&GV);
1740   }
1741 
1742   MD5 Hasher;
1743   Hasher.update(M.getSourceFileName());
1744   MD5::MD5Result Hash;
1745   Hasher.final(Hash);
1746   uint8_t Tag = Hash[0];
1747 
1748   for (GlobalVariable *GV : Globals) {
1749     Tag &= TagMaskByte;
1750     // Skip tag 0 in order to avoid collisions with untagged memory.
1751     if (Tag == 0)
1752       Tag = 1;
1753     instrumentGlobal(GV, Tag++);
1754   }
1755 }
1756 
1757 void HWAddressSanitizer::instrumentPersonalityFunctions() {
1758   // We need to untag stack frames as we unwind past them. That is the job of
1759   // the personality function wrapper, which either wraps an existing
1760   // personality function or acts as a personality function on its own. Each
1761   // function that has a personality function or that can be unwound past has
1762   // its personality function changed to a thunk that calls the personality
1763   // function wrapper in the runtime.
1764   MapVector<Constant *, std::vector<Function *>> PersonalityFns;
1765   for (Function &F : M) {
1766     if (F.isDeclaration() || !F.hasFnAttribute(Attribute::SanitizeHWAddress))
1767       continue;
1768 
1769     if (F.hasPersonalityFn()) {
1770       PersonalityFns[F.getPersonalityFn()->stripPointerCasts()].push_back(&F);
1771     } else if (!F.hasFnAttribute(Attribute::NoUnwind)) {
1772       PersonalityFns[nullptr].push_back(&F);
1773     }
1774   }
1775 
1776   if (PersonalityFns.empty())
1777     return;
1778 
1779   FunctionCallee HwasanPersonalityWrapper = M.getOrInsertFunction(
1780       "__hwasan_personality_wrapper", Int32Ty, Int32Ty, Int32Ty, Int64Ty,
1781       Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy);
1782   FunctionCallee UnwindGetGR = M.getOrInsertFunction("_Unwind_GetGR", VoidTy);
1783   FunctionCallee UnwindGetCFA = M.getOrInsertFunction("_Unwind_GetCFA", VoidTy);
1784 
1785   for (auto &P : PersonalityFns) {
1786     std::string ThunkName = kHwasanPersonalityThunkName;
1787     if (P.first)
1788       ThunkName += ("." + P.first->getName()).str();
1789     FunctionType *ThunkFnTy = FunctionType::get(
1790         Int32Ty, {Int32Ty, Int32Ty, Int64Ty, Int8PtrTy, Int8PtrTy}, false);
1791     bool IsLocal = P.first && (!isa<GlobalValue>(P.first) ||
1792                                cast<GlobalValue>(P.first)->hasLocalLinkage());
1793     auto *ThunkFn = Function::Create(ThunkFnTy,
1794                                      IsLocal ? GlobalValue::InternalLinkage
1795                                              : GlobalValue::LinkOnceODRLinkage,
1796                                      ThunkName, &M);
1797     if (!IsLocal) {
1798       ThunkFn->setVisibility(GlobalValue::HiddenVisibility);
1799       ThunkFn->setComdat(M.getOrInsertComdat(ThunkName));
1800     }
1801 
1802     auto *BB = BasicBlock::Create(*C, "entry", ThunkFn);
1803     IRBuilder<> IRB(BB);
1804     CallInst *WrapperCall = IRB.CreateCall(
1805         HwasanPersonalityWrapper,
1806         {ThunkFn->getArg(0), ThunkFn->getArg(1), ThunkFn->getArg(2),
1807          ThunkFn->getArg(3), ThunkFn->getArg(4),
1808          P.first ? IRB.CreateBitCast(P.first, Int8PtrTy)
1809                  : Constant::getNullValue(Int8PtrTy),
1810          IRB.CreateBitCast(UnwindGetGR.getCallee(), Int8PtrTy),
1811          IRB.CreateBitCast(UnwindGetCFA.getCallee(), Int8PtrTy)});
1812     WrapperCall->setTailCall();
1813     IRB.CreateRet(WrapperCall);
1814 
1815     for (Function *F : P.second)
1816       F->setPersonalityFn(ThunkFn);
1817   }
1818 }
1819 
1820 void HWAddressSanitizer::ShadowMapping::init(Triple &TargetTriple,
1821                                              bool InstrumentWithCalls) {
1822   Scale = kDefaultShadowScale;
1823   if (TargetTriple.isOSFuchsia()) {
1824     // Fuchsia is always PIE, which means that the beginning of the address
1825     // space is always available.
1826     InGlobal = false;
1827     InTls = false;
1828     Offset = 0;
1829     WithFrameRecord = true;
1830   } else if (ClMappingOffset.getNumOccurrences() > 0) {
1831     InGlobal = false;
1832     InTls = false;
1833     Offset = ClMappingOffset;
1834     WithFrameRecord = false;
1835   } else if (ClEnableKhwasan || InstrumentWithCalls) {
1836     InGlobal = false;
1837     InTls = false;
1838     Offset = 0;
1839     WithFrameRecord = false;
1840   } else if (ClWithIfunc) {
1841     InGlobal = true;
1842     InTls = false;
1843     Offset = kDynamicShadowSentinel;
1844     WithFrameRecord = false;
1845   } else if (ClWithTls) {
1846     InGlobal = false;
1847     InTls = true;
1848     Offset = kDynamicShadowSentinel;
1849     WithFrameRecord = true;
1850   } else {
1851     InGlobal = false;
1852     InTls = false;
1853     Offset = kDynamicShadowSentinel;
1854     WithFrameRecord = false;
1855   }
1856 }
1857