VirtualRange.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Leon Albrecht <leon2002.la@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <Kernel/API/KResult.h>
  9. #include <Kernel/VirtualAddress.h>
  10. namespace Kernel::Memory {
  11. class VirtualRange {
  12. friend class VirtualRangeAllocator;
  13. public:
  14. VirtualRange() = delete;
  15. VirtualRange(VirtualAddress base, size_t size)
  16. : m_base(base)
  17. , m_size(size)
  18. {
  19. }
  20. VirtualAddress base() const { return m_base; }
  21. size_t size() const { return m_size; }
  22. bool is_valid() const { return !m_base.is_null(); }
  23. bool contains(VirtualAddress vaddr) const { return vaddr >= base() && vaddr < end(); }
  24. VirtualAddress end() const { return m_base.offset(m_size); }
  25. bool operator==(VirtualRange const& other) const
  26. {
  27. return m_base == other.m_base && m_size == other.m_size;
  28. }
  29. bool contains(VirtualAddress base, size_t size) const
  30. {
  31. if (base.offset(size) < base)
  32. return false;
  33. return base >= m_base && base.offset(size) <= end();
  34. }
  35. bool contains(VirtualRange const& other) const
  36. {
  37. return contains(other.base(), other.size());
  38. }
  39. Vector<VirtualRange, 2> carve(VirtualRange const&) const;
  40. VirtualRange intersect(VirtualRange const&) const;
  41. static KResultOr<VirtualRange> expand_to_page_boundaries(FlatPtr address, size_t size);
  42. private:
  43. VirtualAddress m_base;
  44. size_t m_size { 0 };
  45. };
  46. }
  47. template<>
  48. struct AK::Formatter<Kernel::Memory::VirtualRange> : Formatter<FormatString> {
  49. void format(FormatBuilder& builder, Kernel::Memory::VirtualRange value)
  50. {
  51. return Formatter<FormatString>::format(builder, "{} - {} (size {:p})", value.base().as_ptr(), value.base().offset(value.size() - 1).as_ptr(), value.size());
  52. }
  53. };