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