107 lines
2.6 KiB
C++
107 lines
2.6 KiB
C++
|
|
#pragma once
|
|
|
|
#if !defined(BAD_APPLE_OS_OS_MEMORY_HPP_INCLUDED)
|
|
#define BAD_APPLE_OS_OS_MEMORY_HPP_INCLUDED
|
|
|
|
#include <bit>
|
|
#include <cstdint>
|
|
#include <span>
|
|
|
|
extern "C" int gKernelStart;
|
|
extern "C" int gKernelEnd;
|
|
|
|
namespace baos
|
|
{
|
|
struct PageTableEntry
|
|
{
|
|
bool present : 1;
|
|
bool writable : 1;
|
|
bool user : 1;
|
|
bool writeThrough : 1;
|
|
bool cacheDisabled : 1;
|
|
bool accessed : 1;
|
|
bool dirty : 1;
|
|
bool pageSize : 1;
|
|
bool global : 1;
|
|
std::uint8_t avl : 3;
|
|
std::uint64_t address : 40;
|
|
std::uint16_t avl2 : 11;
|
|
bool executeDisable : 1;
|
|
};
|
|
|
|
enum class MemoryType
|
|
{
|
|
USABLE,
|
|
UNUSABLE,
|
|
MMIO,
|
|
RESERVED
|
|
};
|
|
|
|
struct MemoryRange
|
|
{
|
|
std::uint64_t pageBase = 0;
|
|
std::uint64_t numPages = 0;
|
|
MemoryType type = MemoryType::USABLE;
|
|
|
|
MemoryRange& operator=(const MemoryRange&) noexcept = default;
|
|
bool operator<(const MemoryRange& other) const noexcept
|
|
{
|
|
return pageBase < other.pageBase;
|
|
}
|
|
};
|
|
|
|
struct AllocatePagesOptions
|
|
{
|
|
std::size_t numPages = 1;
|
|
bool bigPages = false;
|
|
};
|
|
|
|
struct PageRange
|
|
{
|
|
std::uint64_t mBase = 0;
|
|
std::uint64_t numPages = 0;
|
|
|
|
explicit operator bool() const noexcept { return numPages > 0; }
|
|
bool operator!() const noexcept { return numPages == 0; }
|
|
|
|
[[nodiscard]] std::span<std::uint8_t> getMemory() const noexcept
|
|
{
|
|
std::uint8_t* basePtr = std::bit_cast<std::uint8_t*>(mBase << 12);
|
|
return {basePtr, basePtr + (numPages * 512)};
|
|
}
|
|
};
|
|
|
|
[[nodiscard]] bool setupPaging(std::span<const MemoryRange> memoryRanges) noexcept;
|
|
[[nodiscard]] const char* memoryTypeName(MemoryType type) noexcept;
|
|
|
|
[[nodiscard]] PageRange allocatePages(const AllocatePagesOptions& options = {}) noexcept;
|
|
|
|
void setupIdentityPaging(std::uint64_t page) noexcept;
|
|
void setupIdentityPaging2M(std::uint64_t page) noexcept;
|
|
void setupIdentityPaging(std::uint64_t firstPage, std::uint64_t lastPage) noexcept;
|
|
|
|
inline void identityMapRegion(void* start, std::size_t bytes) noexcept
|
|
{
|
|
std::uint64_t firstPage = std::bit_cast<std::uint64_t>(start) / 4096;
|
|
std::uint64_t lastPage = std::bit_cast<std::uint64_t>(static_cast<std::uint8_t*>(start) + bytes) / 4096 + 1;
|
|
setupIdentityPaging(firstPage, lastPage);
|
|
}
|
|
|
|
template<typename T = void>
|
|
[[nodiscard]] inline T* pageToPointer(std::uint64_t page) noexcept
|
|
{
|
|
return std::bit_cast<T*>(page << 12);
|
|
}
|
|
|
|
[[nodiscard]] inline std::size_t bytesToPages(std::size_t bytes, bool bigPages = false) noexcept
|
|
{
|
|
const std::size_t pageBytes = bigPages ? (2 << 20) : 4096;
|
|
return (bytes + pageBytes - 1) / pageBytes;
|
|
}
|
|
}
|
|
|
|
void __ba_initInitialHeap() noexcept;
|
|
|
|
#endif // !defined(BAD_APPLE_OS_OS_MEMORY_HPP_INCLUDED)
|