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