VirtualAddress.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/Types.h>
  9. class VirtualAddress {
  10. public:
  11. VirtualAddress() = default;
  12. constexpr explicit VirtualAddress(FlatPtr address)
  13. : m_address(address)
  14. {
  15. }
  16. explicit VirtualAddress(const void* address)
  17. : m_address((FlatPtr)address)
  18. {
  19. }
  20. [[nodiscard]] constexpr bool is_null() const { return m_address == 0; }
  21. [[nodiscard]] constexpr bool is_page_aligned() const { return (m_address & 0xfff) == 0; }
  22. [[nodiscard]] constexpr VirtualAddress offset(FlatPtr o) const { return VirtualAddress(m_address + o); }
  23. [[nodiscard]] constexpr FlatPtr get() const { return m_address; }
  24. void set(FlatPtr address) { m_address = address; }
  25. void mask(FlatPtr m) { m_address &= m; }
  26. bool operator<=(const VirtualAddress& other) const { return m_address <= other.m_address; }
  27. bool operator>=(const VirtualAddress& other) const { return m_address >= other.m_address; }
  28. bool operator>(const VirtualAddress& other) const { return m_address > other.m_address; }
  29. bool operator<(const VirtualAddress& other) const { return m_address < other.m_address; }
  30. bool operator==(const VirtualAddress& other) const { return m_address == other.m_address; }
  31. bool operator!=(const VirtualAddress& other) const { return m_address != other.m_address; }
  32. [[nodiscard]] u8* as_ptr() { return reinterpret_cast<u8*>(m_address); }
  33. [[nodiscard]] const u8* as_ptr() const { return reinterpret_cast<const u8*>(m_address); }
  34. [[nodiscard]] VirtualAddress page_base() const { return VirtualAddress(m_address & ~(FlatPtr)0xfffu); }
  35. private:
  36. FlatPtr m_address { 0 };
  37. };
  38. inline VirtualAddress operator-(const VirtualAddress& a, const VirtualAddress& b)
  39. {
  40. return VirtualAddress(a.get() - b.get());
  41. }
  42. template<>
  43. struct AK::Formatter<VirtualAddress> : AK::Formatter<FormatString> {
  44. void format(FormatBuilder& builder, const VirtualAddress& value)
  45. {
  46. return AK::Formatter<FormatString>::format(builder, "V{}", value.as_ptr());
  47. }
  48. };