Path: blob/main/contrib/llvm-project/compiler-rt/lib/hwasan/hwasan_globals.cpp
35235 views
//===-- hwasan_globals.cpp ------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file is a part of HWAddressSanitizer.9//10// HWAddressSanitizer globals-specific runtime.11//===----------------------------------------------------------------------===//1213#include "hwasan_globals.h"1415#include "sanitizer_common/sanitizer_array_ref.h"1617namespace __hwasan {1819enum { NT_LLVM_HWASAN_GLOBALS = 3 };20struct hwasan_global_note {21s32 begin_relptr;22s32 end_relptr;23};2425// Check that the given library meets the code model requirements for tagged26// globals. These properties are not checked at link time so they need to be27// checked at runtime.28static void CheckCodeModel(ElfW(Addr) base, const ElfW(Phdr) * phdr,29ElfW(Half) phnum) {30ElfW(Addr) min_addr = -1ull, max_addr = 0;31for (unsigned i = 0; i != phnum; ++i) {32if (phdr[i].p_type != PT_LOAD)33continue;34ElfW(Addr) lo = base + phdr[i].p_vaddr, hi = lo + phdr[i].p_memsz;35if (min_addr > lo)36min_addr = lo;37if (max_addr < hi)38max_addr = hi;39}4041if (max_addr - min_addr > 1ull << 32) {42Report("FATAL: HWAddressSanitizer: library size exceeds 2^32\n");43Die();44}45if (max_addr > 1ull << 48) {46Report("FATAL: HWAddressSanitizer: library loaded above address 2^48\n");47Die();48}49}5051ArrayRef<const hwasan_global> HwasanGlobalsFor(ElfW(Addr) base,52const ElfW(Phdr) * phdr,53ElfW(Half) phnum) {54// Read the phdrs from this DSO.55for (unsigned i = 0; i != phnum; ++i) {56if (phdr[i].p_type != PT_NOTE)57continue;5859const char *note = reinterpret_cast<const char *>(base + phdr[i].p_vaddr);60const char *nend = note + phdr[i].p_memsz;6162// Traverse all the notes until we find a HWASan note.63while (note < nend) {64auto *nhdr = reinterpret_cast<const ElfW(Nhdr) *>(note);65const char *name = note + sizeof(ElfW(Nhdr));66const char *desc = name + RoundUpTo(nhdr->n_namesz, 4);6768// Discard non-HWASan-Globals notes.69if (nhdr->n_type != NT_LLVM_HWASAN_GLOBALS ||70internal_strcmp(name, "LLVM") != 0) {71note = desc + RoundUpTo(nhdr->n_descsz, 4);72continue;73}7475// Only libraries with instrumented globals need to be checked against the76// code model since they use relocations that aren't checked at link time.77CheckCodeModel(base, phdr, phnum);7879auto *global_note = reinterpret_cast<const hwasan_global_note *>(desc);80auto *globals_begin = reinterpret_cast<const hwasan_global *>(81note + global_note->begin_relptr);82auto *globals_end = reinterpret_cast<const hwasan_global *>(83note + global_note->end_relptr);8485return {globals_begin, globals_end};86}87}8889return {};90}9192} // namespace __hwasan939495