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