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