Files
DroidDeck/tools/tests/test_fex_guest_high_memory.py
T

430 lines
20 KiB
Python

import platform
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
PATCH = REPO / "tools/fex/patches/0027-fixed-guest-memory-above-host-address-limit.patch"
PROBE = REPO / "tools/fex/probes/guest-high-memory.c"
SOURCE = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp"
HEADER = "Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h"
KERNEL_NAMES = {"pread_64": "pread64", "pwrite_64": "pwrite64", "prlimit_64": "prlimit64"}
NEWER_SYSCALLS = {"mseal": 462, "setxattrat": 463, "getxattrat": 464, "listxattrat": 465, "removexattrat": 466}
PRELUDE = r"""
#include <algorithm>
#include <array>
#include <asm/unistd_64.h>
#include <atomic>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <initializer_list>
#include <iterator>
#include <utility>
#include <vector>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
namespace fextl { template<typename T> using vector = std::vector<T>; }
namespace FEXCore {
namespace Utils { constexpr uint64_t FEX_PAGE_SIZE = 4096; }
constexpr uint64_t AlignUp(uint64_t V, uint64_t A) { return (V + A - 1) & ~(A - 1); }
namespace Allocator { inline uint64_t GetHostVABits() { return 39; } }
}
"""
STUBS = r"""
namespace FEX::HLE {
inline bool HasSyscallError(uint64_t Result) { return Result >= 0xFFFF'FFFF'FFFF'0001ULL; }
namespace FaultSafeUserMemAccess {
inline size_t CopyFromUser(void* Dest, const void* Src, size_t Size) { std::memcpy(Dest, Src, Size); return 0; }
inline size_t CopyToUser(void* Dest, const void* Src, size_t Size) { std::memcpy(Dest, Src, Size); return 0; }
}
namespace x64 {
ENUM
}
}
"""
MAIN = r"""
using namespace FEX::HLE::GuestHighMemory;
namespace Sys = FEX::HLE::x64;
static void Show(const char* Name, uint64_t Value) { std::printf("%s %llx\n", Name, static_cast<unsigned long long>(Value)); }
static uint64_t Call(uint32_t Syscall, uint64_t* Args, ArgumentStorage* Storage) { return TranslateSyscallArguments(Syscall, Args, 6, Storage); }
int main() {
const uint64_t Page = 4096;
const uint64_t High = TaskTop - Page;
const uint64_t Low = 0x140000000ULL;
Show("contains_last_page", Contains(High));
Show("contains_task_top", Contains(TaskTop));
Show("contains_host_limit", Contains(1ULL << 39));
Show("contains_below_limit", Contains((1ULL << 39) - Page));
Show("claims_without_atomics", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED));
SetHostAtomics(true);
Show("claims_fixed", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED));
Show("claims_noreplace", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE));
Show("claims_low", ClaimsMapping(Low, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED));
Show("claims_hint", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS));
Show("claims_task_top", ClaimsMapping(TaskTop, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED));
auto* Backing = static_cast<uint8_t*>(mmap(nullptr, 8 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Base = reinterpret_cast<uint64_t>(Backing);
const uint64_t Single = 0x7f0000000000ULL;
const uint64_t Split = 0x7e0000000000ULL;
const uint64_t Joined = 0x7d0000000000ULL;
AddEntry(Single, Page, Base, false);
AddEntry(Split, Page, Base + 2 * Page, false);
AddEntry(Split + Page, Page, Base + 4 * Page, false);
AddEntry(Joined, Page, Base + 5 * Page, false);
AddEntry(Joined + Page, Page, Base + 6 * Page, false);
ArgumentStorage Storage;
uint64_t Read[6] = {3, Single + 16, 32, 0, 0, 0};
Show("read_result", Call(Sys::SYSCALL_x64_read, Read, &Storage));
Show("read_buffer", Read[1] - Base);
uint64_t Truncate[6] = {3, Single + 16, 0, 0, 0, 0};
Show("ftruncate_result", Call(Sys::SYSCALL_x64_ftruncate, Truncate, &Storage));
Show("ftruncate_length", Truncate[1] - Single);
uint64_t Mapping[6] = {Single, Page, 0, 0, 0, 0};
Show("mmap_result", Call(Sys::SYSCALL_x64_mmap, Mapping, &Storage));
Show("mmap_address", Mapping[0] - Single);
uint64_t Unknown[6] = {Single, Single, Single, Single, Single, Single};
Show("unknown_result", Call(1000, Unknown, &Storage));
Show("unknown_args", Unknown[0] - Single + Unknown[5] - Single);
uint64_t Overrun[6] = {3, Single + Page - 8, 64, 0, 0, 0};
Show("overrun_result", Call(Sys::SYSCALL_x64_read, Overrun, &Storage));
uint64_t Apart[6] = {3, Split + Page - 96, 200, 0, 0, 0};
Show("split_result", Call(Sys::SYSCALL_x64_read, Apart, &Storage));
uint64_t Together[6] = {3, Joined + Page - 96, 200, 0, 0, 0};
Show("joined_result", Call(Sys::SYSCALL_x64_read, Together, &Storage));
Show("joined_buffer", Together[1] - Base);
uint64_t Write[6] = {3, Split + Page - 96, 96, 0, 0, 0};
Show("fits_result", Call(Sys::SYSCALL_x64_write, Write, &Storage));
Show("fits_buffer", Write[1] - Base);
char LowBuffer[16];
struct iovec Guest[2] = {{reinterpret_cast<void*>(Single + 64), 32}, {LowBuffer, sizeof(LowBuffer)}};
uint64_t Vector[6] = {3, reinterpret_cast<uint64_t>(Guest), 2, 0, 0, 0};
Show("readv_result", Call(Sys::SYSCALL_x64_readv, Vector, &Storage));
const auto* HostVector = reinterpret_cast<const struct iovec*>(Vector[1]);
Show("readv_copied", HostVector != Guest);
Show("readv_high_base", reinterpret_cast<uint64_t>(HostVector[0].iov_base) - Base);
Show("readv_low_base", HostVector[1].iov_base == LowBuffer);
Show("readv_guest_untouched", reinterpret_cast<uint64_t>(Guest[0].iov_base) - Single);
struct iovec LowOnly[1] = {{LowBuffer, sizeof(LowBuffer)}};
uint64_t Plain[6] = {3, reinterpret_cast<uint64_t>(LowOnly), 1, 0, 0, 0};
Show("writev_result", Call(Sys::SYSCALL_x64_writev, Plain, &Storage));
Show("writev_untouched", Plain[1] == reinterpret_cast<uint64_t>(LowOnly));
struct iovec Straddle[1] = {{reinterpret_cast<void*>(Split + Page - 8), 16}};
uint64_t Crossing[6] = {3, reinterpret_cast<uint64_t>(Straddle), 1, 0, 0, 0};
Show("writev_split_result", Call(Sys::SYSCALL_x64_writev, Crossing, &Storage));
ArgumentStorage Receive;
struct iovec Incoming[1] = {{reinterpret_cast<void*>(Single + 128), 64}};
struct msghdr Header {};
Header.msg_iov = Incoming;
Header.msg_iovlen = 1;
uint64_t Message[6] = {3, reinterpret_cast<uint64_t>(&Header), 0, 0, 0, 0};
Show("recvmsg_result", Call(Sys::SYSCALL_x64_recvmsg, Message, &Receive));
const auto* HostHeader = reinterpret_cast<struct msghdr*>(Message[1]);
Show("recvmsg_copied", HostHeader != &Header);
Show("recvmsg_base", reinterpret_cast<uint64_t>(HostHeader->msg_iov[0].iov_base) - Base);
Receive.Message.msg_flags = MSG_TRUNC;
FinishSyscallArguments(64, &Receive);
Show("recvmsg_flags", Header.msg_flags);
Show("recvmsg_guest_iov", Header.msg_iov == Incoming);
Show("to_guest", ToGuest(Base + 6 * Page + 8) - Joined);
Show("to_guest_low", ToGuest(Low) == Low);
const uint32_t ExclusiveOps[] = {0xc85f7c20, 0x885ffc20, 0x085ffc20, 0x485f7c20, 0xc8027c20, 0xc802fc20,
0x0802fc20, 0xc87f0820, 0x887f8820, 0xc8230820, 0xc8238820};
const uint32_t OtherOps[] = {0xc8dffc20, 0xc89ffc20, 0xc8e0fc41, 0x4860fc82, 0x08207c82, 0xf8e00041,
0xf8e08041, 0xf9400020, 0xf9000420, 0xa9000440, 0xf8bfc020};
uint64_t Refused = 0;
for (auto Op : ExclusiveOps) {
Refused += IsExclusive(Op);
}
uint64_t Allowed = 0;
for (auto Op : OtherOps) {
Allowed += !IsExclusive(Op);
}
Show("exclusive_refused", Refused);
Show("others_allowed", Allowed);
std::vector<std::pair<uint64_t, uint64_t>> Applied;
auto Record = [&](void* Host, uint64_t Size) {
Applied.emplace_back(reinterpret_cast<uint64_t>(Host), Size);
return 0;
};
Show("split_apply_result", ApplyToRegionsLocked(Split, 2 * Page, -EINVAL, Record));
Show("split_apply_count", Applied.size());
Show("split_apply_first", Applied[0].first - Base);
Show("split_apply_second", Applied[1].first - Base);
Show("split_apply_sizes", Applied[0].second + Applied[1].second);
Applied.clear();
Show("gap_apply_result", ApplyToRegionsLocked(Single, 2 * Page, -EINVAL, Record));
Show("gap_apply_count", Applied.size());
bool Advised = false;
Show("advise_split", Advise(Split, 2 * Page, MADV_DONTNEED, &Advised));
Show("advise_split_applied", Advised);
Show("advise_gap", Advise(Single, 2 * Page, MADV_DONTNEED, &Advised));
Show("advise_gap_applied", Advised);
Show("advise_unaligned", Advise(Single + 8, Page, MADV_DONTNEED, &Advised));
Show("advise_unaligned_applied", Advised);
Show("advise_zero", Advise(Single, 0, MADV_DONTNEED, &Advised));
Show("advise_wrap", Advise(Single, UINT64_MAX - 16, MADV_DONTNEED, &Advised));
Show("advise_wrap_applied", Advised);
Show("protect_split", Protect(Split, 2 * Page, PROT_READ | PROT_WRITE));
Show("protect_zero", Protect(Single, 0, PROT_READ | PROT_WRITE));
Show("protect_wrap", Protect(Single, UINT64_MAX - 16, PROT_READ | PROT_WRITE));
Show("discards", DiscardsContents(MADV_DONTNEED) + DiscardsContents(MADV_FREE) + DiscardsContents(MADV_REMOVE) +
DiscardsContents(MADV_DONTNEED_LOCKED));
Show("keeps", DiscardsContents(MADV_WILLNEED) + DiscardsContents(MADV_NORMAL) + DiscardsContents(MADV_HUGEPAGE));
SetHostAtomics(false);
Show("claims_after_disable", ClaimsMapping(High, Page, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED));
return 0;
}
"""
def added_lines(text, path):
lines = []
inside = False
for line in text.splitlines():
if line.startswith("diff --git "):
inside = line.endswith(" b/" + path)
continue
if inside and line.startswith("+") and not line.startswith("+++"):
lines.append(line[1:])
return lines
def block(lines, signature):
start = next(i for i, line in enumerate(lines) if line.lstrip().startswith(signature))
indent = lines[start][: len(lines[start]) - len(lines[start].lstrip())]
if lines[start].rstrip().endswith(";"):
return lines[start]
end = next(i for i in range(start + 1, len(lines)) if lines[i] in (indent + "}", indent + "};"))
return "\n".join(lines[start:end + 1])
def span(lines, first, stop):
start = next(i for i, line in enumerate(lines) if line.startswith(first))
end = next(i for i in range(start + 1, len(lines)) if lines[i].startswith(stop))
return "\n".join(lines[start:end])
def syscall_enum(code):
entries = []
for name in sorted(set(re.findall(r"SYSCALL_x64_(\w+)", code))):
kernel = KERNEL_NAMES.get(name, name)
fallback = NEWER_SYSCALLS.get(name)
if fallback is None:
entries.append(f"SYSCALL_x64_{name} = __NR_{kernel},")
else:
entries.append(f"#ifdef __NR_{kernel}\nSYSCALL_x64_{name} = __NR_{kernel},\n#else\nSYSCALL_x64_{name} = {fallback},\n#endif")
return "enum Syscalls_x64 : int {\n" + "\n".join(entries) + "\n};"
def harness():
text = PATCH.read_text()
source = added_lines(text, SOURCE)
header = [line for line in added_lines(text, HEADER) if not line.startswith(("#pragma", "#include <FEXCore"))]
hidden = "\n".join([
span(source, " constexpr uint64_t TaskTop", " void BeginWrite()"),
block(source, "void SetEntry("),
block(source, "bool AddEntry("),
span(source, " bool FindLocked(", " uint64_t NeighbourHint("),
block(source, "constexpr bool IsExclusive("),
span(source, " constexpr uint64_t MaxIoVectors", "} // namespace"),
])
public = "\n".join(block(source, signature) for signature in (
"void SetHostAtomics(",
"bool Contains(",
"bool ClaimsMapping(",
"uint64_t Protect(",
"uint64_t Advise(",
"bool DiscardsContents(",
"uint64_t ToGuest(",
"bool TranslateRange(",
"uint64_t TranslateSyscallArguments(",
"void FinishSyscallArguments(",
))
body = "namespace FEX::HLE::GuestHighMemory {\nnamespace {\n" + hidden + "\n}\n" + public + "\n}\n"
stubs = STUBS.replace("ENUM", syscall_enum(hidden + MAIN))
return PRELUDE + "\n".join(header) + stubs + body + MAIN
class GuestHighMemoryTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.results = None
compiler = shutil.which("c++") or shutil.which("g++") or shutil.which("clang++")
if not compiler or platform.machine() not in ("x86_64", "AMD64"):
return
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "high.cpp"
binary = Path(tmp) / "high"
source.write_text(harness())
subprocess.run([compiler, "-std=c++20", "-o", str(binary), str(source)], check=True)
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True).stdout
cls.results = dict(line.split() for line in output.splitlines())
def value(self, name):
if self.results is None:
self.skipTest("needs a C++ compiler and x86-64 syscall headers")
return int(self.results[name], 16)
def efault(self):
return (1 << 64) - 14
def test_contains_uses_the_production_task_top(self):
self.assertEqual(self.value("contains_last_page"), 1)
self.assertEqual(self.value("contains_task_top"), 0)
self.assertEqual(self.value("contains_host_limit"), 1)
self.assertEqual(self.value("contains_below_limit"), 0)
def test_only_fixed_mappings_above_the_host_limit_are_relocated(self):
self.assertEqual(self.value("claims_without_atomics"), 0)
self.assertEqual(self.value("claims_after_disable"), 0)
self.assertEqual(
[self.value(name) for name in ("claims_fixed", "claims_noreplace", "claims_low", "claims_hint", "claims_task_top")],
[1, 0, 0, 0, 0],
)
def test_only_pointer_arguments_are_translated(self):
self.assertEqual(self.value("read_result"), 0)
self.assertEqual(self.value("read_buffer"), 16)
self.assertEqual(self.value("ftruncate_result"), 0)
self.assertEqual(self.value("ftruncate_length"), 16)
self.assertEqual(self.value("mmap_result"), 0)
self.assertEqual(self.value("mmap_address"), 0)
self.assertEqual(self.value("unknown_result"), 0)
self.assertEqual(self.value("unknown_args"), 0)
def test_sized_buffers_must_map_to_one_host_range(self):
self.assertEqual(self.value("overrun_result"), self.efault())
self.assertEqual(self.value("split_result"), self.efault())
self.assertEqual(self.value("joined_result"), 0)
self.assertEqual(self.value("joined_buffer"), 6 * 4096 - 96)
self.assertEqual(self.value("fits_result"), 0)
self.assertEqual(self.value("fits_buffer"), 3 * 4096 - 96)
def test_io_vectors_get_a_translated_host_copy(self):
self.assertEqual(self.value("readv_result"), 0)
self.assertEqual(self.value("readv_copied"), 1)
self.assertEqual(self.value("readv_high_base"), 64)
self.assertEqual(self.value("readv_low_base"), 1)
self.assertEqual(self.value("readv_guest_untouched"), 64)
self.assertEqual(self.value("writev_result"), 0)
self.assertEqual(self.value("writev_untouched"), 1)
self.assertEqual(self.value("writev_split_result"), self.efault())
def test_received_message_fields_return_to_the_guest_header(self):
self.assertEqual(self.value("recvmsg_result"), 0)
self.assertEqual(self.value("recvmsg_copied"), 1)
self.assertEqual(self.value("recvmsg_base"), 128)
self.assertEqual(self.value("recvmsg_flags"), 0x20)
self.assertEqual(self.value("recvmsg_guest_iov"), 1)
def test_kernel_writes_invalidate_by_guest_address(self):
self.assertEqual(self.value("to_guest"), 4096 + 8)
self.assertEqual(self.value("to_guest_low"), 1)
text = PATCH.read_text()
self.assertRegex(text, r"\n\+ Buf = reinterpret_cast<const void\*>\(FEX::HLE::GuestHighMemory::ToGuest\(")
def test_hosts_without_atomics_keep_the_old_mapping_path(self):
text = PATCH.read_text()
self.assertRegex(text, r"\n\+ FEX::HLE::GuestHighMemory::SetHostAtomics\(HostFeatures\.SupportsAtomics\);")
self.assertRegex(text, r"\n\+ if \(!HostAtomics \|\| !\(Flags & MAP_FIXED\)")
def test_exclusive_accesses_are_never_single_stepped(self):
self.assertEqual(self.value("exclusive_refused"), 11)
self.assertEqual(self.value("others_allowed"), 11)
text = PATCH.read_text()
self.assertRegex(text, r"\n\+ if \(!IsLoadStore\(Insn\) \|\| IsLiteralLoad\(Insn\) \|\| IsExclusive\(Insn\)")
def test_high_code_writes_invalidate_every_alias(self):
text = PATCH.read_text()
self.assertRegex(text, r"\n\+ FEX::HLE::SyscallHandler::InvalidateWrittenCodePage\(Thread, FaultBase, Entry->first, Entry->second\);")
def test_madvise_applies_to_each_overlapping_region(self):
self.assertEqual(self.value("split_apply_result"), 0)
self.assertEqual(self.value("split_apply_count"), 2)
self.assertEqual(self.value("split_apply_first"), 2 * 4096)
self.assertEqual(self.value("split_apply_second"), 4 * 4096)
self.assertEqual(self.value("split_apply_sizes"), 2 * 4096)
self.assertEqual(self.value("gap_apply_result"), (1 << 64) - 12)
self.assertEqual(self.value("gap_apply_count"), 1)
self.assertEqual(self.value("advise_split"), 0)
self.assertEqual(self.value("advise_split_applied"), 1)
self.assertEqual(self.value("advise_gap"), (1 << 64) - 12)
self.assertEqual(self.value("advise_gap_applied"), 1)
self.assertEqual(self.value("advise_unaligned"), (1 << 64) - 22)
self.assertEqual(self.value("advise_unaligned_applied"), 0)
self.assertEqual(self.value("protect_split"), 0)
def test_wrapping_lengths_fail_like_linux(self):
self.assertEqual(self.value("advise_zero"), 0)
self.assertEqual(self.value("advise_wrap"), (1 << 64) - 22)
self.assertEqual(self.value("advise_wrap_applied"), 0)
self.assertEqual(self.value("protect_zero"), 0)
self.assertEqual(self.value("protect_wrap"), (1 << 64) - 12)
def test_discarding_advice_invalidates_high_code(self):
self.assertEqual(self.value("discards"), 4)
self.assertEqual(self.value("keeps"), 0)
text = PATCH.read_text()
self.assertRegex(text, r"\n\+ if \(Applied && FEX::HLE::GuestHighMemory::DiscardsContents\(advice\)\) \{")
def test_no_replace_probes_reach_the_host(self):
text = PATCH.read_text()
self.assertIsNone(re.search(r"^\+.*Flags & \(MAP_FIXED \| MAP_FIXED_NOREPLACE\)", text, re.M))
self.assertNotIn("OverlapsLocked", text)
@unittest.skipUnless(platform.machine() == "x86_64", "the probe is x86-64 code")
class GuestHighMemoryProbeTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which("cc") or shutil.which("gcc") or shutil.which("clang")
if not compiler:
raise unittest.SkipTest("no C compiler")
cls.tmp = Path(tempfile.mkdtemp(prefix="fex-guest-high-memory-"))
cls.binary = cls.tmp / "probe"
subprocess.run([compiler, "-O2", "-pthread", "-o", str(cls.binary), str(PROBE)], check=True, capture_output=True, text=True)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmp, ignore_errors=True)
def test_native_kernel_passes_every_check(self):
result = subprocess.run([str(self.binary)], capture_output=True, text=True, timeout=120)
self.assertEqual(result.returncode, 0, result.stdout)
self.assertNotIn("FAIL", result.stdout)
self.assertEqual(result.stdout.splitlines()[-1], "RESULT PASS")
if __name__ == "__main__":
unittest.main()