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