Files
DroidDeck/tools/tests/test_fex_guest_high_memory.py
T
2d25fb91c5 Run Easy Anti-Cheat and BattlEye games on x86-64 DroidDeck-Proton under FEX (#3641)
* FEX: emulate x86-64 ptrace, seccomp and /proc for anti-cheat launchers

* Guest hook: route raw execve/execveat through the exec wrapper and pass self-sent SIGSYS to the program

A program that execs with syscall(SYS_execveat, ...) bypassed the environment the
guest needs, so re-executing /proc/self/exe died in the loader. /proc/self/exe now
maps to the real program on exec as it already does on open.

A SIGSYS the program queues itself, or one from a filter for another architecture,
went to the Android-filter emulation instead of the program's handler.

* FEX: list only guest mappings in /proc/<pid>/maps on hosts below 47 address bits

Credit the anti-cheat emulation source in the patch header.

* Preloads: leave poll, ppoll and select buffers untouched when no emulated device is open

A bad user pointer now reaches the kernel and returns EFAULT instead of crashing the caller inside the wrapper.

* Emulate only host-architecture seccomp traps in the guest hook; report the calling thread's seccomp mode in FEX's /proc/self/status

A SIGSYS carrying another architecture's seccomp siginfo now takes its default action when the program has no handler, so a process whose emulated filter traps a syscall while SIGSYS is blocked or ignored dies as on Linux.

* FEX: read the host status file through the raw openat syscall

* README: credit StonkGuy's FEX anti-cheat emulation

* FEX: open the host status file with a direct system call so preloads cannot rewrite it

* FEX: hand a traced program's ptrace state across exec

* Credit StonkGuy in the FEX anti-cheat patches and README

Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>

* FEX: open guest paths with the raw openat system call so host preloads cannot replace the file

* FEX: serve emulated proc files by the requested path when the host returns a memfd

* FEX: map fixed guest memory above a small host address space

Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>

* FEX: serve decoder reads from fixed guest memory above the host limit

* Run games with anti-cheat files on an x86-64 DroidDeck-Proton under FEX

The Proton launchers look for Easy Anti-Cheat or BattlEye bridge files in
the game folder and, when an x86-64 DroidDeck-Proton and the matching Proton
runtime are installed, hand the launch to that Proton under FEX with the
game's own prefix. Picking the x86-64 tool directly also runs it under FEX.
DROIDDECK_ANTICHEAT=off keeps a game on ARM64.

* Keep x86-64 DroidDeck-Proton builds out of the ARM64 tool list

* droiddeck-fex: take the runtime from an adopted tool's original manifest

* FEX: show the guest command line when the argument area cannot be remapped

* FEX: describe the container's procfs in emulated mount tables

* FEX: order the anti-cheat series after the guest stack patch from main

* Test the container procfs view of FEX's emulated mount tables

* Docs: describe the anti-cheat signal mask fix and the container procfs view

* README: match the StonkGuy credit to the renumbered FEX patches

* Keep anti-cheat games on a tool the user chose instead of moving them to x86-64

* test(game-env): build the adopted-tool wrapper through extra_wrapper_sh

* Check anti-cheat runtime bridges, apply component choices under FEX and honour MAP_FIXED_NOREPLACE above the host limit

* Check the driver query is answered before each wrapper's call sites

* Keep x86-64 Proton builds out of the automatic default tool

* Keep high guest mappings intact when a fixed map or unmap fails

Check room in the region table, splits included, before a fixed map or
unmap removes anything, return the host munmap error without touching
the table entry, and keep write-protecting low shared aliases of
executable ranges that sit above the host address limit.

* Keep a requested x86-64 default and accept linked anti-cheat runtimes

A request for the current automatic x86-64 default now marks it as the
app's choice, so the next settle no longer moves it back to ARM64.
Anti-cheat runtime discovery follows a symlinked runtime directory.

* Route anti-cheat games to x86-64 Proton only on a capable FEX

The FEX build now lists its patches in share/fex-emu/.droiddeck-patches.
Anti-cheat routing needs the fixed guest memory patch in that list and
otherwise keeps the launch on ARM64, as an older FEX cannot map the
anti-cheat helper buffer above the host address limit. Installing a FEX
build without the list removes a list left by an earlier build.

* Update FEX before deciding anti-cheat routing

A device on an older FEX build never went through droiddeck-fex on the
ARM64 path, so the catalog FEX was never installed and the gate kept
anti-cheat games on ARM64 forever. dd_anticheat now runs the new
droiddeck-fex update action first, which installs the catalog build
under the same lock and retry window as other FEX launches.

* Leave MAP_FIXED_NOREPLACE above the host limit to the host

Wine finds the top of the address space with MAP_FIXED_NOREPLACE probes.
Claiming those probes above a 39-bit host limit made Wine place its stacks
in relocated memory, and every wineserver request then failed with EFAULT
because the iovec buffers it passes to writev are nested pointers that are
not translated. Only MAP_FIXED requests are relocated again, so the probes
see the real host limit while fixed mappings above it keep working.

* Translate only pointer syscall arguments into high guest memory

Pointer arguments are now picked from a per-syscall layout table, so
scalar values such as a truncate length are never rewritten. Sized
buffers must map to one contiguous host range or the call fails with
EFAULT, and new host backings are placed next to their guest
neighbours so adjacent mappings stay contiguous. readv, writev and the
preadv/pwritev family, sendmsg and recvmsg get a host-side copy of
their iovec and msghdr with translated bases, leaving the guest copies
untouched. Code invalidation for kernel writes maps the host buffer
back to its guest address, and an unmap checks the table before it
changes any host mapping.

* Claim high guest memory only with LSE atomics and invalidate every code alias

High guest mappings are claimed only when the JIT emits LSE atomics, and
exclusive load/store instructions are never single-stepped, so an atomic
on high memory cannot spin. A store into high code invalidates every
mirror of the written page through the tracked mapping. madvise and
mprotect on high memory apply to each region at its own host address.

* Reject wrapping lengths and drop stale code on discarded high memory

A nonzero length that wraps when page-aligned now fails madvise with
EINVAL and mprotect with ENOMEM, as on Linux. Discarding advice on
high memory invalidates translated code for the range whenever advice
reached any region.

* Add an end-to-end probe for guest memory above the host address limit

* Emulate exclusive pairs on high guest memory and release failed host unmaps later

* Size counted guest buffers by element and keep exclusive access within guest protection

poll, ppoll, epoll waits, mmsg calls and select bitmaps now translate the whole array their count describes, so a buffer that crosses into an unrelated host range fails with EFAULT and oversized counts cannot wrap. High regions remember their protection through mprotect, splitting at the range edges, and exclusive stores to read-only pages or loads from inaccessible pages reach the guest as a fault instead of being emulated.

* Refuse a high unmap when failed host unmaps could not all be retained

UnmapLocked counts the overlapping regions before it changes anything and returns ENOMEM when the retired list could not hold all of them, so a host range is never dropped from tracking while still mapped.

* Serve memory trim requests while syscall user dispatch blocks

A thread that runs with syscall user dispatch on and its selector set to
block (as x86-64 Wine does while in Windows code) took the trim signal
with the selector still blocking. Every raw syscall the handler made was
then dispatched to the program's SIGSYS handler, which either deadlocked
the thread or killed the process when SIGSYS was blocked, so the session
saw it as a deaf process and the game stalled during loading.

Track the selector each thread registers through prctl, allow syscalls
for the length of the handler and restore the selector before returning.

* Allow syscalls for a forwarded prctl while dispatch blocks

The prctl wrapper issues its syscall from the preload's own text, so a
thread whose selector blocks got SIGSYS where the plain libc call would
have been dispatched the same way by the caller's own rules. Allow
syscalls for the forwarded call and restore the selector afterwards.

The dispatch test now waits until the selector blocks before it sends
the trim request, and checks a prctl call made while it blocks.

* Merge high regions after protection changes and translate message batches

Protect now merges neighbouring high regions whose guest and host
ranges touch and whose protection and code state match, so toggling
page protections no longer fills the region table.

Exclusive loads on high memory accept write-only pages and exclusive
stores need only PROT_WRITE, matching x86-64 where writable pages are
readable.

sendmmsg and recvmmsg translate the name, control and io vectors of
every message in the batch, return msg_len for each processed message
and the received header fields for recvmmsg.

Counted arrays passed to getgroups, setgroups, semop, semtimedop,
io_submit, io_getevents, io_pgetevents, move_pages, futex_waitv and
listmount are now checked to stay within one host range. The unused
ToHost helper is removed.

* Translate fixed-size, string and in-array guest pointers in high memory

Give every syscall pointer without a length a fixed x86-64 size, a
length read through another argument, or a terminator scan for strings,
so spans crossing separately backed regions are refused before the
kernel sees them. Size message queue buffers as the type word plus
msgsz. Translate io_submit control blocks and their buffers, including
vectored reads and writes, through bounded host copies, restore the
guest words afterwards, and report guest iocb addresses back from
io_getevents. Translate move_pages page lists for the calling process
and futex_waitv addresses. Merge new mappings with matching neighbours.

* Size high-memory syscall spans by kernel widths and embedded sizes

Read counts with the width the kernel uses for each argument, so int
and unsigned int counts ignore the upper register bits and negative
counts reach the handler. Size capability data by its header version,
perf and scheduler attributes, file handles and mount requests by their
own size fields, and landlock rules by rule type. Keep the translated
prefix of a message batch, read headers that span separate backings one
by one, write results back through the current guest mapping, and stop
counting messages whose length cannot be stored. Revisit an entry moved
into an earlier slot while merging regions. Give newer syscalls
fallback numbers in the test harness.

* Send translated message batches one message at a time

Submit sendmmsg batches that need scratch headers one message per call,
storing each length before the next message goes out, so a length that
cannot be stored stops the batch where Linux would. Skip the name length
when no name was given and store flags before the control length. Check
the whole fixed file-handle header even when its size is invalid. Hand
capget and capset a private header so the checked data size matches the
version the kernel reads, and return a rewritten version to the guest.
Patch and restore AIO control blocks under the mapping lock and restore
only the block that was patched.

* Harden high-memory aio, capability and message batch write-backs

Restore patched aio buffers through /proc/self/mem when the control block
became read-only and keep the scratch vectors alive if that fails too,
fault capability calls whose header write-back fails, stop send batches
after a short message, and pin the batch socket with a private dup.

* Pin batch sockets, fall back to whole batches and reconcile pending aio restores

Follow-up message sends and the first dispatch share one duplicated
socket. When it cannot be duplicated, the whole translated batch goes
to the kernel in one call and lengths are written back up to the first
one that cannot be stored. Short sends compare against the iovec
lengths given to the kernel. Unrestorable aio_buf edits, including
unreadable control blocks, keep their storage in a bounded list that
later submissions reconcile.

* Stop message batches at unreadable vectors, send singly without a spare descriptor and reserve aio restore slots

A message whose iovec snapshot cannot be taken ends the prepared batch
instead of being sent with an unknown length; when it is the first
message the kernel handles the original array natively. When the
batch socket cannot be duplicated, messages still go one at a time on
the original descriptor with each length written before the next send.
Pending aio restore slots are reserved under the pending mutex before
the first guest edit and released or handed to the pending record, so
concurrent submissions cannot exceed the bound. Tests use a real
socket pair, injected descriptor exhaustion and concurrent
reservations.

* Send only the first message of a batch when the socket cannot be pinned

* Replay high-memory faults over the whole access and reconcile aio restores on unmap

* Keep high-memory traps ordered, fault-exact and locked against unmap

Protect, Map and low mmap/munmap/mremap/mprotect reconcile pending aio
restores at once, and io_submit reconciles them even when no high region
is mapped. Ordered loads and stores split across backings are emulated
between full fences instead of being byte-copied through the trampoline;
atomics and exclusives are still refused. Gather and scatter use
fault-safe copies, and a failing piece is re-faulted at the guest
instruction through a probe load, with SIGBUS redelivered the same way.
The VMA lock is held from planning until the scatter finishes, so unmap
and protect cannot race a resumed access. Sign-extending loads are no
longer classified as writes.

* Defer user signals while guest high memory mappings are held

Only the trampoline breakpoint completes a replay, user-sent SIGSEGV,
SIGBUS and SIGTRAP raised while the mapping lock is held are requeued
after it is released, and stranded control block words are restored
when their page turns readable again. The harness now runs under a
timeout.

* Rebase the FEX patch series onto FEX-2612

* FEX: restore stranded aio words before readable protection, report failures

Restore every pending aio word in the range before a readable guest
protection is applied, on both the high and low paths, and fail the guest
mprotect with the old protection kept when a word cannot be restored or its
window cannot be closed. Ignore user-sent SIGSEGV/SIGBUS after deferral,
read the cleared syscall info when resuming with guest GPRs and on restore,
and check exclusive acquisition from a separate thread in the harness.

* FEX: submit aio control blocks through private host copies

Stop editing guest IOCBs in place when aio_buf needs translation. io_submit
now hands the kernel a host copy of each such control block, maps
io_event.obj back to the guest pointer when the completion is reaped,
redirects io_cancel by guest pointer and context to the copy, and frees
copies on reap, on io_destroy, or when the kernel did not accept them.
The guest control block is never patched and its protection is never
touched, so the pending restore records, the protection windows and the
restore hooks in mmap, munmap, mremap and mprotect are removed with their
tests.

* fex: keep aio keys, cancels and reaped events native for copied control blocks

Guest aio_key is no longer cleared before dispatch: the slot is probed with a
same-value write and only the first n accepted copies get key 0 after the host
io_submit returns n. io_cancel redirects to a copy only when the guest block is
readable and its key is 0, so unreadable blocks fault in the kernel as before.
io_getevents and io_pgetevents reap into emulator storage, translate and
release copies there, then copy the events out, returning -EFAULT if that
fails. A successful io_setup clears the ring header magic so userspace ring
reapers fall back to io_getevents, where copies are translated and released.

* fex: leave aio rejections, keys and unwritable event buffers to the kernel

A copied control block whose key slot is read-only is now passed to the
kernel as the guest's own block at the end of the list, so the kernel reports
its native fd, eventfd or key error. After io_submit, guest keys follow the
private copies through the first rejected position, and they are stored
through a fresh translation of the guest address, skipped when it no longer
maps. io_getevents and io_pgetevents probe the guest event buffer and reap at
most its writable prefix, handing an unwritable buffer to the kernel so
completions are not consumed.

* Kept AIO completions and key stores stable against sibling remaps

Wrapped event buffers go to the kernel unchanged. Direct reaps report guest
control blocks and release copies only after the store lands. Guest stores and
reads hold the mapping lock across translation and copy. Completions whose
copy-out fails are stashed per context and delivered first on the next reap,
and dropped on io_destroy.

* fex: stage every AIO reap and keep stashed completions recoverable

Hold the guest mapping for every high address, restore the caller's
signal mask after thread-context holds, replace the fixed event stash
with a per-context table that reserves space before dispatch, stage
all reaps so control block identities are translated before copy-out,
keep collecting ready completions once the stash meets min_nr, and
restash events on every error except an interrupted delivery or a
destroyed context.

* fex: own AIO recovery storage before dispatch and bind it to the context lifetime

Allocate the recovery node with the event buffer before the kernel
consumes completions and hand the buffer itself to the stash when
copy-out fails, so settling never allocates. Track each context by a
generation that io_setup advances, so a destroy that finishes after a
replacement context reuses the ring address only releases the old
context's copies and stash. Drop the reservation cap so blocking reaps
keep their min_nr.

* fex: publish AIO contexts from private storage, keep their generation, wake blocked reapers for stashed completions

* fex: wait for AIO events in bounded slices instead of wake markers, roll back setup by its own generation, fault unreadable io_setup output

Blocked reapers wait in the kernel for at most 20 ms at a time and take stashed completions between waits until the guest minimum or timeout is met, so no eventfd or io_submit notification is needed. Deferred signals end the wait like EINTR. io_setup rollback uses the generation BeginContext installed, and an unreadable context output returns -EFAULT before dispatch.

---------

Co-authored-by: StonkGuy <68372320+StonkGuy@users.noreply.github.com>
Co-authored-by: StonkGuy <StonkGuy@users.noreply.github.com>
2026-12-05 02:26:42 -05:00

3393 lines
186 KiB
Python

import platform
import re
import shutil
import signal
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 = {
"futex_wake": 454, "futex_wait": 455, "futex_requeue": 456, "statmount": 457, "listmount": 458,
"lsm_get_self_attr": 459, "lsm_set_self_attr": 460, "lsm_list_modules": 461,
"mseal": 462, "setxattrat": 463, "getxattrat": 464, "listxattrat": 465, "removexattrat": 466,
}
OLDEST_HEADERS_LAST_SYSCALL = 453
HARNESS_SECONDS = 120
PRELUDE = r"""
#include <algorithm>
#include <array>
#include <chrono>
#include <asm/unistd_64.h>
#include <atomic>
#include <cerrno>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <csignal>
#include <ctime>
#include <fcntl.h>
#include <functional>
#include <initializer_list>
#include <iterator>
#include <mutex>
#include <shared_mutex>
#include <utility>
#include <vector>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <thread>
#include <type_traits>
#include <list>
#include <unordered_map>
#include <unistd.h>
namespace fextl {
template<typename T> using vector = std::vector<T>;
template<typename T> using list = std::list<T>;
template<typename K, typename V> using unordered_map = std::unordered_map<K, V>;
using std::make_unique;
}
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"""
static int MunmapFailures;
static int TestMunmap(void* Address, size_t Size) {
if (MunmapFailures > 0) {
--MunmapFailures;
errno = ENOMEM;
return -1;
}
return munmap(Address, Size);
}
#define munmap TestMunmap
static int SendCalls;
static int SendFailures;
static size_t SendLimit = ~size_t {};
static int SentSocket = -1;
static size_t SentLengths[8];
static struct iovec* GrowAfterSend;
static void* UnmapAfterSend;
static bool PassSend;
static int DupFailures;
static int TestSendmmsg(int Socket, struct mmsghdr* Messages, unsigned int Count, int Flags) {
if (PassSend) {
return sendmmsg(Socket, Messages, Count, Flags);
}
SentSocket = Socket;
if (Count != 1 || SendFailures > 0) {
SendFailures -= SendFailures > 0;
errno = EAGAIN;
return -1;
}
size_t Length = 0;
for (size_t i = 0; i < Messages[0].msg_hdr.msg_iovlen; ++i) {
Length += Messages[0].msg_hdr.msg_iov[i].iov_len;
}
Length = std::min(Length, SendLimit);
SentLengths[SendCalls++ & 7] = Length;
Messages[0].msg_len = Length;
if (GrowAfterSend) {
GrowAfterSend->iov_len = 64;
}
if (UnmapAfterSend) {
munmap(UnmapAfterSend, 4096);
UnmapAfterSend = nullptr;
}
return 1;
}
#define sendmmsg TestSendmmsg
static int TestFcntl(int FD, int Command, int Argument = 0) {
if (Command == F_DUPFD_CLOEXEC && DupFailures > 0) {
--DupFailures;
errno = EMFILE;
return -1;
}
return fcntl(FD, Command, Argument);
}
#define fcntl TestFcntl
static int ProtectCalls;
static int TestMprotect(void* Address, size_t Size, int Prot) {
++ProtectCalls;
return mprotect(Address, Size, Prot);
}
#define mprotect TestMprotect
static uint64_t AioDestroyed;
static std::function<void(uint64_t)> AioDestroyHook;
static int AioReaps;
static uint64_t AioReapArgs[7];
static std::function<long(const uint64_t*)> AioReapHook;
template<typename T> static uint64_t SyscallWord(T Value) {
if constexpr (std::is_null_pointer_v<T>) {
return 0;
} else if constexpr (std::is_pointer_v<T>) {
return reinterpret_cast<uint64_t>(Value);
} else {
return static_cast<uint64_t>(Value);
}
}
template<typename... T> static long TestSyscall(long Number, T... Args) {
const uint64_t Words[] = {0, SyscallWord(Args)...};
if (Number == SYS_io_getevents || Number == SYS_io_pgetevents) {
++AioReaps;
std::copy_n(Words, std::min<size_t>(std::size(Words), 7), AioReapArgs);
AioReapArgs[0] = Number;
if (AioReapHook) {
return AioReapHook(Words);
}
errno = EINTR;
return -1;
}
if (Number == SYS_io_destroy) {
AioDestroyed = Words[1];
if (AioDestroyHook) {
AioDestroyHook(Words[1]);
}
errno = EINVAL;
return -1;
}
return syscall(Number, Args...);
}
#define syscall TestSyscall
namespace FEXCore {
template<template<typename> class LockType = std::unique_lock, typename MutexType>
inline auto MaskSignalsAndLockMutex(MutexType& Mutex, uint64_t = ~0ULL) { return LockType<MutexType> {Mutex}; }
}
namespace ArchHelpers::Context {
inline uint64_t GetArmReg(void* UContext, uint32_t Reg) { return static_cast<uint64_t*>(UContext)[Reg]; }
inline void SetArmReg(void* UContext, uint32_t Reg, uint64_t Value) { static_cast<uint64_t*>(UContext)[Reg] = Value; }
}
namespace FEX::HLE {
struct TestVMATracking { std::shared_mutex Mutex; };
struct TestSyscallHandler { TestVMATracking VMATracking; };
inline TestSyscallHandler TestHandler;
inline TestSyscallHandler* _SyscallHandler = &TestHandler;
struct TestThreadObject {
struct {
struct {
bool Held;
uint32_t Deferred;
siginfo_t DeferredInfo[3];
} Mappings;
} HighMemoryTrap;
struct {
std::vector<int> DeferredSignalFrames;
} SignalInfo;
};
inline TestThreadObject TestThread {};
struct ThreadManager {
static TestThreadObject* GetCurrentThreadObject() { return &TestThread; }
};
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) {
struct iovec Local {Dest, Size};
struct iovec Remote {const_cast<void*>(Src), Size};
return Size == 0 || process_vm_readv(getpid(), &Local, 1, &Remote, 1, 0) == static_cast<ssize_t>(Size) ? 0 : Size;
}
inline void (*BeforeUserWrite)() = nullptr;
inline size_t CopyToUser(void* Dest, const void* Src, size_t Size) {
if (auto* Hook = std::exchange(BeforeUserWrite, nullptr)) {
Hook();
}
struct iovec Local {const_cast<void*>(Src), Size};
struct iovec Remote {Dest, Size};
return Size == 0 || process_vm_writev(getpid(), &Local, 1, &Remote, 1, 0) == static_cast<ssize_t>(Size) ? 0 : Size;
}
}
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)); }
struct TestHold {
bool Held;
uint32_t Deferred;
siginfo_t DeferredInfo[3];
};
static std::atomic<int> TrapsSeen;
static std::atomic<int> TrapCode;
static std::atomic<int> TrapValue;
static bool ExclusiveFromAnotherThread() {
std::thread Writer([] { std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex}; });
Writer.join();
return true;
}
static void CountTrap(int, siginfo_t* Info, void*) {
++TrapsSeen;
TrapCode = Info->si_code;
TrapValue = Info->si_value.sival_int;
}
static uint64_t Call(uint32_t Syscall, uint64_t* Args, ArgumentStorage* Storage) { return TranslateSyscallArguments(Syscall, Args, 6, Storage); }
template<typename Arguments>
static uint64_t FinishResult(uint64_t Result, Arguments* Storage) {
if constexpr (std::is_void_v<decltype(FinishSyscallArguments(Result, Storage))>) {
FinishSyscallArguments(Result, Storage);
return Result;
} else {
return FinishSyscallArguments(Result, Storage);
}
}
int main() {
alarm(HARNESS_SECONDS);
const uint64_t Page = 4096;
static bool FirstHighStoreHeld;
FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] { FirstHighStoreHeld = FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held; };
const uint32_t FirstHighValue = 1;
Show("high_store_unmapped_result", CopyToGuest(0x720000000000ULL, &FirstHighValue, sizeof(FirstHighValue)));
Show("high_store_unmapped_held", FirstHighStoreHeld);
Show("high_store_unmapped_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held);
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_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, PROT_READ | PROT_WRITE);
AddEntry(Split, Page, Base + 2 * Page, false, PROT_READ | PROT_WRITE);
AddEntry(Split + Page, Page, Base + 4 * Page, false, PROT_READ | PROT_WRITE);
AddEntry(Joined, Page, Base + 5 * Page, false, PROT_READ | PROT_WRITE);
AddEntry(Joined + Page, Page, Base + 6 * Page, false, PROT_READ | PROT_WRITE);
ArgumentStorage Storage;
const int Peer = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
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));
uint64_t PollApart[6] = {Split + Page - 96, 25, 0, 0, 0, 0};
Show("poll_split_result", Call(Sys::SYSCALL_x64_poll, PollApart, &Storage));
uint64_t PollFits[6] = {Split + Page - 96, 12, 0, 0, 0, 0};
Show("poll_fits_result", Call(Sys::SYSCALL_x64_poll, PollFits, &Storage));
uint64_t PollJoined[6] = {Joined + Page - 96, 25, 0, 0, 0, 0};
Show("poll_joined_result", Call(Sys::SYSCALL_x64_poll, PollJoined, &Storage));
uint64_t PollHuge[6] = {Single, 1ULL << 61, 0, 0, 0, 0};
Show("poll_huge_result", Call(Sys::SYSCALL_x64_poll, PollHuge, &Storage));
uint64_t EpollApart[6] = {3, Split + Page - 96, 9, 0, 0, 0};
Show("epoll_split_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollApart, &Storage));
uint64_t EpollFits[6] = {3, Split + Page - 96, 8, 0, 0, 0};
Show("epoll_fits_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollFits, &Storage));
uint64_t SelectApart[6] = {1024, Split + Page - 64, 0, 0, 0, 0};
Show("select_split_result", Call(Sys::SYSCALL_x64_select, SelectApart, &Storage));
uint64_t SelectFits[6] = {512, Split + Page - 64, 0, 0, 0, 0};
Show("select_fits_result", Call(Sys::SYSCALL_x64_select, SelectFits, &Storage));
uint64_t SelectWide[6] = {(1ULL << 32) + 1, Single, 0, 0, 0, 0};
Show("select_wide_result", Call(Sys::SYSCALL_x64_select, SelectWide, &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, uint32_t) {
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));
auto* Guarded = static_cast<uint8_t*>(mmap(nullptr, 3 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Guard = 0x7b0000000000ULL;
RegionView Part {};
AddEntry(Guard, 3 * Page, reinterpret_cast<uint64_t>(Guarded), false, PROT_READ | PROT_WRITE);
Show("guard_protect", Protect(Guard + Page, Page, PROT_READ));
FindLocked(Guard, &Part);
Show("guard_low_size", Part.Size);
Show("guard_low_prot", Part.Prot);
FindLocked(Guard + Page, &Part);
Show("guard_mid_size", Part.Size);
Show("guard_mid_host", Part.Host - reinterpret_cast<uint64_t>(Guarded));
Show("guard_mid_prot", Part.Prot);
FindLocked(Guard + 2 * Page, &Part);
Show("guard_high_size", Part.Size);
Show("guard_high_prot", Part.Prot);
Show("guard_store_readonly", ExclusiveReachable(0xc8027c20, PROT_READ));
Show("guard_load_readonly", ExclusiveReachable(0xc85f7c20, PROT_READ));
Show("guard_store_writable", ExclusiveReachable(0xc8027c20, PROT_READ | PROT_WRITE));
Show("guard_load_none", ExclusiveReachable(0xc85f7c20, PROT_NONE));
Show("guard_pair_store_readonly", ExclusiveReachable(0xc8220c20, PROT_READ));
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));
auto* Spare = static_cast<uint8_t*>(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Retire = 0x7c0000000000ULL;
unsigned char Resident = 0;
RegionView View {};
AddEntry(Retire, 2 * Page, reinterpret_cast<uint64_t>(Spare), false, PROT_READ | PROT_WRITE);
MunmapFailures = 1;
Show("retire_unmap", UnmapLocked(Retire, Page));
Show("retire_pending", RetiredCount);
Show("retire_untracked", !FindLocked(Retire, &View));
Show("retire_host_held", mincore(Spare, Page, &Resident) == 0);
Show("retire_second", UnmapLocked(Retire + Page, Page));
Show("retire_released", RetiredCount);
Show("retire_host_gone", mincore(Spare, Page, &Resident) != 0 && errno == ENOMEM);
Show("retire_rest_gone", mincore(Spare + Page, Page, &Resident) != 0 && errno == ENOMEM);
auto* Kept = static_cast<uint8_t*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Full = 0x7a0000000000ULL;
AddEntry(Full, Page, reinterpret_cast<uint64_t>(Kept), false, PROT_READ | PROT_WRITE);
for (uint32_t i = 0; i < MaxRegions; ++i) {
Retired[i] = {0x10000000ULL + i * 2 * Page, Page};
}
RetiredCount = MaxRegions;
MunmapFailures = MaxRegions + 1;
Show("retire_full_unmap", UnmapLocked(Full, Page));
Show("retire_full_tracked", FindLocked(Full, &View));
Show("retire_full_host_held", mincore(Kept, Page, &Resident) == 0);
RetiredCount = 0;
MunmapFailures = 0;
Show("retire_full_after", UnmapLocked(Full, Page));
Show("retire_full_gone", !FindLocked(Full, &View));
struct {
uint64_t Host;
uint64_t Low;
uint64_t High;
uint32_t Size;
bool Valid;
} Monitor {};
uint64_t Context[32] {};
alignas(16) uint64_t Cell[2] = {5, 0};
const auto CellHost = reinterpret_cast<uint64_t>(Cell);
EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context);
Show("ldxr_value", Context[0]);
Context[0] = 9;
EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context);
Show("stxr_status", Context[2]);
Show("stxr_memory", Cell[0]);
EmulateExclusive(Monitor, 0xc85f7c20, CellHost, Context);
Cell[0] = 11;
Context[0] = 12;
EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context);
Show("contended_status", Context[2]);
Show("contended_memory", Cell[0]);
Context[0] = 13;
EmulateExclusive(Monitor, 0xc8027c20, CellHost, Context);
Show("unarmed_status", Context[2]);
Show("unarmed_memory", Cell[0]);
Cell[0] = 1;
Cell[1] = 2;
EmulateExclusive(Monitor, 0xc87f0c20, CellHost, Context);
Show("ldxp_low", Context[0]);
Show("ldxp_high", Context[3]);
Context[0] = 7;
Context[3] = 8;
EmulateExclusive(Monitor, 0xc8220c20, CellHost, Context);
Show("stxp_status", Context[2]);
Show("stxp_memory", Cell[0] * 16 + Cell[1]);
Cell[0] = 0x1122334455667788ULL;
EmulateExclusive(Monitor, 0x085f7c20, CellHost, Context);
Show("ldxrb_value", Context[0]);
Context[0] = 0x1ab;
EmulateExclusive(Monitor, 0x0802fc20, CellHost, Context);
Show("stlxrb_status", Context[2]);
Show("stlxrb_memory", Cell[0]);
Show("misaligned", EmulateExclusive(Monitor, 0xc85f7c20, CellHost + 4, Context));
Show("writeonly_load", ExclusiveReachable(0xc85f7c20, PROT_WRITE));
Show("writeonly_store", ExclusiveReachable(0xc8027c20, PROT_WRITE));
Show("writeonly_pair_store", ExclusiveReachable(0xc8220c20, PROT_WRITE));
Show("exec_only_load", ExclusiveReachable(0xc85f7c20, PROT_EXEC));
const uint32_t GuardEntries = Count.load();
Show("guard_restore", Protect(Guard + Page, Page, PROT_READ | PROT_WRITE));
FindLocked(Guard + Page, &Part);
Show("guard_restored_guest", Part.Guest - Guard);
Show("guard_restored_size", Part.Size);
Show("guard_restored_merged", GuardEntries - Count.load());
Show("split_hosts_kept_apart", FindLocked(Split + Page, &Part) && Part.Guest == Split + Page && Part.Size == Page);
const uint64_t Toggles = 1100;
auto* Striped = static_cast<uint8_t*>(mmap(nullptr, Toggles * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Stripe = 0x790000000000ULL;
AddEntry(Stripe, Toggles * Page, reinterpret_cast<uint64_t>(Striped), false, PROT_READ | PROT_WRITE);
const uint32_t StripeEntries = Count.load();
uint64_t ToggleFailures = 0;
for (uint64_t i = 0; i < Toggles; ++i) {
ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ) != 0;
ToggleFailures += Protect(Stripe + i * Page, Page, PROT_READ | PROT_WRITE) != 0;
}
Show("toggle_failures", ToggleFailures);
Show("toggle_entries", Count.load() - StripeEntries);
FindLocked(Stripe, &Part);
Show("toggle_pages", Part.Size / Page);
uint64_t SemApart[6] = {1, Split + Page - 12, 3, 0, 0, 0};
Show("semop_split_result", Call(Sys::SYSCALL_x64_semop, SemApart, &Storage));
uint64_t SemFits[6] = {1, Split + Page - 12, 2, 0, 0, 0};
Show("semop_fits_result", Call(Sys::SYSCALL_x64_semop, SemFits, &Storage));
uint64_t GroupsApart[6] = {4, Split + Page - 12, 0, 0, 0, 0};
Show("getgroups_split_result", Call(Sys::SYSCALL_x64_getgroups, GroupsApart, &Storage));
uint64_t EventsApart[6] = {1, 1, 2, Split + Page - 32, 0, 0};
Show("io_getevents_split_result", Call(Sys::SYSCALL_x64_io_getevents, EventsApart, &Storage));
uint64_t EventsFit[6] = {1, 1, 1, Split + Page - 32, 0, 0};
Show("io_getevents_fits_result", Call(Sys::SYSCALL_x64_io_getevents, EventsFit, &Storage));
uint64_t PagesApart[6] = {0, 2, Split + Page - 8, 0, 0, 0};
Show("move_pages_split_result", Call(Sys::SYSCALL_x64_move_pages, PagesApart, &Storage));
char BatchLow[16];
struct iovec SendVectors[2] = {{reinterpret_cast<void*>(Single + 256), 32}, {BatchLow, sizeof(BatchLow)}};
struct mmsghdr Outgoing[2] {};
Outgoing[0].msg_hdr.msg_iov = &SendVectors[0];
Outgoing[0].msg_hdr.msg_iovlen = 1;
Outgoing[1].msg_hdr.msg_iov = &SendVectors[1];
Outgoing[1].msg_hdr.msg_iovlen = 1;
ArgumentStorage SendBatch;
uint64_t Send[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Outgoing), 2, 0, 0, 0};
Show("sendmmsg_result", Call(Sys::SYSCALL_x64_sendmmsg, Send, &SendBatch));
auto* HostSend = reinterpret_cast<struct mmsghdr*>(Send[1]);
Show("sendmmsg_copied", HostSend != Outgoing);
Show("sendmmsg_high_base", reinterpret_cast<uint64_t>(HostSend[0].msg_hdr.msg_iov[0].iov_base) - Base);
Show("sendmmsg_low_base", HostSend[1].msg_hdr.msg_iov[0].iov_base == BatchLow);
Show("sendmmsg_guest_untouched", reinterpret_cast<uint64_t>(Outgoing[0].msg_hdr.msg_iov[0].iov_base) - Single);
Show("sendmmsg_submitted", Send[2]);
SendCalls = 0;
HostSend[0].msg_len = 32;
Show("sendmmsg_finish", FinishResult(1, &SendBatch));
Show("sendmmsg_later_sends", SendCalls);
Show("sendmmsg_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len);
Outgoing[0].msg_len = 0;
Outgoing[1].msg_len = 0;
ArgumentStorage DeclinedBatch;
uint64_t Declined[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Outgoing), 2, 0, 0, 0};
Call(Sys::SYSCALL_x64_sendmmsg, Declined, &DeclinedBatch);
reinterpret_cast<struct mmsghdr*>(Declined[1])[0].msg_len = 32;
SendFailures = 1;
Show("sendmmsg_refused_finish", FinishResult(1, &DeclinedBatch));
Show("sendmmsg_refused_lengths", Outgoing[0].msg_len * 0x100 + Outgoing[1].msg_len);
struct iovec ReceiveVectors[2] = {{reinterpret_cast<void*>(Single + 512), 64}, {BatchLow, sizeof(BatchLow)}};
struct mmsghdr Arriving[2] {};
Arriving[0].msg_hdr.msg_iov = &ReceiveVectors[0];
Arriving[0].msg_hdr.msg_iovlen = 1;
Arriving[1].msg_hdr.msg_iov = &ReceiveVectors[1];
Arriving[1].msg_hdr.msg_iovlen = 1;
ArgumentStorage ReceiveBatch;
uint64_t Batch[6] = {3, reinterpret_cast<uint64_t>(Arriving), 2, 0, 0, 0};
Show("recvmmsg_result", Call(Sys::SYSCALL_x64_recvmmsg, Batch, &ReceiveBatch));
auto* HostReceive = reinterpret_cast<struct mmsghdr*>(Batch[1]);
Show("recvmmsg_copied", HostReceive != Arriving);
Show("recvmmsg_base", reinterpret_cast<uint64_t>(HostReceive[0].msg_hdr.msg_iov[0].iov_base) - Base);
HostReceive[0].msg_len = 40;
HostReceive[0].msg_hdr.msg_flags = MSG_TRUNC;
HostReceive[1].msg_len = 5;
FinishSyscallArguments(1, &ReceiveBatch);
Show("recvmmsg_first_length", Arriving[0].msg_len);
Show("recvmmsg_first_flags", Arriving[0].msg_hdr.msg_flags);
Show("recvmmsg_second_length", Arriving[1].msg_len);
Show("recvmmsg_guest_iov", Arriving[0].msg_hdr.msg_iov == &ReceiveVectors[0]);
std::vector<struct mmsghdr> Many(1100);
Many[0].msg_hdr.msg_iov = &ReceiveVectors[0];
Many[0].msg_hdr.msg_iovlen = 1;
ArgumentStorage ManyBatch;
uint64_t Wide[6] = {3, reinterpret_cast<uint64_t>(Many.data()), Many.size(), 0, 0, 0};
Show("recvmmsg_wide_result", Call(Sys::SYSCALL_x64_recvmmsg, Wide, &ManyBatch));
Show("recvmmsg_wide_count", Wide[2]);
uint64_t BatchApart[6] = {3, Split + Page - 64, 2, 0, 0, 0};
Show("sendmmsg_split_result", Call(Sys::SYSCALL_x64_sendmmsg, BatchApart, &ManyBatch));
ArgumentStorage Sizes;
uint64_t StatSplit[6] = {3, Split + Page - 64, 0, 0, 0, 0};
Show("fstat_split_result", Call(Sys::SYSCALL_x64_fstat, StatSplit, &Sizes));
uint64_t StatEdge[6] = {3, Single + Page - 144, 0, 0, 0, 0};
Show("fstat_edge_result", Call(Sys::SYSCALL_x64_fstat, StatEdge, &Sizes));
uint64_t NameEdge[6] = {Single + Page - 390, 0, 0, 0, 0, 0};
Show("uname_edge_result", Call(Sys::SYSCALL_x64_uname, NameEdge, &Sizes));
uint64_t NameOver[6] = {Single + Page - 389, 0, 0, 0, 0, 0};
Show("uname_over_result", Call(Sys::SYSCALL_x64_uname, NameOver, &Sizes));
uint64_t Action[6] = {10, Single + Page - 32, 0, 8, 0, 0};
Show("sigaction_edge_result", Call(Sys::SYSCALL_x64_rt_sigaction, Action, &Sizes));
uint64_t ActionOver[6] = {10, Single + Page - 24, 0, 8, 0, 0};
Show("sigaction_over_result", Call(Sys::SYSCALL_x64_rt_sigaction, ActionOver, &Sizes));
uint64_t MaskApart[6] = {0, Split + Page - 4, 0, 8, 0, 0};
Show("sigprocmask_split_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskApart, &Sizes));
uint64_t MaskFits[6] = {0, Split + Page - 8, 0, 8, 0, 0};
Show("sigprocmask_fits_result", Call(Sys::SYSCALL_x64_rt_sigprocmask, MaskFits, &Sizes));
uint64_t Sleep[6] = {Single + Page - 16, 0, 0, 0, 0, 0};
Show("nanosleep_edge_result", Call(Sys::SYSCALL_x64_nanosleep, Sleep, &Sizes));
uint64_t SleepOver[6] = {Single + Page - 8, 0, 0, 0, 0, 0};
Show("nanosleep_over_result", Call(Sys::SYSCALL_x64_nanosleep, SleepOver, &Sizes));
uint64_t Residency[6] = {Low, 3 * Page, Split + Page - 2, 0, 0, 0};
Show("mincore_split_result", Call(Sys::SYSCALL_x64_mincore, Residency, &Sizes));
uint64_t ResidencyFits[6] = {Low, 2 * Page, Split + Page - 2, 0, 0, 0};
Show("mincore_fits_result", Call(Sys::SYSCALL_x64_mincore, ResidencyFits, &Sizes));
uint64_t Lock[6] = {3, F_GETLK, Split + Page - 16, 0, 0, 0};
Show("fcntl_lock_split_result", Call(Sys::SYSCALL_x64_fcntl, Lock, &Sizes));
uint64_t LockFits[6] = {3, F_GETLK, Single + Page - 32, 0, 0, 0};
Show("fcntl_lock_fits_result", Call(Sys::SYSCALL_x64_fcntl, LockFits, &Sizes));
Show("fcntl_lock_fits_buffer", LockFits[2] - Base);
std::memcpy(Backing + 3 * Page - 2, "ab", 2);
std::memcpy(Backing + 4 * Page, "cd", 3);
uint64_t PathApart[6] = {Split + Page - 2, 0, 0, 0, 0, 0};
Show("open_split_result", Call(Sys::SYSCALL_x64_open, PathApart, &Sizes));
std::memcpy(Backing + 6 * Page - 2, "ab", 2);
std::memcpy(Backing + 6 * Page, "cd", 3);
uint64_t PathJoined[6] = {Joined + Page - 2, 0, 0, 0, 0, 0};
Show("open_joined_result", Call(Sys::SYSCALL_x64_open, PathJoined, &Sizes));
Show("open_joined_path", PathJoined[0] - Base);
std::memcpy(Backing + 3000, "dir/file", 9);
uint64_t PathInside[6] = {static_cast<uint64_t>(AT_FDCWD), Single + 3000, 0, 0, 0, 0};
Show("openat_inside_result", Call(Sys::SYSCALL_x64_openat, PathInside, &Sizes));
Show("openat_inside_path", PathInside[1] - Base);
std::memset(Backing + Page - 8, 'x', 8);
uint64_t PathOpen[6] = {Single + Page - 8, 0, 0, 0, 0, 0};
Show("open_unterminated_result", Call(Sys::SYSCALL_x64_open, PathOpen, &Sizes));
uint64_t RenameApart[6] = {Single + 3000, Split + Page - 2, 0, 0, 0, 0};
Show("rename_split_result", Call(Sys::SYSCALL_x64_rename, RenameApart, &Sizes));
socklen_t AddressLength = 16;
uint64_t Accept[6] = {3, Split + Page - 16, reinterpret_cast<uint64_t>(&AddressLength), 0, 0, 0};
Show("accept_fits_result", Call(Sys::SYSCALL_x64_accept, Accept, &Sizes));
AddressLength = 32;
uint64_t AcceptOver[6] = {3, Split + Page - 16, reinterpret_cast<uint64_t>(&AddressLength), 0, 0, 0};
Show("accept_split_result", Call(Sys::SYSCALL_x64_accept, AcceptOver, &Sizes));
AddressLength = 4096;
uint64_t AcceptCapped[6] = {3, Single + Page - 128, reinterpret_cast<uint64_t>(&AddressLength), 0, 0, 0};
Show("accept_capped_result", Call(Sys::SYSCALL_x64_accept, AcceptCapped, &Sizes));
const uint32_t HighLength = 32;
std::memcpy(Backing + 40, &HighLength, sizeof(HighLength));
uint64_t AcceptHigh[6] = {3, Split + Page - 16, Single + 40, 0, 0, 0};
Show("accept_high_length_result", Call(Sys::SYSCALL_x64_accept, AcceptHigh, &Sizes));
uint32_t OptionLength = 8;
uint64_t Option[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast<uint64_t>(&OptionLength), 0};
Show("getsockopt_split_result", Call(Sys::SYSCALL_x64_getsockopt, Option, &Sizes));
OptionLength = 4;
uint64_t OptionFits[6] = {3, 1, 2, Split + Page - 4, reinterpret_cast<uint64_t>(&OptionLength), 0};
Show("getsockopt_fits_result", Call(Sys::SYSCALL_x64_getsockopt, OptionFits, &Sizes));
uint64_t QueueFits[6] = {1, Split + Page - 16, 8, 0, 0, 0};
Show("msgsnd_fits_result", Call(Sys::SYSCALL_x64_msgsnd, QueueFits, &Sizes));
uint64_t QueueOver[6] = {1, Split + Page - 16, 9, 0, 0, 0};
Show("msgsnd_split_result", Call(Sys::SYSCALL_x64_msgsnd, QueueOver, &Sizes));
uint64_t QueueReceive[6] = {1, Split + Page - 16, 9, 0, 0, 0};
Show("msgrcv_split_result", Call(Sys::SYSCALL_x64_msgrcv, QueueReceive, &Sizes));
uint64_t QueueHuge[6] = {1, Single, 1ULL << 40, 0, 0, 0};
Show("msgsnd_huge_result", Call(Sys::SYSCALL_x64_msgsnd, QueueHuge, &Sizes));
std::memcpy(Backing + 100, "x", 2);
uint64_t ValidFailures = 0;
uint64_t ValidTranslated = 0;
uint64_t StatValid[6] = {Single + 100, Single + 1024, 0, 0, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_stat, StatValid, &Sizes) != 0;
ValidTranslated += StatValid[0] == Base + 100 && StatValid[1] == Base + 1024;
uint64_t StatxValid[6] = {static_cast<uint64_t>(AT_FDCWD), Single + 100, 0, 0x7ff, Single + 1536, 0};
ValidFailures += Call(Sys::SYSCALL_x64_statx, StatxValid, &Sizes) != 0;
ValidTranslated += StatxValid[1] == Base + 100 && StatxValid[4] == Base + 1536;
uint64_t ClockValid[6] = {1, Single + 2048, 0, 0, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_clock_gettime, ClockValid, &Sizes) != 0;
ValidTranslated += ClockValid[1] == Base + 2048;
uint64_t WaitValid[6] = {static_cast<uint64_t>(-1), Single + 64, 0, Single + 512, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_wait4, WaitValid, &Sizes) != 0;
ValidTranslated += WaitValid[1] == Base + 64 && WaitValid[3] == Base + 512;
uint64_t PipeValid[6] = {Single + 8, 0, 0, 0, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_pipe2, PipeValid, &Sizes) != 0;
ValidTranslated += PipeValid[0] == Base + 8;
uint64_t LimitValid[6] = {0, 7, Single + 2560, Single + 2600, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_prlimit_64, LimitValid, &Sizes) != 0;
ValidTranslated += LimitValid[2] == Base + 2560 && LimitValid[3] == Base + 2600;
uint64_t TimerValid[6] = {1, 0, Single + 2304, Single + 2336, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_timer_settime, TimerValid, &Sizes) != 0;
ValidTranslated += TimerValid[2] == Base + 2304 && TimerValid[3] == Base + 2336;
AddressLength = 16;
uint64_t AcceptValid[6] = {3, Single + 256, reinterpret_cast<uint64_t>(&AddressLength), 0, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_accept, AcceptValid, &Sizes) != 0;
ValidTranslated += AcceptValid[1] == Base + 256;
uint64_t NameValid[6] = {Single, 0, 0, 0, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_uname, NameValid, &Sizes) != 0;
ValidTranslated += NameValid[0] == Base;
uint64_t SignalValid[6] = {10, Single + 2800, Single + 2900, 8, 0, 0};
ValidFailures += Call(Sys::SYSCALL_x64_rt_sigaction, SignalValid, &Sizes) != 0;
ValidTranslated += SignalValid[1] == Base + 2800 && SignalValid[2] == Base + 2900;
Show("single_valid_failures", ValidFailures);
Show("single_valid_translated", ValidTranslated);
struct TestIocb {
uint64_t Data;
uint32_t Key;
int32_t ReadWriteFlags;
uint16_t Opcode;
int16_t Priority;
uint32_t File;
uint64_t Buffer;
uint64_t Bytes;
int64_t Offset;
uint64_t Reserved;
uint32_t Flags;
uint32_t ResultFile;
};
TestIocb ReadBlock {};
ReadBlock.Data = 0x77;
ReadBlock.Key = 5;
ReadBlock.Buffer = Single + 768;
ReadBlock.Bytes = 64;
char VectorLow[16];
struct iovec Scatter[2] = {{reinterpret_cast<void*>(Single + 800), 16}, {VectorLow, sizeof(VectorLow)}};
TestIocb Vectored {};
Vectored.Opcode = 7;
Vectored.Buffer = reinterpret_cast<uint64_t>(Scatter);
Vectored.Bytes = 2;
TestIocb ReadExpected = ReadBlock;
const TestIocb VectoredExpected = Vectored;
auto GuestBlocksUntouched = [&] {
return std::memcmp(&ReadBlock, &ReadExpected, sizeof(TestIocb)) == 0 && std::memcmp(&Vectored, &VectoredExpected, sizeof(TestIocb)) == 0;
};
struct TestEvent {
uint64_t Data;
uint64_t Object;
int64_t Result;
int64_t Result2;
};
auto Deliver = [](const uint64_t* Args, const void* Events, size_t Size) {
static_cast<void>(FEX::HLE::FaultSafeUserMemAccess::CopyToUser(reinterpret_cast<void*>(Args[3]), Events, Size));
};
uint64_t Submitted[2] = {reinterpret_cast<uint64_t>(&ReadBlock), reinterpret_cast<uint64_t>(&Vectored)};
ArgumentStorage Submit;
uint64_t SubmitArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
const auto CopiesBefore = IoCopyCount.load();
ProtectCalls = 0;
Show("io_submit_result", Call(Sys::SYSCALL_x64_io_submit, SubmitArgs, &Submit));
Show("io_submit_count", SubmitArgs[1]);
Show("io_submit_list_copied", SubmitArgs[2] != reinterpret_cast<uint64_t>(Submitted));
const auto* Sent = reinterpret_cast<const uint64_t*>(SubmitArgs[2]);
const auto* SentRead = reinterpret_cast<const TestIocb*>(Sent[0]);
const auto* SentVector = reinterpret_cast<const TestIocb*>(Sent[1]);
Show("io_submit_private_blocks", SentRead != &ReadBlock && SentVector != &Vectored);
Show("io_submit_buffer", SentRead->Buffer - Base);
Show("io_submit_fields_kept", SentRead->Data == 0x77 && SentRead->Bytes == 64 && SentRead->Key == 5);
const auto* HostScatter = reinterpret_cast<const struct iovec*>(SentVector->Buffer);
Show("io_submit_vector_copied", HostScatter != Scatter);
Show("io_submit_vector_base", reinterpret_cast<uint64_t>(HostScatter[0].iov_base) - Base);
Show("io_submit_vector_low", HostScatter[1].iov_base == VectorLow);
Show("io_submit_guest_key", ReadBlock.Key);
Show("io_submit_guest_untouched", GuestBlocksUntouched());
Show("io_submit_copies", IoCopyCount.load() - CopiesBefore);
FinishSyscallArguments(2, &Submit);
Show("io_submit_accepted_key", ReadBlock.Key);
ReadExpected.Key = 0;
Show("io_submit_copies_kept", IoCopyCount.load() - CopiesBefore);
Show("io_submit_finished_untouched", GuestBlocksUntouched());
TestEvent CancelEvent {};
ArgumentStorage Cancel;
uint64_t CancelArgs[6] = {1, reinterpret_cast<uint64_t>(&ReadBlock), reinterpret_cast<uint64_t>(&CancelEvent), 0, 0, 0};
Show("io_cancel_result", Call(Sys::SYSCALL_x64_io_cancel, CancelArgs, &Cancel));
Show("io_cancel_private", CancelArgs[1] == Sent[0]);
ArgumentStorage CancelElsewhere;
uint64_t ElsewhereArgs[6] = {2, reinterpret_cast<uint64_t>(&ReadBlock), reinterpret_cast<uint64_t>(&CancelEvent), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, ElsewhereArgs, &CancelElsewhere);
Show("io_cancel_other_context", ElsewhereArgs[1] == reinterpret_cast<uint64_t>(&ReadBlock));
TestEvent Reaped[3] = {{0x77, Sent[0], 64, 0}, {0, Sent[1], 16, 0}, {8, Base + 1536, 16, 0}};
ArgumentStorage ReapCopies;
uint64_t ReapCopiesArgs[6] = {1, 1, 3, reinterpret_cast<uint64_t>(Reaped), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ReapCopiesArgs, &ReapCopies);
Show("io_getevents_host_buffer", ReapCopiesArgs[3] == reinterpret_cast<uint64_t>(ReapCopies.EventBuffer.data()));
Deliver(ReapCopiesArgs, Reaped, sizeof(Reaped));
FinishSyscallArguments(3, &ReapCopies);
Show("io_getevents_copy_object", Reaped[0].Object == reinterpret_cast<uint64_t>(&ReadBlock));
Show("io_getevents_vector_object", Reaped[1].Object == reinterpret_cast<uint64_t>(&Vectored));
Show("io_getevents_alias_object", Reaped[2].Object - Single);
Show("io_getevents_copies_freed", IoCopyCount.load() - CopiesBefore);
Show("io_getevents_untouched", GuestBlocksUntouched());
Show("io_submit_protect_calls", ProtectCalls);
auto* HighBlock = reinterpret_cast<TestIocb*>(Backing + 1536);
*HighBlock = {};
HighBlock->Opcode = 1;
HighBlock->Buffer = reinterpret_cast<uint64_t>(LowBuffer);
HighBlock->Bytes = sizeof(LowBuffer);
uint64_t HighList[1] = {Single + 1536};
ArgumentStorage HighSubmit;
uint64_t HighArgs[6] = {1, 1, reinterpret_cast<uint64_t>(HighList), 0, 0, 0};
Show("io_submit_high_result", Call(Sys::SYSCALL_x64_io_submit, HighArgs, &HighSubmit));
Show("io_submit_high_copied", HighArgs[2] != reinterpret_cast<uint64_t>(HighList));
Show("io_submit_high_block", reinterpret_cast<const uint64_t*>(HighArgs[2])[0] - Base);
Show("io_submit_high_guest_list", HighList[0] - Single);
Show("io_submit_high_uncopied", IoCopyCount.load() - CopiesBefore);
FinishSyscallArguments(1, &HighSubmit);
TestIocb BadBlock {};
BadBlock.Buffer = Split + Page - 8;
BadBlock.Bytes = 16;
uint64_t Mixed[2] = {reinterpret_cast<uint64_t>(&ReadBlock), reinterpret_cast<uint64_t>(&BadBlock)};
ArgumentStorage Partial;
uint64_t PartialArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Mixed), 0, 0, 0};
Show("io_submit_partial_result", Call(Sys::SYSCALL_x64_io_submit, PartialArgs, &Partial));
Show("io_submit_partial_count", PartialArgs[1]);
Show("io_submit_partial_copies", IoCopyCount.load() - CopiesBefore);
FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &Partial);
Show("io_submit_partial_released", IoCopyCount.load() - CopiesBefore);
Show("io_submit_partial_untouched", GuestBlocksUntouched());
ArgumentStorage Truncated;
uint64_t TruncatedArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, TruncatedArgs, &Truncated);
const uint64_t TruncatedFirst = reinterpret_cast<const uint64_t*>(TruncatedArgs[2])[0];
FinishSyscallArguments(1, &Truncated);
Show("io_submit_short_kept", IoCopyCount.load() - CopiesBefore);
Show("io_submit_short_first_live", FindIoCopyLocked(TruncatedFirst) != nullptr);
ArgumentStorage OtherContext;
uint64_t OtherContextArgs[6] = {3, 1, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, OtherContextArgs, &OtherContext);
FinishSyscallArguments(1, &OtherContext);
ArgumentStorage Destroy;
uint64_t DestroyArgs[6] = {1, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, DestroyArgs, &Destroy);
FinishSyscallArguments(0, &Destroy);
Show("io_destroy_released", IoCopyCount.load() - CopiesBefore);
ArgumentStorage DestroyFailed;
uint64_t DestroyFailedArgs[6] = {3, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, DestroyFailedArgs, &DestroyFailed);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &DestroyFailed);
Show("io_destroy_failed_kept", IoCopyCount.load() - CopiesBefore);
ArgumentStorage DestroyOther;
uint64_t DestroyOtherArgs[6] = {3, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, DestroyOtherArgs, &DestroyOther);
FinishSyscallArguments(0, &DestroyOther);
Show("io_destroy_other_released", IoCopyCount.load() - CopiesBefore);
uint64_t OnlyCrossing[1] = {reinterpret_cast<uint64_t>(&BadBlock)};
ArgumentStorage FirstBad;
uint64_t FirstBadArgs[6] = {1, 1, reinterpret_cast<uint64_t>(OnlyCrossing), 0, 0, 0};
Show("io_submit_first_bad_result", Call(Sys::SYSCALL_x64_io_submit, FirstBadArgs, &FirstBad));
FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &FirstBad);
Show("io_submit_first_bad_copies", IoCopyCount.load() - CopiesBefore);
TestIocb KeyFirst = ReadBlock;
KeyFirst.Key = 5;
TestIocb KeySecond = ReadBlock;
KeySecond.Key = 6;
uint64_t KeyList[2] = {reinterpret_cast<uint64_t>(&KeyFirst), reinterpret_cast<uint64_t>(&KeySecond)};
ArgumentStorage KeySubmit;
uint64_t KeySubmitArgs[6] = {4, 2, reinterpret_cast<uint64_t>(KeyList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, KeySubmitArgs, &KeySubmit);
const uint64_t KeyFirstSent = reinterpret_cast<const uint64_t*>(KeySubmitArgs[2])[0];
Show("io_submit_keys_prepared", KeyFirst.Key == 5 && KeySecond.Key == 6);
TestEvent KeyCancelEvent {};
ArgumentStorage EarlyCancel;
uint64_t EarlyCancelArgs[6] = {4, reinterpret_cast<uint64_t>(&KeyFirst), reinterpret_cast<uint64_t>(&KeyCancelEvent), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, EarlyCancelArgs, &EarlyCancel);
Show("io_cancel_keyed_native", EarlyCancelArgs[1] == reinterpret_cast<uint64_t>(&KeyFirst));
FinishSyscallArguments(1, &KeySubmit);
Show("io_submit_key_accepted", KeyFirst.Key);
Show("io_submit_key_after_rejected", KeySecond.Key);
Show("io_submit_key_rejected_released", IoCopyCount.load() - CopiesBefore);
ArgumentStorage LateCancel;
uint64_t LateCancelArgs[6] = {4, reinterpret_cast<uint64_t>(&KeyFirst), reinterpret_cast<uint64_t>(&KeyCancelEvent), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, LateCancelArgs, &LateCancel);
Show("io_cancel_accepted_private", LateCancelArgs[1] == KeyFirstSent);
TestIocb KeyA = ReadBlock;
KeyA.Key = 7;
TestIocb KeyB = ReadBlock;
KeyB.Key = 8;
TestIocb KeyC = ReadBlock;
KeyC.Key = 9;
uint64_t KeyTriple[3] = {reinterpret_cast<uint64_t>(&KeyA), reinterpret_cast<uint64_t>(&KeyB), reinterpret_cast<uint64_t>(&KeyC)};
ArgumentStorage RejectSubmit;
uint64_t RejectSubmitArgs[6] = {6, 3, reinterpret_cast<uint64_t>(KeyTriple), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, RejectSubmitArgs, &RejectSubmit);
const auto* RejectSent = reinterpret_cast<const uint64_t*>(RejectSubmitArgs[2]);
reinterpret_cast<TestIocb*>(RejectSent[0])->Key = 0;
reinterpret_cast<TestIocb*>(RejectSent[1])->Key = 0;
FinishSyscallArguments(1, &RejectSubmit);
Show("io_submit_rejected_key_cleared", KeyA.Key == 0 && KeyB.Key == 0);
Show("io_submit_unreached_key", KeyC.Key);
TestIocb KeyD = ReadBlock;
KeyD.Key = 3;
uint64_t KeySingle[1] = {reinterpret_cast<uint64_t>(&KeyD)};
ArgumentStorage FirstRejected;
uint64_t FirstRejectedArgs[6] = {6, 1, reinterpret_cast<uint64_t>(KeySingle), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, FirstRejectedArgs, &FirstRejected);
reinterpret_cast<TestIocb*>(reinterpret_cast<const uint64_t*>(FirstRejectedArgs[2])[0])->Key = 0;
FinishSyscallArguments(static_cast<uint64_t>(-EBADF), &FirstRejected);
Show("io_submit_first_rejected_key", KeyD.Key);
ArgumentStorage RejectDestroy;
uint64_t RejectDestroyArgs[6] = {6, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, RejectDestroyArgs, &RejectDestroy);
FinishSyscallArguments(0, &RejectDestroy);
Show("io_submit_rejected_released", IoCopyCount.load() - CopiesBefore);
auto* SealedEvents = static_cast<TestEvent*>(mmap(nullptr, Page, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
int64_t NoWait[2] = {0, 0};
const uint64_t Immediate = reinterpret_cast<uint64_t>(NoWait);
ArgumentStorage UnwritableReap;
uint64_t UnwritableReapArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, UnwritableReapArgs, &UnwritableReap);
Show("io_getevents_unwritable_staged", UnwritableReapArgs[3] == reinterpret_cast<uint64_t>(UnwritableReap.EventBuffer.data()) &&
UnwritableReapArgs[2] == 1 && UnwritableReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t));
Show("io_getevents_unwritable_result", FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &UnwritableReap));
Show("io_getevents_unwritable_kept", IoCopyCount.load() - CopiesBefore);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage SealedReap;
uint64_t SealedReapArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, SealedReapArgs, &SealedReap);
mprotect(SealedEvents, Page, PROT_READ);
const TestEvent SealedEvent {0x77, KeyFirstSent, 64, 0};
Deliver(SealedReapArgs, &SealedEvent, sizeof(SealedEvent));
Show("io_getevents_sealed_result", FinishSyscallArguments(1, &SealedReap));
Show("io_getevents_sealed_released", IoCopyCount.load() - CopiesBefore);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage StashedReap;
uint64_t StashedReapArgs[6] = {4, 1, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, StashedReapArgs, &StashedReap);
Show("io_getevents_stash_nonblocking", StashedReapArgs[1] == 0 && StashedReapArgs[2] == 1 &&
StashedReapArgs[3] == reinterpret_cast<uint64_t>(StashedReap.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t)));
Show("io_getevents_stash_result", FinishSyscallArguments(0, &StashedReap));
Show("io_getevents_stash_event", SealedEvents[0].Object == reinterpret_cast<uint64_t>(&KeyFirst) && SealedEvents[0].Data == 0x77);
ArgumentStorage DrainedReap;
uint64_t DrainedReapArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), Immediate, 0};
Call(Sys::SYSCALL_x64_io_getevents, DrainedReapArgs, &DrainedReap);
Show("io_getevents_stash_once", DrainedReapArgs[1] == 1 && DrainedReapArgs[2] == 1 && FinishSyscallArguments(0, &DrainedReap) == 0);
auto FailReap = [&](uint64_t Context, const TestEvent& Event) {
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage Failed;
uint64_t FailedArgs[6] = {Context, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, FailedArgs, &Failed);
mprotect(SealedEvents, Page, PROT_READ);
Deliver(FailedArgs, &Event, sizeof(Event));
const auto Result = FinishSyscallArguments(1, &Failed);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
return Result;
};
Show("io_getevents_stash_ready_failed", FailReap(4, {0x57, reinterpret_cast<uint64_t>(&KeyD), 1, 0}));
ArgumentStorage ReadyReap;
uint64_t ReadyReapArgs[6] = {4, 1, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ReadyReapArgs, &ReadyReap);
const TestEvent Ready {0x58, reinterpret_cast<uint64_t>(&KeyC), 1, 0};
Deliver(ReadyReapArgs, &Ready, sizeof(Ready));
Show("io_getevents_stash_ready_result", FinishSyscallArguments(1, &ReadyReap));
Show("io_getevents_stash_ready_order", SealedEvents[0].Data == 0x57 && SealedEvents[1].Data == 0x58 &&
SealedEvents[1].Object == reinterpret_cast<uint64_t>(&KeyC));
Show("io_getevents_stash_plain_failed", FailReap(4, {0x55, reinterpret_cast<uint64_t>(&KeyD), 1, 0}));
ArgumentStorage TopUp;
uint64_t TopUpArgs[6] = {4, 2, 3, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, TopUpArgs, &TopUp);
Show("io_getevents_stash_topup_args", TopUpArgs[1] == 1 && TopUpArgs[2] == 2 &&
TopUpArgs[3] == reinterpret_cast<uint64_t>(TopUp.EventBuffer.data() + sizeof(TestEvent) / sizeof(uint64_t)));
const TestEvent Fresh {0x66, reinterpret_cast<uint64_t>(&KeyA), 2, 0};
Deliver(TopUpArgs, &Fresh, sizeof(Fresh));
Show("io_getevents_stash_topup_result", FinishSyscallArguments(1, &TopUp));
Show("io_getevents_stash_topup_order", SealedEvents[0].Data == 0x55 && SealedEvents[0].Object == reinterpret_cast<uint64_t>(&KeyD) &&
SealedEvents[1].Data == 0x66 && SealedEvents[1].Object == reinterpret_cast<uint64_t>(&KeyA));
FailReap(4, {0x44, reinterpret_cast<uint64_t>(&KeyB), 1, 0});
ArgumentStorage FaultedRetry;
uint64_t FaultedRetryArgs[6] = {4, 2, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, FaultedRetryArgs, &FaultedRetry);
Show("io_getevents_stash_fault_result", FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &FaultedRetry));
ArgumentStorage Interrupted;
uint64_t InterruptedArgs[6] = {4, 2, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, InterruptedArgs, &Interrupted);
Show("io_getevents_stash_kept_after_fault", InterruptedArgs[1] == 1 && InterruptedArgs[2] == 1);
Show("io_getevents_stash_interrupted", FinishSyscallArguments(static_cast<uint64_t>(-EINTR), &Interrupted));
Show("io_getevents_stash_interrupted_event", SealedEvents[0].Data == 0x44 && SealedEvents[0].Object == reinterpret_cast<uint64_t>(&KeyB));
FailReap(4, {0x45, reinterpret_cast<uint64_t>(&KeyB), 1, 0});
ArgumentStorage RejectedMask;
uint64_t RejectedMaskArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_pgetevents, RejectedMaskArgs, &RejectedMask);
Show("io_getevents_stash_einval_result", FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &RejectedMask));
ArgumentStorage AfterRejected;
uint64_t AfterRejectedArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, AfterRejectedArgs, &AfterRejected);
Show("io_getevents_stash_einval_kept", FinishSyscallArguments(0, &AfterRejected) == 1 && SealedEvents[0].Data == 0x45);
FailReap(12, {0x46, reinterpret_cast<uint64_t>(&KeyB), 1, 0});
ArgumentStorage InFlight;
uint64_t InFlightArgs[6] = {12, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, InFlightArgs, &InFlight);
ArgumentStorage InFlightDestroy;
uint64_t InFlightDestroyArgs[6] = {12, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, InFlightDestroyArgs, &InFlightDestroy);
FinishSyscallArguments(0, &InFlightDestroy);
ArgumentStorage Recreated;
uint64_t RecreatedArgs[6] = {12, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), Immediate, 0};
Call(Sys::SYSCALL_x64_io_getevents, RecreatedArgs, &Recreated);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &InFlight);
Show("io_getevents_stash_recreated_result", FinishSyscallArguments(0, &Recreated));
ArgumentStorage AfterDestroy;
uint64_t AfterDestroyArgs[6] = {12, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), Immediate, 0};
Call(Sys::SYSCALL_x64_io_getevents, AfterDestroyArgs, &AfterDestroy);
Show("io_getevents_stash_destroyed_in_flight", AfterDestroyArgs[1] == 1 && AfterDestroyArgs[2] == 1 && FinishSyscallArguments(0, &AfterDestroy) == 0);
std::vector<TestEvent> FullStash(65536);
ArgumentStorage Filling;
uint64_t FillingArgs[6] = {31, 1, FullStash.size(), reinterpret_cast<uint64_t>(FullStash.data()), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, FillingArgs, &Filling);
ArgumentStorage Contended;
uint64_t ContendedArgs[6] = {31, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ContendedArgs, &Contended);
Show("io_getevents_stash_blocking_kept", FillingArgs[2] == FullStash.size() && ContendedArgs[1] == 1 && ContendedArgs[2] == 1);
FinishSyscallArguments(0, &Contended);
FinishSyscallArguments(0, &Filling);
ArgumentStorage Uncrowded;
uint64_t UncrowdedArgs[6] = {31, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, UncrowdedArgs, &Uncrowded);
Show("io_getevents_stash_reserve_released", UncrowdedArgs[1] == 1 && UncrowdedArgs[2] == 1);
FinishSyscallArguments(0, &Uncrowded);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage Owned;
uint64_t OwnedArgs[6] = {32, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, OwnedArgs, &Owned);
const auto* OwnedBuffer = Owned.EventBuffer.data();
const bool OwnedReady = Owned.Recovery.size() == 1;
mprotect(SealedEvents, Page, PROT_READ);
const TestEvent OwnedEvent {0x47, reinterpret_cast<uint64_t>(&KeyB), 1, 0};
Deliver(OwnedArgs, &OwnedEvent, sizeof(OwnedEvent));
const auto OwnedResult = FinishSyscallArguments(1, &Owned);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
const auto& OwnedState = AioContextsLocked()[32];
Show("io_getevents_recovery_preallocated", OwnedReady && OwnedResult == static_cast<uint64_t>(-EFAULT) && Owned.Recovery.empty() &&
OwnedState.Batches.size() == 1 && OwnedState.Batches.front().data() == OwnedBuffer);
ArgumentStorage OwnedRetry;
uint64_t OwnedRetryArgs[6] = {32, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, OwnedRetryArgs, &OwnedRetry);
Show("io_getevents_recovery_delivered", FinishSyscallArguments(0, &OwnedRetry) == 1 && SealedEvents[0].Data == 0x47);
uint32_t ReplacementRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
const uint64_t Replaced = reinterpret_cast<uint64_t>(ReplacementRing);
FailReap(Replaced, {0x48, reinterpret_cast<uint64_t>(&KeyB), 1, 0});
const auto ReplacedCopies = IoCopyCount.load();
ArgumentStorage OldSubmit;
uint64_t OldSubmitArgs[6] = {Replaced, 1, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, OldSubmitArgs, &OldSubmit);
const auto OldCopy = reinterpret_cast<const uint64_t*>(OldSubmitArgs[2])[0];
FinishSyscallArguments(1, &OldSubmit);
ArgumentStorage OldDestroy;
uint64_t OldDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, OldDestroyArgs, &OldDestroy);
uint64_t ReplacementContext = Replaced;
ArgumentStorage Replacement;
uint64_t ReplacementArgs[6] = {128, reinterpret_cast<uint64_t>(&ReplacementContext), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, ReplacementArgs, &Replacement);
FinishSyscallArguments(0, &Replacement);
ArgumentStorage NewSubmit;
uint64_t NewSubmitArgs[6] = {Replaced, 1, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, NewSubmitArgs, &NewSubmit);
const auto NewCopy = reinterpret_cast<const uint64_t*>(NewSubmitArgs[2])[0];
FinishSyscallArguments(1, &NewSubmit);
ArgumentStorage StaleReap;
uint64_t StaleReapArgs[6] = {Replaced, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, StaleReapArgs, &StaleReap);
const bool StaleSkipped = StaleReapArgs[1] == 1 && StaleReapArgs[2] == 1;
FinishSyscallArguments(0, &StaleReap);
FailReap(Replaced, {0x49, reinterpret_cast<uint64_t>(&KeyB), 1, 0});
FinishSyscallArguments(0, &OldDestroy);
Show("io_destroy_replacement_copies_kept", StaleSkipped && IoCopyCount.load() - ReplacedCopies == 1 && OldCopy != NewCopy &&
!FindIoCopyLocked(OldCopy) && FindIoCopyLocked(NewCopy));
ArgumentStorage ReplacementRetry;
uint64_t ReplacementRetryArgs[6] = {Replaced, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ReplacementRetryArgs, &ReplacementRetry);
Show("io_destroy_replacement_stash_kept", FinishSyscallArguments(0, &ReplacementRetry) == 1 && SealedEvents[0].Data == 0x49);
ArgumentStorage NewDestroy;
uint64_t NewDestroyArgs[6] = {Replaced, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, NewDestroyArgs, &NewDestroy);
FinishSyscallArguments(0, &NewDestroy);
Show("io_destroy_replacement_released", IoCopyCount.load() - ReplacedCopies + (FindIoCopyLocked(NewCopy) != nullptr));
uint32_t WakeRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
const uint64_t Woken = reinterpret_cast<uint64_t>(WakeRing);
uint64_t WakeContext = Woken;
ArgumentStorage WakeSetup;
uint64_t WakeSetupArgs[6] = {128, reinterpret_cast<uint64_t>(&WakeContext), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, WakeSetupArgs, &WakeSetup);
const bool SetupPrivate = WakeSetupArgs[1] == reinterpret_cast<uint64_t>(&WakeSetup.SetupId);
FinishSyscallArguments(0, &WakeSetup);
const auto WakeGeneration = AioContextsLocked()[Woken].Generation;
ArgumentStorage WakeRejected;
uint64_t WakeRejectedArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, WakeRejectedArgs, &WakeRejected);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &WakeRejected);
Show("io_setup_generation_kept", SetupPrivate && WakeGeneration != 0 && AioContextsLocked().count(Woken) == 1 &&
AioContextsLocked()[Woken].Generation == WakeGeneration && AioContextsLocked()[Woken].Live);
const uint64_t EventWords = sizeof(TestEvent) / sizeof(uint64_t);
const int ReapsBefore = AioReaps;
ArgumentStorage Blocked;
uint64_t BlockedArgs[6] = {Woken, 2, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, BlockedArgs, &Blocked);
Show("io_getevents_blocking_sliced", Blocked.Blocking && BlockedArgs[1] == 2 && BlockedArgs[2] == 2 &&
BlockedArgs[4] == reinterpret_cast<uint64_t>(Blocked.Wait) && Blocked.Wait[0] == 0 && Blocked.Wait[1] == 20000000 && Blocked.Deadline < 0);
ArgumentStorage StashPair;
uint64_t StashPairArgs[6] = {Woken, 2, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, StashPairArgs, &StashPair);
mprotect(SealedEvents, Page, PROT_READ);
const TestEvent StashPairEvents[2] = {{0x4a, reinterpret_cast<uint64_t>(&KeyB), 1, 0}, {0x4b, reinterpret_cast<uint64_t>(&KeyC), 1, 0}};
Deliver(StashPairArgs, StashPairEvents, sizeof(StashPairEvents));
const auto StashPairResult = FinishSyscallArguments(2, &StashPair);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
Show("io_getevents_slice_collects_stash", StashPairResult == static_cast<uint64_t>(-EFAULT) && FinishSyscallArguments(0, &Blocked) == 2 &&
AioReaps == ReapsBefore && SealedEvents[0].Data == 0x4a && SealedEvents[1].Data == 0x4b &&
SealedEvents[1].Object == reinterpret_cast<uint64_t>(&KeyC));
ArgumentStorage Waiting;
uint64_t WaitingArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, WaitingArgs, &Waiting);
bool SiblingStashed = false;
AioReapHook = [&](const uint64_t* Words) -> long {
SiblingStashed = Words[1] == Woken && Words[2] == 1 && Words[3] == 1 && Words[4] == reinterpret_cast<uint64_t>(Waiting.EventBuffer.data()) &&
Words[5] == reinterpret_cast<uint64_t>(Waiting.Wait) && Waiting.Wait[1] == 20000000 &&
FailReap(Woken, {0x4c, reinterpret_cast<uint64_t>(&KeyB), 1, 0}) == static_cast<uint64_t>(-EFAULT);
return 0;
};
const auto WaitingResult = FinishSyscallArguments(0, &Waiting);
AioReapHook = nullptr;
Show("io_getevents_slice_without_notification", SiblingStashed && WaitingResult == 1 && AioReaps == ReapsBefore + 1 &&
AioReapArgs[0] == SYS_io_getevents && SealedEvents[0].Data == 0x4c);
ArgumentStorage Gathering;
uint64_t GatheringArgs[6] = {Woken, 3, 3, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, GatheringArgs, &Gathering);
const TestEvent Trickle[3] = {{0x51, reinterpret_cast<uint64_t>(&KeyA), 1, 0}, {0x52, reinterpret_cast<uint64_t>(&KeyB), 1, 0},
{0x53, reinterpret_cast<uint64_t>(&KeyC), 1, 0}};
Deliver(GatheringArgs, &Trickle[0], sizeof(TestEvent));
int Waits = 0;
bool Remaining = true;
AioReapHook = [&](const uint64_t* Words) -> long {
++Waits;
if (Waits == 1) {
Remaining = Remaining && Words[2] == 2 && Words[3] == 2 && Words[4] == reinterpret_cast<uint64_t>(Gathering.EventBuffer.data() + EventWords);
return 0;
}
const uint64_t Have = Waits == 2 ? 1 : 2;
Remaining = Remaining && Words[2] == 3 - Have && Words[3] == 3 - Have &&
Words[4] == reinterpret_cast<uint64_t>(Gathering.EventBuffer.data() + Have * EventWords);
std::memcpy(reinterpret_cast<void*>(Words[4]), &Trickle[Have], sizeof(TestEvent));
return 1;
};
const auto GatheringResult = FinishSyscallArguments(1, &Gathering);
AioReapHook = nullptr;
Show("io_getevents_slices_accumulate", GatheringResult == 3 && Waits == 3 && Remaining && SealedEvents[0].Data == 0x51 &&
SealedEvents[1].Data == 0x52 && SealedEvents[2].Data == 0x53 && SealedEvents[2].Object == reinterpret_cast<uint64_t>(&KeyC));
ArgumentStorage Interrupt;
uint64_t InterruptArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, InterruptArgs, &Interrupt);
const int ReapsInterrupt = AioReaps;
Show("io_getevents_slice_host_eintr", FinishSyscallArguments(0, &Interrupt) == static_cast<uint64_t>(-EINTR) && AioReaps == ReapsInterrupt + 1);
FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.push_back(SIGUSR1);
ArgumentStorage Signalled;
uint64_t SignalledArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, SignalledArgs, &Signalled);
const int ReapsSignalled = AioReaps;
const auto SignalledResult = FinishSyscallArguments(0, &Signalled);
ArgumentStorage SignalledSome;
uint64_t SignalledSomeArgs[6] = {Woken, 2, 2, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, SignalledSomeArgs, &SignalledSome);
Deliver(SignalledSomeArgs, &Trickle[1], sizeof(TestEvent));
const auto SignalledSomeResult = FinishSyscallArguments(1, &SignalledSome);
FEX::HLE::TestThread.SignalInfo.DeferredSignalFrames.clear();
Show("io_getevents_slice_deferred_signal", SignalledResult == static_cast<uint64_t>(-EINTR) && SignalledSomeResult == 1 &&
AioReaps == ReapsSignalled && SealedEvents[0].Data == 0x52);
ArgumentStorage Polled;
uint64_t PolledArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), Immediate, 0};
Call(Sys::SYSCALL_x64_io_getevents, PolledArgs, &Polled);
const int ReapsPolled = AioReaps;
Show("io_getevents_zero_timeout", PolledArgs[4] == reinterpret_cast<uint64_t>(Polled.Wait) && Polled.Wait[0] == 0 && Polled.Wait[1] == 0 &&
FinishSyscallArguments(0, &Polled) == 0 && AioReaps == ReapsPolled);
int64_t ShortWait[2] = {0, 1000000};
ArgumentStorage Timed;
uint64_t TimedArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), reinterpret_cast<uint64_t>(ShortWait), 0};
const auto TimedStart = std::chrono::steady_clock::now();
Call(Sys::SYSCALL_x64_io_getevents, TimedArgs, &Timed);
const bool TimedFirst = Timed.Wait[0] == 0 && Timed.Wait[1] > 0 && Timed.Wait[1] <= 1000000;
bool TimedBounded = true;
AioReapHook = [&](const uint64_t* Words) -> long {
const auto* Wait = reinterpret_cast<const int64_t*>(Words[5]);
TimedBounded = TimedBounded && Wait[0] == 0 && Wait[1] > 0 && Wait[1] <= 1000000;
return 0;
};
const auto TimedResult = FinishSyscallArguments(0, &Timed);
const auto TimedTook = std::chrono::steady_clock::now() - TimedStart;
AioReapHook = nullptr;
Show("io_getevents_timeout_returns_empty", TimedFirst && TimedBounded && TimedResult == 0 && TimedTook >= std::chrono::milliseconds(1) &&
ShortWait[0] == 0 && ShortWait[1] == 1000000);
int64_t LongWait[2] = {5, 0};
uint64_t MaskWords[2] = {0, 8};
ArgumentStorage Masked;
uint64_t MaskedArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), reinterpret_cast<uint64_t>(LongWait), reinterpret_cast<uint64_t>(MaskWords)};
Call(Sys::SYSCALL_x64_io_pgetevents, MaskedArgs, &Masked);
const bool MaskedSliced = Masked.Wait[0] == 0 && Masked.Wait[1] == 20000000 && Masked.Deadline > 0;
AioReapHook = [&](const uint64_t* Words) -> long {
std::memcpy(reinterpret_cast<void*>(Words[4]), &Trickle[2], sizeof(TestEvent));
return 1;
};
const auto MaskedResult = FinishSyscallArguments(0, &Masked);
AioReapHook = nullptr;
Show("io_pgetevents_slices_keep_mask", MaskedSliced && MaskedResult == 1 && AioReapArgs[0] == SYS_io_pgetevents &&
AioReapArgs[6] == reinterpret_cast<uint64_t>(MaskWords) && SealedEvents[0].Data == 0x53);
int64_t BadWait[2] = {0, 2000000000};
ArgumentStorage Unsliced;
uint64_t UnslicedArgs[6] = {Woken, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), reinterpret_cast<uint64_t>(BadWait), 0};
Call(Sys::SYSCALL_x64_io_getevents, UnslicedArgs, &Unsliced);
const int ReapsUnsliced = AioReaps;
Show("io_getevents_odd_timeout_native", !Unsliced.Blocking && UnslicedArgs[1] == 1 && UnslicedArgs[4] == reinterpret_cast<uint64_t>(BadWait) &&
FinishSyscallArguments(0, &Unsliced) == 0 && AioReaps == ReapsUnsliced);
uint64_t* Published = static_cast<uint64_t*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
uint32_t LostRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
*Published = reinterpret_cast<uint64_t>(LostRing);
ArgumentStorage Unpublished;
uint64_t UnpublishedArgs[6] = {128, reinterpret_cast<uint64_t>(Published), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, UnpublishedArgs, &Unpublished);
mprotect(Published, Page, PROT_READ);
Show("io_setup_unpublished_result", FinishSyscallArguments(0, &Unpublished));
Show("io_setup_unpublished_destroyed", AioDestroyed == reinterpret_cast<uint64_t>(LostRing) &&
AioContextsLocked().count(reinterpret_cast<uint64_t>(LostRing)) == 0);
mprotect(Published, Page, PROT_READ | PROT_WRITE);
uint32_t ReusedRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
const uint64_t Reused = reinterpret_cast<uint64_t>(ReusedRing);
*Published = Reused;
uint64_t ReusedGeneration = 0;
AioDestroyHook = [&](uint64_t Ring) { ReusedGeneration = BeginContext(Ring); };
ArgumentStorage ReusedSetup;
uint64_t ReusedSetupArgs[6] = {128, reinterpret_cast<uint64_t>(Published), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, ReusedSetupArgs, &ReusedSetup);
mprotect(Published, Page, PROT_READ);
const auto ReusedResult = FinishSyscallArguments(0, &ReusedSetup);
AioDestroyHook = nullptr;
Show("io_setup_rollback_keeps_reused_context", ReusedResult == static_cast<uint64_t>(-EFAULT) && ReusedGeneration != 0 &&
AioContextsLocked().count(Reused) == 1 && AioContextsLocked()[Reused].Generation == ReusedGeneration);
ReleaseContext(Reused, ReusedGeneration);
mprotect(Published, Page, PROT_NONE);
ArgumentStorage UnreadableSetup;
uint64_t UnreadableArgs[6] = {128, reinterpret_cast<uint64_t>(Published), 0, 0, 0, 0};
Show("io_setup_unreadable_output_faults", Call(Sys::SYSCALL_x64_io_setup, UnreadableArgs, &UnreadableSetup) == static_cast<uint64_t>(-EFAULT) &&
UnreadableArgs[1] == reinterpret_cast<uint64_t>(Published) && UnreadableSetup.SetupContext == 0 &&
FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &UnreadableSetup) == static_cast<uint64_t>(-EFAULT));
munmap(Published, Page);
ArgumentStorage BogusReap;
uint64_t BogusReapArgs[6] = {0x5bad, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, BogusReapArgs, &BogusReap);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &BogusReap);
Show("io_getevents_invalid_context_forgotten", AioContextsLocked().count(0x5bad));
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage Pending;
uint64_t PendingArgs[6] = {33, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, PendingArgs, &Pending);
ArgumentStorage Rejected;
uint64_t RejectedArgs[6] = {33, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_pgetevents, RejectedArgs, &Rejected);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &Rejected);
mprotect(SealedEvents, Page, PROT_READ);
const TestEvent PendingEvent {0x4a, reinterpret_cast<uint64_t>(&KeyB), 1, 0};
Deliver(PendingArgs, &PendingEvent, sizeof(PendingEvent));
FinishSyscallArguments(1, &Pending);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage PendingRetry;
uint64_t PendingRetryArgs[6] = {33, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, PendingRetryArgs, &PendingRetry);
Show("io_getevents_rejected_sibling_kept", FinishSyscallArguments(0, &PendingRetry) == 1 && SealedEvents[0].Data == 0x4a);
FailReap(10, {0x33, reinterpret_cast<uint64_t>(&KeyC), 1, 0});
ArgumentStorage StashDestroy;
uint64_t StashDestroyArgs[6] = {10, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, StashDestroyArgs, &StashDestroy);
FinishSyscallArguments(0, &StashDestroy);
ArgumentStorage DestroyedReap;
uint64_t DestroyedReapArgs[6] = {10, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), Immediate, 0};
Call(Sys::SYSCALL_x64_io_getevents, DestroyedReapArgs, &DestroyedReap);
Show("io_getevents_stash_destroyed", DestroyedReapArgs[2] == 1 && FinishSyscallArguments(0, &DestroyedReap) == 0);
ArgumentStorage TripleFailed;
uint64_t TripleFailedArgs[6] = {4, 3, 3, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, TripleFailedArgs, &TripleFailed);
mprotect(SealedEvents, Page, PROT_READ);
const TestEvent Triple[3] = {{0x31, reinterpret_cast<uint64_t>(&KeyA), 1, 0}, {0x32, reinterpret_cast<uint64_t>(&KeyB), 1, 0},
{0x33, reinterpret_cast<uint64_t>(&KeyC), 1, 0}};
Deliver(TripleFailedArgs, Triple, sizeof(Triple));
Show("io_getevents_stash_triple_failed", FinishSyscallArguments(3, &TripleFailed));
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage SealedRetry;
uint64_t SealedRetryArgs[6] = {4, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, SealedRetryArgs, &SealedRetry);
mprotect(SealedEvents, Page, PROT_READ);
Show("io_getevents_stash_retry_failed", FinishSyscallArguments(0, &SealedRetry));
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage OrderedReap;
uint64_t OrderedReapArgs[6] = {4, 3, 3, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, OrderedReapArgs, &OrderedReap);
Show("io_getevents_stash_ordered_result", FinishSyscallArguments(0, &OrderedReap));
Show("io_getevents_stash_ordered", SealedEvents[0].Data == 0x31 && SealedEvents[1].Data == 0x32 && SealedEvents[2].Data == 0x33 &&
SealedEvents[2].Object == reinterpret_cast<uint64_t>(&KeyC));
static TestEvent ManyEvents[100];
for (uint64_t i = 0; i < 100; ++i) {
ManyEvents[i] = {0x1000 + i, reinterpret_cast<uint64_t>(&KeyA), 1, 0};
}
ArgumentStorage ManyFailed;
uint64_t ManyFailedArgs[6] = {4, 100, 100, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ManyFailedArgs, &ManyFailed);
mprotect(SealedEvents, Page, PROT_READ);
Deliver(ManyFailedArgs, ManyEvents, sizeof(ManyEvents));
Show("io_getevents_stash_many_failed", FinishSyscallArguments(100, &ManyFailed));
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
ArgumentStorage ManyRetry;
uint64_t ManyRetryArgs[6] = {4, 100, 100, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ManyRetryArgs, &ManyRetry);
bool ManyOrdered = FinishSyscallArguments(0, &ManyRetry) == 100;
for (uint64_t i = 0; i < 100; ++i) {
ManyOrdered = ManyOrdered && SealedEvents[i].Data == 0x1000 + i;
}
Show("io_getevents_stash_many_kept", ManyOrdered);
for (uint64_t Context = 100; Context < 120; ++Context) {
FailReap(Context, {Context, reinterpret_cast<uint64_t>(&KeyA), 1, 0});
}
bool EveryContext = true;
for (uint64_t Context = 100; Context < 120; ++Context) {
ArgumentStorage ContextRetry;
uint64_t ContextRetryArgs[6] = {Context, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, ContextRetryArgs, &ContextRetry);
EveryContext = EveryContext && FinishSyscallArguments(0, &ContextRetry) == 1 && SealedEvents[0].Data == Context;
}
Show("io_getevents_stash_every_context", EveryContext);
TestIocb DirectBlock = ReadBlock;
uint64_t DirectList[1] = {reinterpret_cast<uint64_t>(&DirectBlock)};
auto SubmitDirect = [&] {
ArgumentStorage DirectSubmit;
uint64_t DirectSubmitArgs[6] = {11, 1, reinterpret_cast<uint64_t>(DirectList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, DirectSubmitArgs, &DirectSubmit);
const auto Sent = reinterpret_cast<const uint64_t*>(DirectSubmitArgs[2])[0];
FinishSyscallArguments(1, &DirectSubmit);
return Sent;
};
const auto DirectBefore = IoCopyCount.load();
const auto DirectSent = SubmitDirect();
mprotect(SealedEvents, Page, PROT_READ);
ArgumentStorage DirectReap;
uint64_t DirectReapArgs[6] = {11, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, DirectReapArgs, &DirectReap);
Show("io_getevents_unwritable_first_staged", DirectReapArgs[3] == reinterpret_cast<uint64_t>(DirectReap.EventBuffer.data()) && DirectReapArgs[2] == 1);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
const TestEvent DirectEvent {0x21, DirectSent, 64, 0};
Deliver(DirectReapArgs, &DirectEvent, sizeof(DirectEvent));
Show("io_getevents_late_writable_result", FinishSyscallArguments(1, &DirectReap));
Show("io_getevents_late_writable_object", SealedEvents[0].Object == reinterpret_cast<uint64_t>(&DirectBlock));
Show("io_getevents_late_writable_released", IoCopyCount.load() - DirectBefore);
const auto HiddenSent = SubmitDirect();
SealedEvents[0] = {};
mprotect(SealedEvents, Page, PROT_READ);
ArgumentStorage HiddenReap;
uint64_t HiddenReapArgs[6] = {11, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, HiddenReapArgs, &HiddenReap);
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
const TestEvent HiddenEvent {0x22, HiddenSent, 64, 0};
Deliver(HiddenReapArgs, &HiddenEvent, sizeof(HiddenEvent));
mprotect(SealedEvents, Page, PROT_NONE);
Show("io_getevents_hidden_result", FinishSyscallArguments(1, &HiddenReap));
mprotect(SealedEvents, Page, PROT_READ | PROT_WRITE);
Show("io_getevents_hidden_no_private", SealedEvents[0].Object == 0);
Show("io_getevents_hidden_released", IoCopyCount.load() - DirectBefore);
ArgumentStorage HiddenRetry;
uint64_t HiddenRetryArgs[6] = {11, 1, 1, reinterpret_cast<uint64_t>(SealedEvents), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, HiddenRetryArgs, &HiddenRetry);
Show("io_getevents_hidden_retry", FinishSyscallArguments(0, &HiddenRetry) == 1 && SealedEvents[0].Data == 0x22 &&
SealedEvents[0].Object == reinterpret_cast<uint64_t>(&DirectBlock));
ArgumentStorage DirectDestroy;
uint64_t DirectDestroyArgs[6] = {11, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, DirectDestroyArgs, &DirectDestroy);
FinishSyscallArguments(0, &DirectDestroy);
munmap(SealedEvents, Page);
munmap(SealedEvents, Page);
ArgumentStorage WrappedReap;
uint64_t WrappedReapArgs[6] = {4, 1, 1024, 0xFFFF'FFFF'FFFF'F000ULL, 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, WrappedReapArgs, &WrappedReap);
Show("io_getevents_wrapped_staged", WrappedReapArgs[3] == reinterpret_cast<uint64_t>(WrappedReap.EventBuffer.data()) && WrappedReapArgs[2] == 1 &&
WrappedReap.EventBuffer.size() == sizeof(TestEvent) / sizeof(uint64_t));
Show("io_getevents_wrapped_result", FinishSyscallArguments(static_cast<uint64_t>(-EFAULT), &WrappedReap));
auto* EdgeEvents = static_cast<char*>(mmap(nullptr, 2 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
mprotect(EdgeEvents + Page, Page, PROT_READ);
ArgumentStorage EdgeReap;
uint64_t EdgeReapArgs[6] = {4, 3, 4, reinterpret_cast<uint64_t>(EdgeEvents + Page - 2 * sizeof(TestEvent)), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, EdgeReapArgs, &EdgeReap);
Show("io_getevents_writable_prefix", EdgeReapArgs[2]);
Show("io_getevents_writable_min", EdgeReapArgs[1]);
Show("io_getevents_writable_buffer", EdgeReap.EventBuffer.size() * sizeof(uint64_t) / sizeof(TestEvent));
munmap(EdgeEvents, 2 * Page);
uint32_t Ring[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
uint64_t RingContext = reinterpret_cast<uint64_t>(Ring);
ArgumentStorage Setup;
uint64_t SetupArgs[6] = {128, reinterpret_cast<uint64_t>(&RingContext), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, SetupArgs, &Setup);
FinishSyscallArguments(0, &Setup);
Show("io_setup_magic", Ring[4]);
Show("io_setup_header_kept", Ring[0] == 0 && Ring[1] == 128 && Ring[2] == 0 && Ring[3] == 0 && Ring[5] == 1 && Ring[6] == 0 && Ring[7] == 32);
uint32_t KeptRing[8] = {0, 128, 0, 0, 0xa10a10a1, 1, 0, 32};
uint64_t KeptContext = reinterpret_cast<uint64_t>(KeptRing);
ArgumentStorage FailedSetup;
uint64_t FailedSetupArgs[6] = {128, reinterpret_cast<uint64_t>(&KeptContext), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, FailedSetupArgs, &FailedSetup);
FinishSyscallArguments(static_cast<uint64_t>(-EINVAL), &FailedSetup);
Show("io_setup_failed_magic", KeptRing[4]);
TestEvent Completions[2] = {{7, Base + 1536, 16, 0}, {8, Base + 1536, 16, 0}};
ArgumentStorage Reap;
uint64_t ReapArgs[6] = {1, 1, 2, reinterpret_cast<uint64_t>(Completions), 0, 0};
Show("io_getevents_result", Call(Sys::SYSCALL_x64_io_getevents, ReapArgs, &Reap));
Deliver(ReapArgs, Completions, sizeof(Completions));
FinishSyscallArguments(1, &Reap);
Show("io_getevents_object", Completions[0].Object - Single);
Show("io_getevents_unreported", Completions[1].Object - Base);
uint64_t Pages[2] = {Single + 16, Low};
int PageStatus[2] = {};
ArgumentStorage Move;
uint64_t MoveArgs[6] = {0, 2, reinterpret_cast<uint64_t>(Pages), 0, reinterpret_cast<uint64_t>(PageStatus), 0};
Show("move_pages_result", Call(Sys::SYSCALL_x64_move_pages, MoveArgs, &Move));
Show("move_pages_copied", MoveArgs[2] != reinterpret_cast<uint64_t>(Pages));
Show("move_pages_first", reinterpret_cast<const uint64_t*>(MoveArgs[2])[0] - Base);
Show("move_pages_second", reinterpret_cast<const uint64_t*>(MoveArgs[2])[1] == Low);
Show("move_pages_guest_list", Pages[0] - Single);
ArgumentStorage Remote;
uint64_t RemoteArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Pages), 0, reinterpret_cast<uint64_t>(PageStatus), 0};
Show("move_pages_remote_result", Call(Sys::SYSCALL_x64_move_pages, RemoteArgs, &Remote));
Show("move_pages_remote_kept", RemoteArgs[2] == reinterpret_cast<uint64_t>(Pages));
uint32_t LowWord = 0;
uint64_t Waiters[2][3] = {{0, Single + 64, 2}, {0, reinterpret_cast<uint64_t>(&LowWord), 2}};
ArgumentStorage Wait;
uint64_t WaitArgs[6] = {reinterpret_cast<uint64_t>(Waiters), 2, 0, 0, 1, 0};
Show("futex_waitv_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitArgs, &Wait));
Show("futex_waitv_copied", WaitArgs[0] != reinterpret_cast<uint64_t>(Waiters));
Show("futex_waitv_first", reinterpret_cast<const uint64_t*>(WaitArgs[0])[1] - Base);
Show("futex_waitv_second", reinterpret_cast<const uint64_t*>(WaitArgs[0])[4] == reinterpret_cast<uint64_t>(&LowWord));
Show("futex_waitv_guest", Waiters[0][1] - Single);
uint64_t Straddling[1][3] = {{0, Split + Page - 2, 2}};
ArgumentStorage WaitBad;
uint64_t WaitBadArgs[6] = {reinterpret_cast<uint64_t>(Straddling), 1, 0, 0, 1, 0};
Show("futex_waitv_split_result", Call(Sys::SYSCALL_x64_futex_waitv, WaitBadArgs, &WaitBad));
uint64_t Requeue[2][3] = {{0, Single + 64, 2}, {0, Single + 128, 2}};
ArgumentStorage RequeueStorage;
uint64_t RequeueArgs[6] = {reinterpret_cast<uint64_t>(Requeue), 0, 1, 1, 0, 0};
Show("futex_requeue_result", Call(Sys::SYSCALL_x64_futex_requeue, RequeueArgs, &RequeueStorage));
Show("futex_requeue_second", reinterpret_cast<const uint64_t*>(RequeueArgs[0])[4] - Base);
const uint64_t Mapped = 0x780000000000ULL;
const int Anonymous = MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED;
Show("map_result", Map(Mapped, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped);
const uint32_t MappedEntries = Count.load();
Show("map_unmap", Unmap(Mapped + Page, Page));
Show("map_again", Map(Mapped + Page, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0) - Mapped);
FindLocked(Mapped, &Part);
Show("map_merged_size", Part.Size);
Show("map_merged_entries", Count.load() - MappedEntries);
Show("map_unmap_again", Unmap(Mapped + Page, Page));
Show("map_readonly", Map(Mapped + Page, Page, PROT_READ, Anonymous, -1, 0) - Mapped);
FindLocked(Mapped, &Part);
Show("map_readonly_size", Part.Size);
Show("map_readonly_entries", Count.load() - MappedEntries);
auto* Order = static_cast<uint8_t*>(mmap(nullptr, 5 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t OrderHost = reinterpret_cast<uint64_t>(Order);
const uint64_t Ordered = 0x770000000000ULL;
const uint32_t OrderEntries = Count.load();
AddEntry(Ordered + Page, Page, OrderHost + Page, false, PROT_READ);
AddEntry(Ordered + 3 * Page, Page, OrderHost + 4 * Page, false, PROT_READ);
AddEntry(Ordered, Page, OrderHost, false, PROT_READ);
AddEntry(Ordered + 2 * Page, Page, OrderHost + 3 * Page, false, PROT_READ);
Show("slot_order_restore", Protect(Ordered, 4 * Page, PROT_READ | PROT_WRITE));
Show("slot_order_entries", Count.load() - OrderEntries);
FindLocked(Ordered + 2 * Page, &Part);
Show("slot_order_second_size", Part.Size);
ArgumentStorage Widths;
uint64_t GroupsWide[6] = {(1ULL << 32) + 1, Single + Page - 4, 0, 0, 0, 0};
Show("getgroups_wide_result", Call(Sys::SYSCALL_x64_getgroups, GroupsWide, &Widths));
Show("getgroups_wide_list", GroupsWide[1] - Base);
uint64_t GroupsNegative[6] = {0xffffffffULL, Single + Page - 4, 0, 0, 0, 0};
Show("getgroups_negative_result", Call(Sys::SYSCALL_x64_getgroups, GroupsNegative, &Widths));
uint64_t GroupsLarge[6] = {(1ULL << 32) + 2, Single + Page - 4, 0, 0, 0, 0};
Show("getgroups_large_result", Call(Sys::SYSCALL_x64_getgroups, GroupsLarge, &Widths));
uint64_t PollWide[6] = {Single + Page - 8, (1ULL << 32) + 1, 0, 0, 0, 0};
Show("poll_wide_result", Call(Sys::SYSCALL_x64_poll, PollWide, &Widths));
uint64_t EpollNegative[6] = {3, Single + Page - 12, 0xffffffffULL, 0, 0, 0};
Show("epoll_negative_result", Call(Sys::SYSCALL_x64_epoll_wait, EpollNegative, &Widths));
ArgumentStorage NegativeReap;
uint64_t EventsNegative[6] = {1, 1, static_cast<uint64_t>(-1), Single, 0, 0};
Show("io_getevents_negative_result", Call(Sys::SYSCALL_x64_io_getevents, EventsNegative, &NegativeReap));
struct iovec PrefixVectors[2] = {{reinterpret_cast<void*>(Single + 256), 32}, {reinterpret_cast<void*>(Split + Page - 8), 16}};
struct mmsghdr Prefix[2] {};
Prefix[0].msg_hdr.msg_iov = &PrefixVectors[0];
Prefix[0].msg_hdr.msg_iovlen = 1;
Prefix[1].msg_hdr.msg_iov = &PrefixVectors[1];
Prefix[1].msg_hdr.msg_iovlen = 1;
ArgumentStorage PrefixBatch;
uint64_t PrefixArgs[6] = {3, reinterpret_cast<uint64_t>(Prefix), 2, 0, 0, 0};
Show("sendmmsg_prefix_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixArgs, &PrefixBatch));
Show("sendmmsg_prefix_count", PrefixArgs[2]);
ArgumentStorage PrefixBad;
uint64_t PrefixBadArgs[6] = {3, reinterpret_cast<uint64_t>(&Prefix[1]), 1, 0, 0, 0};
Show("sendmmsg_first_bad_result", Call(Sys::SYSCALL_x64_sendmmsg, PrefixBadArgs, &PrefixBad));
auto* ApartFirst = reinterpret_cast<struct mmsghdr*>(Backing + 3 * Page - sizeof(struct mmsghdr));
auto* ApartSecond = reinterpret_cast<struct mmsghdr*>(Backing + 4 * Page);
char ApartLow[32];
struct iovec ApartVectors[2] = {{ApartLow, 11}, {ApartLow, 22}};
*ApartFirst = {};
ApartFirst->msg_hdr.msg_iov = &ApartVectors[0];
ApartFirst->msg_hdr.msg_iovlen = 1;
*ApartSecond = {};
ApartSecond->msg_hdr.msg_iov = &ApartVectors[1];
ApartSecond->msg_hdr.msg_iovlen = 1;
ArgumentStorage ApartBatch;
uint64_t HeadersApart[6] = {static_cast<uint64_t>(Peer), Split + Page - sizeof(struct mmsghdr), 2, 0, 0, 0};
Show("sendmmsg_headers_apart_result", Call(Sys::SYSCALL_x64_sendmmsg, HeadersApart, &ApartBatch));
Show("sendmmsg_headers_apart_count", HeadersApart[2]);
auto* ApartHost = reinterpret_cast<struct mmsghdr*>(HeadersApart[1]);
Show("sendmmsg_headers_apart_first", ApartHost[0].msg_hdr.msg_iov[0].iov_len);
Show("sendmmsg_headers_apart_second", ApartHost[1].msg_hdr.msg_iov[0].iov_len);
SendCalls = 0;
ApartHost[0].msg_len = 11;
Show("sendmmsg_headers_apart_finish", FinishResult(1, &ApartBatch));
Show("sendmmsg_headers_apart_sent", SentLengths[0]);
Show("sendmmsg_headers_apart_lengths", ApartFirst->msg_len * 0x100 + ApartSecond->msg_len);
struct iovec MovingVector = {reinterpret_cast<void*>(Single + 256), 32};
const uint64_t Moving = 0x760000000000ULL;
Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t OldHost {};
TranslateRange(Moving, Page, &OldHost);
auto* MovingHeaders = reinterpret_cast<struct mmsghdr*>(OldHost);
MovingHeaders[0] = {};
MovingHeaders[0].msg_hdr.msg_iov = &MovingVector;
MovingHeaders[0].msg_hdr.msg_iovlen = 1;
ArgumentStorage MovingBatch;
uint64_t MovingArgs[6] = {3, Moving, 1, 0, 0, 0};
Show("moved_result", Call(Sys::SYSCALL_x64_sendmmsg, MovingArgs, &MovingBatch));
reinterpret_cast<struct mmsghdr*>(MovingArgs[1])[0].msg_len = 32;
Unmap(Moving, Page);
auto* Unrelated = static_cast<struct mmsghdr*>(mmap(reinterpret_cast<void*>(OldHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0));
Map(Moving, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t NewHost {};
TranslateRange(Moving, Page, &NewHost);
Show("moved_finish", FinishResult(1, &MovingBatch));
Show("moved_unrelated_placed", reinterpret_cast<uint64_t>(Unrelated) == OldHost && NewHost != OldHost);
Show("moved_unrelated_length", Unrelated[0].msg_len);
Show("moved_new_length", reinterpret_cast<struct mmsghdr*>(NewHost)[0].msg_len);
const uint64_t Sealed = 0x750000000000ULL;
Map(Sealed, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t SealedHost {};
TranslateRange(Sealed, 2 * Page, &SealedHost);
auto* SealedHeaders = reinterpret_cast<struct mmsghdr*>(SealedHost + Page - sizeof(struct mmsghdr));
for (int i = 0; i < 3; ++i) {
SealedHeaders[i] = {};
SealedHeaders[i].msg_hdr.msg_iov = &MovingVector;
SealedHeaders[i].msg_hdr.msg_iovlen = 1;
}
Protect(Sealed + Page, Page, PROT_READ);
ArgumentStorage SealedBatch;
uint64_t SealedArgs[6] = {static_cast<uint64_t>(Peer), Sealed + Page - sizeof(struct mmsghdr), 3, 0, 0, 0};
Show("sealed_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedArgs, &SealedBatch));
Show("sealed_submitted", SealedArgs[2]);
auto* SealedCopy = reinterpret_cast<struct mmsghdr*>(SealedArgs[1]);
SealedCopy[0].msg_len = 32;
SendCalls = 0;
Show("sealed_finish", FinishResult(1, &SealedBatch));
Show("sealed_later_sends", SendCalls);
Show("sealed_first_length", SealedHeaders[0].msg_len);
Show("sealed_second_length", SealedHeaders[1].msg_len);
Show("sealed_third_length", SealedHeaders[2].msg_len);
ArgumentStorage SealedOnly;
uint64_t SealedOnlyArgs[6] = {3, Sealed + Page, 1, 0, 0, 0};
Show("sealed_only_result", Call(Sys::SYSCALL_x64_sendmmsg, SealedOnlyArgs, &SealedOnly));
reinterpret_cast<struct mmsghdr*>(SealedOnlyArgs[1])[0].msg_len = 32;
Show("sealed_only_finish", FinishResult(1, &SealedOnly));
ArgumentStorage Embedded;
uint8_t* SplitEnd = Backing + 3 * Page;
const uint32_t Sizes32[] = {64, 0, 72};
const char* PerfNames[] = {"perf_attr_fits_result", "perf_attr_default_result", "perf_attr_large_result"};
for (int i = 0; i < 3; ++i) {
std::memcpy(SplitEnd - 64 + 4, &Sizes32[i], 4);
uint64_t PerfArgs[6] = {Split + Page - 64, 0, static_cast<uint64_t>(-1), static_cast<uint64_t>(-1), 0, 0};
Show(PerfNames[i], Call(Sys::SYSCALL_x64_perf_event_open, PerfArgs, &Embedded));
}
const uint32_t SchedSizes[] = {48, 56};
const char* SchedNames[] = {"sched_attr_fits_result", "sched_attr_large_result"};
for (int i = 0; i < 2; ++i) {
std::memcpy(SplitEnd - 48, &SchedSizes[i], 4);
uint64_t SchedArgs[6] = {0, Split + Page - 48, 0, 0, 0, 0};
Show(SchedNames[i], Call(Sys::SYSCALL_x64_sched_setattr, SchedArgs, &Embedded));
}
const uint32_t CapHeader1[2] = {0x19980330, 0};
const uint32_t CapHeader3[2] = {0x20080522, 0};
uint64_t CapV1[6] = {reinterpret_cast<uint64_t>(CapHeader1), Split + Page - 12, 0, 0, 0, 0};
Show("capget_v1_result", Call(Sys::SYSCALL_x64_capget, CapV1, &Embedded));
Show("capget_v1_data", CapV1[1] - Base);
uint64_t CapV3[6] = {reinterpret_cast<uint64_t>(CapHeader3), Split + Page - 12, 0, 0, 0, 0};
Show("capget_v3_result", Call(Sys::SYSCALL_x64_capget, CapV3, &Embedded));
uint64_t CapSetV3[6] = {reinterpret_cast<uint64_t>(CapHeader3), Split + Page - 12, 0, 0, 0, 0};
Show("capset_v3_result", Call(Sys::SYSCALL_x64_capset, CapSetV3, &Embedded));
uint32_t CapGuest[2] = {0x19980330, 0};
ArgumentStorage CapCopy;
uint64_t CapCopyArgs[6] = {reinterpret_cast<uint64_t>(CapGuest), Split + Page - 12, 0, 0, 0, 0};
Show("capget_copy_result", Call(Sys::SYSCALL_x64_capget, CapCopyArgs, &CapCopy));
Show("capget_copy_private", CapCopyArgs[0] != reinterpret_cast<uint64_t>(CapGuest));
CapGuest[0] = 0x20080522;
Show("capget_copy_version", reinterpret_cast<const uint32_t*>(CapCopyArgs[0])[0]);
Show("capget_copy_finish", FinishResult(0, &CapCopy));
Show("capget_copy_guest_version", CapGuest[0]);
uint32_t CapUnknown[2] = {0x1234, 0};
ArgumentStorage CapInvalid;
uint64_t CapInvalidArgs[6] = {reinterpret_cast<uint64_t>(CapUnknown), Single + 64, 0, 0, 0, 0};
Show("capget_invalid_result", Call(Sys::SYSCALL_x64_capget, CapInvalidArgs, &CapInvalid));
reinterpret_cast<uint32_t*>(CapInvalidArgs[0])[0] = 0x20080522;
Show("capget_invalid_finish", FinishResult(static_cast<uint64_t>(-EINVAL), &CapInvalid));
Show("capget_invalid_version", CapUnknown[0]);
const uint32_t HandleBytes[] = {8, 16};
const char* HandleNames[] = {"name_to_handle_fits_result", "name_to_handle_large_result"};
const char* OpenNames[] = {"open_by_handle_fits_result", "open_by_handle_large_result"};
int MountId = 0;
for (int i = 0; i < 2; ++i) {
std::memcpy(SplitEnd - 16, &HandleBytes[i], 4);
uint64_t HandleArgs[6] = {static_cast<uint64_t>(AT_FDCWD), reinterpret_cast<uint64_t>("x"), Split + Page - 16, reinterpret_cast<uint64_t>(&MountId), 0, 0};
Show(HandleNames[i], Call(Sys::SYSCALL_x64_name_to_handle_at, HandleArgs, &Embedded));
uint64_t OpenArgs[6] = {3, Split + Page - 16, 0, 0, 0, 0};
Show(OpenNames[i], Call(Sys::SYSCALL_x64_open_by_handle_at, OpenArgs, &Embedded));
}
const uint32_t OversizedHandle = 1000;
std::memcpy(SplitEnd - 4, &OversizedHandle, 4);
uint64_t HandleHeaderSplit[6] = {static_cast<uint64_t>(AT_FDCWD), reinterpret_cast<uint64_t>("x"), Split + Page - 4, reinterpret_cast<uint64_t>(&MountId), 0, 0};
Show("name_to_handle_header_split_result", Call(Sys::SYSCALL_x64_name_to_handle_at, HandleHeaderSplit, &Embedded));
uint64_t OpenHeaderSplit[6] = {3, Split + Page - 4, 0, 0, 0, 0};
Show("open_by_handle_header_split_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderSplit, &Embedded));
std::memcpy(SplitEnd - 8, &OversizedHandle, 4);
uint64_t OpenHeaderFits[6] = {3, Split + Page - 8, 0, 0, 0, 0};
Show("open_by_handle_header_fits_result", Call(Sys::SYSCALL_x64_open_by_handle_at, OpenHeaderFits, &Embedded));
const uint32_t RequestSizes[] = {24, 32};
const char* RequestNames[] = {"statmount_fits_result", "statmount_large_result"};
for (int i = 0; i < 2; ++i) {
std::memcpy(SplitEnd - 24, &RequestSizes[i], 4);
uint64_t RequestArgs[6] = {Split + Page - 24, 0, 0, 0, 0, 0};
Show(RequestNames[i], Call(Sys::SYSCALL_x64_statmount, RequestArgs, &Embedded));
}
uint64_t PathRule[6] = {3, 1, Split + Page - 12, 0, 0, 0};
Show("landlock_path_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PathRule, &Embedded));
uint64_t PortRule[6] = {3, 2, Split + Page - 12, 0, 0, 0};
Show("landlock_port_result", Call(Sys::SYSCALL_x64_landlock_add_rule, PortRule, &Embedded));
const uint64_t Nameless = 0x740000000000ULL;
Map(Nameless, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t NamelessHost {};
TranslateRange(Nameless, 2 * Page, &NamelessHost);
const uint64_t NamelessGuestHeader = Nameless + Page - 16;
auto* NamelessHeader = reinterpret_cast<struct msghdr*>(NamelessHost + Page - 16);
struct iovec NamelessVector = {reinterpret_cast<void*>(Single + 128), 64};
*NamelessHeader = {};
NamelessHeader->msg_iov = &NamelessVector;
NamelessHeader->msg_iovlen = 1;
Protect(Nameless, Page, PROT_READ);
ArgumentStorage NamelessReceive;
uint64_t NamelessArgs[6] = {3, NamelessGuestHeader, 0, 0, 0, 0};
Show("recvmsg_nameless_result", Call(Sys::SYSCALL_x64_recvmsg, NamelessArgs, &NamelessReceive));
NamelessReceive.Message.msg_flags = MSG_TRUNC;
Show("recvmsg_nameless_finish", FinishResult(64, &NamelessReceive));
Show("recvmsg_nameless_flags", NamelessHeader->msg_flags);
char NameBuffer[16];
const uint64_t Named = 0x700000000000ULL;
Map(Named, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t NamedHost {};
TranslateRange(Named, 2 * Page, &NamedHost);
auto* NamedHeader = reinterpret_cast<struct msghdr*>(NamedHost + Page - 16);
*NamedHeader = {};
NamedHeader->msg_name = NameBuffer;
NamedHeader->msg_namelen = sizeof(NameBuffer);
NamedHeader->msg_iov = &NamelessVector;
NamedHeader->msg_iovlen = 1;
Protect(Named, Page, PROT_READ);
ArgumentStorage NamedReceive;
uint64_t NamedArgs[6] = {3, Named + Page - 16, 0, 0, 0, 0};
Show("recvmsg_named_result", Call(Sys::SYSCALL_x64_recvmsg, NamedArgs, &NamedReceive));
Show("recvmsg_named_private", NamedArgs[1] != NamedHost + Page - 16);
Show("recvmsg_named_name_kept", reinterpret_cast<const struct msghdr*>(NamedArgs[1])->msg_name == NameBuffer);
Show("recvmsg_named_finish", FinishResult(64, &NamedReceive));
const uint64_t Flagged = 0x730000000000ULL;
Map(Flagged, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t FlaggedHost {};
TranslateRange(Flagged, 2 * Page, &FlaggedHost);
auto* FlaggedHeader = reinterpret_cast<struct msghdr*>(FlaggedHost + Page - offsetof(struct msghdr, msg_flags));
*FlaggedHeader = {};
FlaggedHeader->msg_iov = &NamelessVector;
FlaggedHeader->msg_iovlen = 1;
FlaggedHeader->msg_controllen = 99;
Protect(Flagged + Page, Page, PROT_READ);
ArgumentStorage FlaggedReceive;
uint64_t FlaggedArgs[6] = {3, Flagged + Page - offsetof(struct msghdr, msg_flags), 0, 0, 0, 0};
Show("recvmsg_flags_first_result", Call(Sys::SYSCALL_x64_recvmsg, FlaggedArgs, &FlaggedReceive));
FlaggedReceive.Message.msg_controllen = 0;
Show("recvmsg_flags_first_finish", FinishResult(64, &FlaggedReceive));
Show("recvmsg_flags_first_controllen", FlaggedHeader->msg_controllen);
const uint64_t Blocks = 0x720000000000ULL;
Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t BlocksHost {};
TranslateRange(Blocks, Page, &BlocksHost);
auto* HighIocb = reinterpret_cast<TestIocb*>(BlocksHost);
*HighIocb = {};
HighIocb->Data = 0x99;
HighIocb->Opcode = 7;
HighIocb->Buffer = reinterpret_cast<uint64_t>(Scatter);
HighIocb->Bytes = 2;
const TestIocb HighExpected = *HighIocb;
uint64_t HighIocbList[1] = {Blocks};
ArgumentStorage HighCopy;
uint64_t HighCopyArgs[6] = {1, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Show("io_submit_high_copy_result", Call(Sys::SYSCALL_x64_io_submit, HighCopyArgs, &HighCopy));
const uint64_t HighSent = reinterpret_cast<const uint64_t*>(HighCopyArgs[2])[0];
Show("io_submit_high_copy_private", HighSent != BlocksHost && FindIoCopyLocked(HighSent) != nullptr);
Show("io_submit_high_copy_vector", reinterpret_cast<const struct iovec*>(reinterpret_cast<const TestIocb*>(HighSent)->Buffer)[0].iov_base == reinterpret_cast<void*>(Base + 800));
Show("io_submit_high_copy_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0);
ArgumentStorage HighCancel;
uint64_t HighCancelArgs[6] = {1, Blocks, reinterpret_cast<uint64_t>(&CancelEvent), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, HighCancelArgs, &HighCancel);
Show("io_cancel_high_private", HighCancelArgs[1] == HighSent);
Show("io_submit_high_copy_hidden", Protect(Blocks, Page, PROT_NONE));
uint64_t SealedProbe = 0;
auto HiddenRead = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyFromUser(&SealedProbe, &HighIocb->Buffer, sizeof(SealedProbe)) != 0; };
auto HiddenWrite = [&] { return FEX::HLE::FaultSafeUserMemAccess::CopyToUser(&HighIocb->Buffer, &SealedProbe, sizeof(SealedProbe)) != 0; };
ProtectCalls = 0;
FinishSyscallArguments(1, &HighCopy);
Show("io_submit_high_copy_sealed", HiddenRead() && HiddenWrite());
ArgumentStorage HiddenCancel;
uint64_t HiddenCancelArgs[6] = {1, Blocks, reinterpret_cast<uint64_t>(&CancelEvent), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, HiddenCancelArgs, &HiddenCancel);
Show("io_cancel_hidden_native", HiddenCancelArgs[1] == BlocksHost);
TestEvent HighReaped[1] = {{0x99, HighSent, 16, 0}};
ArgumentStorage HighReap;
uint64_t HighReapArgs[6] = {1, 1, 1, reinterpret_cast<uint64_t>(HighReaped), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, HighReapArgs, &HighReap);
Deliver(HighReapArgs, HighReaped, sizeof(HighReaped));
FinishSyscallArguments(1, &HighReap);
Show("io_getevents_high_object", HighReaped[0].Object - Blocks);
Show("io_getevents_high_sealed", HiddenRead() && HiddenWrite());
Show("io_getevents_high_protect_calls", ProtectCalls);
Show("io_getevents_high_freed", IoCopyCount.load() - CopiesBefore);
Protect(Blocks, Page, PROT_READ | PROT_WRITE);
Show("io_getevents_high_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0);
Protect(Blocks, Page, PROT_READ);
ArgumentStorage SealedSubmit;
uint64_t SealedSubmitArgs[6] = {1, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Show("io_submit_read_only_result", Call(Sys::SYSCALL_x64_io_submit, SealedSubmitArgs, &SealedSubmit));
Show("io_submit_read_only_count", SealedSubmitArgs[1]);
Show("io_submit_read_only_passed", reinterpret_cast<const uint64_t*>(SealedSubmitArgs[2])[0] == BlocksHost);
Show("io_submit_read_only_copies", IoCopyCount.load() - CopiesBefore);
FinishSyscallArguments(static_cast<uint64_t>(-EBADF), &SealedSubmit);
TestIocb Leading = ReadBlock;
uint64_t LeadingList[2] = {reinterpret_cast<uint64_t>(&Leading), Blocks};
ArgumentStorage LeadingSubmit;
uint64_t LeadingSubmitArgs[6] = {5, 2, reinterpret_cast<uint64_t>(LeadingList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, LeadingSubmitArgs, &LeadingSubmit);
const auto* LeadingSent = reinterpret_cast<const uint64_t*>(LeadingSubmitArgs[2]);
Show("io_submit_read_only_after_copy", LeadingSubmitArgs[1] == 2 && FindIoCopyLocked(LeadingSent[0]) != nullptr && LeadingSent[1] == BlocksHost);
FinishSyscallArguments(1, &LeadingSubmit);
ArgumentStorage LeadingDestroy;
uint64_t LeadingDestroyArgs[6] = {5, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, LeadingDestroyArgs, &LeadingDestroy);
FinishSyscallArguments(0, &LeadingDestroy);
Show("io_submit_read_only_after_copy_released", IoCopyCount.load() - CopiesBefore);
Show("io_submit_read_only_untouched", std::memcmp(HighIocb, &HighExpected, sizeof(TestIocb)) == 0);
Protect(Blocks, Page, PROT_READ | PROT_WRITE);
HighIocb->Opcode = 1;
HighIocb->Buffer = reinterpret_cast<uint64_t>(LowBuffer);
HighIocb->Bytes = sizeof(LowBuffer);
Protect(Blocks, Page, PROT_READ);
ArgumentStorage ReadOnlyNative;
uint64_t ReadOnlyNativeArgs[6] = {1, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Show("io_submit_read_only_native_result", Call(Sys::SYSCALL_x64_io_submit, ReadOnlyNativeArgs, &ReadOnlyNative));
Show("io_submit_read_only_native_block", reinterpret_cast<const uint64_t*>(ReadOnlyNativeArgs[2])[0] == BlocksHost);
Show("io_submit_read_only_native_copies", IoCopyCount.load() - CopiesBefore);
Protect(Blocks, Page, PROT_READ | PROT_WRITE);
HighIocb->Opcode = 7;
HighIocb->Buffer = reinterpret_cast<uint64_t>(Scatter);
HighIocb->Bytes = 2;
HighIocb->Key = 4;
ArgumentStorage KeyedHigh;
uint64_t KeyedHighArgs[6] = {7, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, KeyedHighArgs, &KeyedHigh);
FinishSyscallArguments(1, &KeyedHigh);
Show("io_submit_high_key_accepted", HighIocb->Key);
HighIocb->Key = 4;
ArgumentStorage MovedHigh;
uint64_t MovedHighArgs[6] = {7, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, MovedHighArgs, &MovedHigh);
Unmap(Blocks, Page);
void* ReusedPage = mmap(reinterpret_cast<void*>(BlocksHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
Show("io_submit_key_reused_mapped", ReusedPage == reinterpret_cast<void*>(BlocksHost));
if (ReusedPage == reinterpret_cast<void*>(BlocksHost)) {
static_cast<TestIocb*>(ReusedPage)->Key = 4;
FinishSyscallArguments(1, &MovedHigh);
Show("io_submit_key_unmapped_skipped", static_cast<TestIocb*>(ReusedPage)->Key);
munmap(ReusedPage, Page);
}
Map(Blocks, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
static uint64_t RacedHost;
static uint32_t RacedSeen;
static TestIocb* RacedStandIn;
static std::thread RacedSibling;
static std::atomic<int> RacedAttempted;
static bool RacedBlocked;
TranslateRange(Blocks, Page, &RacedHost);
auto* RacedIocb = reinterpret_cast<TestIocb*>(RacedHost);
*RacedIocb = {};
RacedIocb->Opcode = 7;
RacedIocb->Buffer = reinterpret_cast<uint64_t>(Scatter);
RacedIocb->Bytes = 2;
RacedIocb->Key = 4;
ArgumentStorage RacedHigh;
uint64_t RacedHighArgs[6] = {7, 1, reinterpret_cast<uint64_t>(HighIocbList), 0, 0, 0};
Call(Sys::SYSCALL_x64_io_submit, RacedHighArgs, &RacedHigh);
FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] {
RacedSibling = std::thread([] {
std::unique_lock Lock {FEX::HLE::_SyscallHandler->VMATracking.Mutex, std::try_to_lock};
RacedBlocked = !Lock.owns_lock();
RacedAttempted = 1;
if (!Lock.owns_lock()) {
Lock.lock();
}
RacedSeen = reinterpret_cast<TestIocb*>(RacedHost)->Key;
Unmap(Blocks, Page);
void* StandIn = mmap(reinterpret_cast<void*>(RacedHost), Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
if (StandIn == reinterpret_cast<void*>(RacedHost)) {
RacedStandIn = static_cast<TestIocb*>(StandIn);
RacedStandIn->Key = 4;
}
});
while (RacedAttempted.load() == 0) {
std::this_thread::yield();
}
};
FinishSyscallArguments(1, &RacedHigh);
RacedSibling.join();
Show("io_submit_key_store_blocked_writer", RacedBlocked);
Show("io_submit_key_store_before_unmap", RacedSeen);
Show("io_submit_key_store_stand_in", RacedStandIn != nullptr ? RacedStandIn->Key : 0xff);
Show("io_submit_key_store_released", FEX::HLE::TestThread.HighMemoryTrap.Mappings.Held);
if (RacedStandIn != nullptr) {
munmap(RacedStandIn, Page);
}
ArgumentStorage KeyedDestroy;
uint64_t KeyedDestroyArgs[6] = {7, 0, 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_destroy, KeyedDestroyArgs, &KeyedDestroy);
FinishSyscallArguments(0, &KeyedDestroy);
Show("io_submit_keyed_high_released", IoCopyCount.load() - CopiesBefore);
auto* LowBlock = static_cast<TestIocb*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
*LowBlock = {};
LowBlock->Opcode = 7;
LowBlock->Buffer = reinterpret_cast<uint64_t>(Scatter);
LowBlock->Bytes = 2;
const TestIocb LowExpected = *LowBlock;
uint64_t LowList[1] = {reinterpret_cast<uint64_t>(LowBlock)};
ArgumentStorage LowCopy;
uint64_t LowCopyArgs[6] = {1, 1, reinterpret_cast<uint64_t>(LowList), 0, 0, 0};
Show("low_iocb_result", Call(Sys::SYSCALL_x64_io_submit, LowCopyArgs, &LowCopy));
const uint64_t LowSent = reinterpret_cast<const uint64_t*>(LowCopyArgs[2])[0];
Show("low_iocb_private", LowSent != reinterpret_cast<uint64_t>(LowBlock) && FindIoCopyLocked(LowSent) != nullptr);
mprotect(LowBlock, Page, PROT_READ);
ProtectCalls = 0;
FinishSyscallArguments(1, &LowCopy);
Show("low_iocb_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0);
const auto Regions = Count.load();
Count.store(0);
ArgumentStorage QuietCancel;
uint64_t QuietCancelArgs[6] = {1, reinterpret_cast<uint64_t>(LowBlock), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_cancel, QuietCancelArgs, &QuietCancel);
Show("low_iocb_quiet_cancel", QuietCancelArgs[1] == LowSent);
TestEvent QuietReaped[1] = {{0, LowSent, 16, 0}};
ArgumentStorage QuietReap;
uint64_t QuietReapArgs[6] = {1, 1, 1, reinterpret_cast<uint64_t>(QuietReaped), 0, 0};
Call(Sys::SYSCALL_x64_io_getevents, QuietReapArgs, &QuietReap);
Show("low_iocb_quiet_host_buffer", QuietReapArgs[3] == reinterpret_cast<uint64_t>(QuietReap.EventBuffer.data()));
Deliver(QuietReapArgs, QuietReaped, sizeof(QuietReaped));
FinishSyscallArguments(1, &QuietReap);
uint32_t QuietRing[8] = {0, 64, 0, 0, 0xa10a10a1, 1, 0, 32};
uint64_t QuietRingContext = reinterpret_cast<uint64_t>(QuietRing);
ArgumentStorage QuietSetup;
uint64_t QuietSetupArgs[6] = {64, reinterpret_cast<uint64_t>(&QuietRingContext), 0, 0, 0, 0};
Call(Sys::SYSCALL_x64_io_setup, QuietSetupArgs, &QuietSetup);
FinishSyscallArguments(0, &QuietSetup);
Show("low_quiet_setup_magic", QuietRing[4]);
Count.store(Regions);
Show("low_iocb_quiet_object", QuietReaped[0].Object == reinterpret_cast<uint64_t>(LowBlock));
Show("low_iocb_quiet_freed", IoCopyCount.load() - CopiesBefore);
Show("low_iocb_protect_calls", ProtectCalls);
Show("low_iocb_reaped_untouched", std::memcmp(LowBlock, &LowExpected, sizeof(TestIocb)) == 0);
munmap(LowBlock, Page);
for (auto& Copy : IoCopies) {
Copy.Used = true;
}
IoCopyCount = MaxIoCopies;
ArgumentStorage Crowded;
uint64_t CrowdedArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Show("io_submit_crowded_result", Call(Sys::SYSCALL_x64_io_submit, CrowdedArgs, &Crowded));
Show("io_submit_crowded_untouched", GuestBlocksUntouched());
IoCopies[5].Used = false;
IoCopyCount = MaxIoCopies - 1;
ArgumentStorage LastCopy;
uint64_t LastCopyArgs[6] = {1, 2, reinterpret_cast<uint64_t>(Submitted), 0, 0, 0};
Show("io_submit_last_copy_result", Call(Sys::SYSCALL_x64_io_submit, LastCopyArgs, &LastCopy));
Show("io_submit_last_copy_count", LastCopyArgs[1]);
Show("io_submit_last_copy_slot", reinterpret_cast<const uint64_t*>(LastCopyArgs[2])[0] == reinterpret_cast<uint64_t>(&IoCopies[5]));
for (auto& Copy : IoCopies) {
Copy.Used = false;
}
IoCopyCount = 0;
auto* CapPage = static_cast<uint32_t*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
CapPage[0] = 0x1234;
ArgumentStorage CapSealed;
uint64_t CapSealedArgs[6] = {reinterpret_cast<uint64_t>(CapPage), Single + 64, 0, 0, 0, 0};
Show("capget_sealed_result", Call(Sys::SYSCALL_x64_capget, CapSealedArgs, &CapSealed));
reinterpret_cast<uint32_t*>(CapSealedArgs[0])[0] = 0x20080522;
mprotect(CapPage, Page, PROT_READ);
Show("capget_sealed_finish", FinishResult(static_cast<uint64_t>(-EINVAL), &CapSealed));
Show("capget_sealed_version", CapPage[0]);
struct iovec ShortVector = {reinterpret_cast<void*>(Single + 256), 32};
struct mmsghdr Shorts[3] {};
for (auto& Short : Shorts) {
Short.msg_hdr.msg_iov = &ShortVector;
Short.msg_hdr.msg_iovlen = 1;
}
ArgumentStorage ShortFirst;
uint64_t ShortFirstArgs[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Shorts), 3, 0, 0, 0};
Show("sendmmsg_short_first_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortFirstArgs, &ShortFirst));
reinterpret_cast<struct mmsghdr*>(ShortFirstArgs[1])[0].msg_len = 10;
SendCalls = 0;
Show("sendmmsg_short_first_finish", FinishResult(1, &ShortFirst));
Show("sendmmsg_short_first_sends", SendCalls);
Show("sendmmsg_short_first_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len);
for (auto& Short : Shorts) {
Short.msg_len = 0;
}
ArgumentStorage ShortSecond;
uint64_t ShortSecondArgs[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Shorts), 3, 0, 0, 0};
Show("sendmmsg_short_second_result", Call(Sys::SYSCALL_x64_sendmmsg, ShortSecondArgs, &ShortSecond));
Show("sendmmsg_short_second_submitted", ShortSecondArgs[2]);
const int Pinned = ShortSecond.Socket;
Show("sendmmsg_pinned_distinct", Pinned >= 0 && Pinned != Peer);
Show("sendmmsg_pinned_dispatched", ShortSecondArgs[0] == static_cast<uint64_t>(Pinned));
reinterpret_cast<struct mmsghdr*>(ShortSecondArgs[1])[0].msg_len = 32;
SendCalls = 0;
SendLimit = 5;
SentSocket = -1;
Show("sendmmsg_short_second_finish", FinishResult(1, &ShortSecond));
SendLimit = ~size_t {};
Show("sendmmsg_short_second_sends", SendCalls);
Show("sendmmsg_short_second_lengths", Shorts[0].msg_len * 0x10000 + Shorts[1].msg_len * 0x100 + Shorts[2].msg_len);
Show("sendmmsg_pinned_used", SentSocket == Pinned);
Show("sendmmsg_pinned_closed", fcntl(Pinned, F_GETFD) == -1 && errno == EBADF && ShortSecond.Socket == -1);
for (auto& Short : Shorts) {
Short.msg_len = 0;
}
ArgumentStorage ShortFailed;
uint64_t ShortFailedArgs[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Shorts), 3, 0, 0, 0};
Call(Sys::SYSCALL_x64_sendmmsg, ShortFailedArgs, &ShortFailed);
const int FailedPin = ShortFailed.Socket;
Show("sendmmsg_error_finish", FinishResult(static_cast<uint64_t>(-EAGAIN), &ShortFailed));
Show("sendmmsg_error_closed", FailedPin >= 0 && fcntl(FailedPin, F_GETFD) == -1 && errno == EBADF);
int Pair[2];
if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0, Pair) != 0) {
std::fprintf(stderr, "socketpair: %s\n", std::strerror(errno));
return 1;
}
struct iovec Payloads[3] = {};
for (int i = 0; i < 3; ++i) {
std::memset(Backing + 2048 + 16 * i, 'A' + i, 4);
Payloads[i] = {reinterpret_cast<void*>(Single + 2048 + 16 * i), 4};
}
auto Drain = [&] {
uint64_t Packed = 0;
unsigned char Data[16];
while (recv(Pair[1], Data, sizeof(Data), MSG_DONTWAIT) > 0) {
Packed = Packed * 0x100 + Data[0];
}
return Packed;
};
auto Dispatch = [&](uint64_t* Args) {
return static_cast<uint64_t>(sendmmsg(static_cast<int>(Args[0]), reinterpret_cast<struct mmsghdr*>(Args[1]), static_cast<unsigned>(Args[2]), 0));
};
auto Lengths = [&](struct mmsghdr* Headers) {
return Headers[0].msg_len * 0x10000 + Headers[1].msg_len * 0x100 + Headers[2].msg_len;
};
PassSend = true;
struct mmsghdr Real[3] {};
for (int i = 0; i < 3; ++i) {
Real[i].msg_hdr.msg_iov = &Payloads[i];
Real[i].msg_hdr.msg_iovlen = 1;
}
DupFailures = 1;
ArgumentStorage Emfile;
uint64_t EmfileArgs[6] = {static_cast<uint64_t>(Pair[0]), reinterpret_cast<uint64_t>(Real), 3, 0, 0, 0};
Show("sendmmsg_emfile_result", Call(Sys::SYSCALL_x64_sendmmsg, EmfileArgs, &Emfile));
Show("sendmmsg_emfile_submitted", EmfileArgs[2]);
Show("sendmmsg_emfile_original", EmfileArgs[0] == static_cast<uint64_t>(Pair[0]) && Emfile.Socket == -1 && DupFailures == 0);
Show("sendmmsg_emfile_first_only", Drain());
Show("sendmmsg_emfile_finish", FinishResult(Dispatch(EmfileArgs), &Emfile));
Show("sendmmsg_emfile_received", Drain());
Show("sendmmsg_emfile_lengths", Lengths(Real));
const uint64_t ReadOnly = 0x730000000000ULL;
Map(ReadOnly, 2 * Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
uint64_t ReadOnlyHost {};
TranslateRange(ReadOnly, 2 * Page, &ReadOnlyHost);
auto* ReadOnlyHeaders = reinterpret_cast<struct mmsghdr*>(ReadOnlyHost + Page - sizeof(struct mmsghdr));
for (int i = 0; i < 3; ++i) {
ReadOnlyHeaders[i] = {};
ReadOnlyHeaders[i].msg_hdr.msg_iov = &Payloads[i];
ReadOnlyHeaders[i].msg_hdr.msg_iovlen = 1;
}
Protect(ReadOnly + Page, Page, PROT_READ);
DupFailures = 1;
ArgumentStorage ReadOnlyBatch;
uint64_t ReadOnlyArgs[6] = {static_cast<uint64_t>(Pair[0]), ReadOnly + Page - sizeof(struct mmsghdr), 3, 0, 0, 0};
Show("sendmmsg_emfile_readonly_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyArgs, &ReadOnlyBatch));
Show("sendmmsg_emfile_readonly_submitted", ReadOnlyArgs[2]);
Show("sendmmsg_emfile_readonly_finish", FinishResult(Dispatch(ReadOnlyArgs), &ReadOnlyBatch));
Show("sendmmsg_emfile_readonly_received", Drain());
Show("sendmmsg_emfile_readonly_lengths", Lengths(ReadOnlyHeaders));
DupFailures = 1;
ArgumentStorage ReadOnlyFirst;
uint64_t ReadOnlyFirstArgs[6] = {static_cast<uint64_t>(Pair[0]), ReadOnly + Page, 1, 0, 0, 0};
Show("sendmmsg_emfile_only_result", Call(Sys::SYSCALL_x64_sendmmsg, ReadOnlyFirstArgs, &ReadOnlyFirst));
Show("sendmmsg_emfile_only_finish", FinishResult(Dispatch(ReadOnlyFirstArgs), &ReadOnlyFirst));
Show("sendmmsg_emfile_only_received", Drain());
DupFailures = 0;
auto* Unreadable = static_cast<struct iovec*>(mmap(nullptr, Page, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
struct mmsghdr Middle[3] {};
for (int i = 0; i < 3; ++i) {
Middle[i].msg_hdr.msg_iov = i == 1 ? Unreadable : &Payloads[i];
Middle[i].msg_hdr.msg_iovlen = 1;
}
ArgumentStorage MiddleBatch;
uint64_t MiddleArgs[6] = {static_cast<uint64_t>(Pair[0]), reinterpret_cast<uint64_t>(Middle), 3, 0, 0, 0};
Show("sendmmsg_unreadable_middle_result", Call(Sys::SYSCALL_x64_sendmmsg, MiddleArgs, &MiddleBatch));
Show("sendmmsg_unreadable_middle_submitted", MiddleArgs[2]);
Show("sendmmsg_unreadable_middle_queued", MiddleBatch.Messages.size());
Show("sendmmsg_unreadable_middle_finish", FinishResult(Dispatch(MiddleArgs), &MiddleBatch));
Show("sendmmsg_unreadable_middle_received", Drain());
Show("sendmmsg_unreadable_middle_lengths", Lengths(Middle));
struct mmsghdr Last[3] {};
for (int i = 0; i < 3; ++i) {
Last[i].msg_hdr.msg_iov = i == 2 ? Unreadable : &Payloads[i];
Last[i].msg_hdr.msg_iovlen = 1;
}
ArgumentStorage LastBatch;
uint64_t LastArgs[6] = {static_cast<uint64_t>(Pair[0]), reinterpret_cast<uint64_t>(Last), 3, 0, 0, 0};
Show("sendmmsg_unreadable_last_result", Call(Sys::SYSCALL_x64_sendmmsg, LastArgs, &LastBatch));
Show("sendmmsg_unreadable_last_submitted", LastArgs[2]);
Show("sendmmsg_unreadable_last_queued", LastBatch.Messages.size());
const int LastPin = LastBatch.Socket;
Show("sendmmsg_unreadable_last_pinned", LastPin >= 0 && LastArgs[0] == static_cast<uint64_t>(LastPin));
Show("sendmmsg_unreadable_last_finish", FinishResult(Dispatch(LastArgs), &LastBatch));
Show("sendmmsg_unreadable_last_received", Drain());
Show("sendmmsg_unreadable_last_lengths", Lengths(Last));
struct mmsghdr First[3] {};
for (int i = 0; i < 3; ++i) {
First[i].msg_hdr.msg_iov = i == 0 ? Unreadable : &Payloads[i];
First[i].msg_hdr.msg_iovlen = 1;
}
ArgumentStorage FirstBatch;
uint64_t FirstArgs[6] = {static_cast<uint64_t>(Pair[0]), reinterpret_cast<uint64_t>(First), 3, 0, 0, 0};
Show("sendmmsg_unreadable_first_result", Call(Sys::SYSCALL_x64_sendmmsg, FirstArgs, &FirstBatch));
Show("sendmmsg_unreadable_first_native", FirstArgs[1] == reinterpret_cast<uint64_t>(First) && FirstArgs[2] == 3 && FirstBatch.GuestMessages == 0);
Show("sendmmsg_unreadable_first_error", static_cast<uint64_t>(sendmmsg(Pair[0], First, 3, 0)) == static_cast<uint64_t>(-1) && errno == EFAULT);
Show("sendmmsg_unreadable_first_received", Drain());
PassSend = false;
auto* LowVectors = static_cast<struct iovec*>(mmap(nullptr, Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
char KeptLow[16];
LowVectors[0] = {KeptLow, sizeof(KeptLow)};
struct mmsghdr Growing[3] {};
Growing[0].msg_hdr.msg_iov = &ShortVector;
Growing[0].msg_hdr.msg_iovlen = 1;
for (int i = 1; i < 3; ++i) {
Growing[i].msg_hdr.msg_iov = LowVectors;
Growing[i].msg_hdr.msg_iovlen = 1;
}
ArgumentStorage Grown;
uint64_t GrownArgs[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Growing), 3, 0, 0, 0};
Show("sendmmsg_grown_result", Call(Sys::SYSCALL_x64_sendmmsg, GrownArgs, &Grown));
auto* GrownCopy = reinterpret_cast<struct mmsghdr*>(GrownArgs[1]);
Show("sendmmsg_grown_private", GrownCopy[1].msg_hdr.msg_iov != LowVectors && GrownCopy[1].msg_hdr.msg_iov[0].iov_base == KeptLow);
GrownCopy[0].msg_len = 32;
SendCalls = 0;
GrowAfterSend = LowVectors;
Show("sendmmsg_grown_finish", FinishResult(1, &Grown));
GrowAfterSend = nullptr;
Show("sendmmsg_grown_sends", SendCalls);
Show("sendmmsg_grown_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len);
for (auto& Message : Growing) {
Message.msg_len = 0;
}
LowVectors[0] = {KeptLow, sizeof(KeptLow)};
ArgumentStorage Vanished;
uint64_t VanishedArgs[6] = {static_cast<uint64_t>(Peer), reinterpret_cast<uint64_t>(Growing), 3, 0, 0, 0};
Show("sendmmsg_vanished_result", Call(Sys::SYSCALL_x64_sendmmsg, VanishedArgs, &Vanished));
reinterpret_cast<struct mmsghdr*>(VanishedArgs[1])[0].msg_len = 32;
SendCalls = 0;
SendLimit = 5;
UnmapAfterSend = LowVectors;
Show("sendmmsg_vanished_finish", FinishResult(1, &Vanished));
SendLimit = ~size_t {};
Show("sendmmsg_vanished_sends", SendCalls);
Show("sendmmsg_vanished_unmapped", UnmapAfterSend == nullptr && msync(LowVectors, Page, MS_ASYNC) == -1 && errno == ENOMEM);
Show("sendmmsg_vanished_lengths", Growing[0].msg_len * 0x10000 + Growing[1].msg_len * 0x100 + Growing[2].msg_len);
uint64_t AccessRegs[32] {};
AccessRegs[0] = 0x10000;
AccessRegs[2] = 0xfffffffeULL;
auto Decode = [&](const char* Name, uint32_t Insn) {
uint64_t Address {};
uint32_t Size {};
bool Plain {};
const bool Known = DecodeAccess(Insn, AccessRegs, &Address, &Size, &Plain);
std::printf("decode_%s_known %x\n", Name, Known);
std::printf("decode_%s_offset %llx\n", Name, static_cast<unsigned long long>(Address - AccessRegs[0]));
std::printf("decode_%s_size %x\n", Name, Size);
std::printf("decode_%s_plain %x\n", Name, Plain);
};
Decode("str_x_imm", 0xf9000401);
Decode("ldr_x_pre", 0xf85fcc01);
Decode("ldr_x_post", 0xf8408401);
Decode("stur_x", 0xf81fc001);
Decode("ldr_w_lsl", 0xb8627801);
Decode("ldr_w_sxtw", 0xb862c801);
Decode("ldr_w_uxtw", 0xb8624801);
Decode("ldr_w_reserved", 0xb8620801);
Decode("stp_x", 0xa9010c01);
Decode("ldp_w_negative", 0x297f0c01);
Decode("ldp_q_post", 0xacc10c01);
Decode("str_q", 0x3d800401);
Decode("ld1_four", 0x4c402001);
Decode("st1_post", 0x4c9f7c01);
Decode("ld1_lane", 0x0d409001);
Decode("ld4r", 0x4d60e801);
Decode("ldadd", 0xf8210002);
Decode("ldar", 0xc8dffc01);
Decode("casp", 0x48227c04);
Decode("ldxp", 0xc87f0c01);
Decode("ldapur", 0x995fc001);
Decode("ldraa", 0xf8200400);
auto* Backings = static_cast<uint8_t*>(mmap(nullptr, 6 * Page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0));
const uint64_t Backed = reinterpret_cast<uint64_t>(Backings);
const uint64_t SeparateGuest = 0x6f0000000000ULL;
const uint64_t Adjacent = 0x6f0000100000ULL;
AddEntry(SeparateGuest, Page, Backed, false, PROT_READ | PROT_WRITE);
AddEntry(SeparateGuest + Page, Page, Backed + 2 * Page, false, PROT_READ | PROT_WRITE);
AddEntry(Adjacent, Page, Backed + 4 * Page, false, PROT_READ | PROT_WRITE);
AddEntry(Adjacent + Page, Page, Backed + 5 * Page, false, PROT_READ | PROT_WRITE);
std::memset(Backings + Page, 0xee, Page);
uint64_t StoreRegs[32] {};
StoreRegs[0] = SeparateGuest + Page - 4;
StoreRegs[1] = 0x1122334455667788ULL;
uint64_t SplitAddress {};
uint32_t SplitSize {};
bool SplitPlain {};
DecodeAccess(0xf9000001, StoreRegs, &SplitAddress, &SplitSize, &SplitPlain);
AccessPiece SplitPieces[MaxAccessPieces] {};
const auto SplitParts = PlanAccessLocked(SplitAddress, SplitSize, SplitPieces);
Show("split_access_parts", SplitParts);
Show("split_access_first", SplitPieces[0].Host - Backed);
Show("split_access_second", SplitPieces[1].Host - Backed);
Show("split_access_sizes", SplitPieces[0].Size * 0x10 + SplitPieces[1].Size);
Show("split_access_guests", (SplitPieces[0].Guest == SeparateGuest + Page - 4) * 0x10 + (SplitPieces[1].Guest == SeparateGuest + Page));
Show("split_access_contiguous", HostContiguous(SplitPieces, SplitParts));
Show("split_access_store_reachable", PiecesReachable(SplitPieces, SplitParts, true));
alignas(16) uint8_t Window[96] {};
const auto WindowOffset = SplitAddress & 15;
CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true);
std::memcpy(Window + WindowOffset, &StoreRegs[1], sizeof(StoreRegs[1]));
CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false);
uint32_t SplitWords[3] {};
std::memcpy(&SplitWords[0], Backings + Page - 4, 4);
std::memcpy(&SplitWords[1], Backings + 2 * Page, 4);
std::memcpy(&SplitWords[2], Backings + Page, 4);
Show("split_store_low", SplitWords[0]);
Show("split_store_high", SplitWords[1]);
Show("split_store_neighbour", SplitWords[2]);
std::memset(Window, 0, sizeof(Window));
CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true);
uint64_t SplitLoaded {};
std::memcpy(&SplitLoaded, Window + WindowOffset, sizeof(SplitLoaded));
Show("split_load_value", SplitLoaded);
SplitPieces[1].Prot = PROT_READ;
Show("split_readonly_store", PiecesReachable(SplitPieces, SplitParts, true));
Show("split_readonly_load", PiecesReachable(SplitPieces, SplitParts, false));
SplitPieces[1].Prot = PROT_NONE;
Show("split_none_load", PiecesReachable(SplitPieces, SplitParts, false));
AccessPiece EdgePieces[MaxAccessPieces] {};
Show("split_unmapped_parts", PlanAccessLocked(SeparateGuest + 2 * Page - 4, 8, EdgePieces));
Show("split_inside_parts", PlanAccessLocked(SeparateGuest + 16, 64, EdgePieces));
Show("split_inside_host", EdgePieces[0].Host - Backed);
AccessPiece JoinedPieces[MaxAccessPieces] {};
const auto JoinedParts = PlanAccessLocked(Adjacent + Page - 4, 8, JoinedPieces);
Show("joined_access_parts", JoinedParts);
Show("joined_access_contiguous", HostContiguous(JoinedPieces, JoinedParts));
Show("joined_access_delta", JoinedPieces[0].Host - (Adjacent + Page - 4) == Backed + 4 * Page - Adjacent);
uint64_t OrderedRegs[32] {};
Show("ordered_load_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs));
Show("ordered_load_value", OrderedRegs[1]);
OrderedRegs[1] = 0xa1a2a3a4b5b6b7b8ULL;
Show("ordered_store_parts", EmulateOrdered(0xd9000001, SplitPieces, SplitParts, OrderedRegs));
uint32_t OrderedWords[2] {};
std::memcpy(&OrderedWords[0], Backings + Page - 4, 4);
std::memcpy(&OrderedWords[1], Backings + 2 * Page, 4);
Show("ordered_store_low", OrderedWords[0]);
Show("ordered_store_high", OrderedWords[1]);
AccessPiece WordPieces[MaxAccessPieces] {};
const auto WordParts = PlanAccessLocked(SeparateGuest + Page - 2, 4, WordPieces);
OrderedRegs[1] = 0;
Show("ordered_signed_parts", EmulateOrdered(0x99800001, WordPieces, WordParts, OrderedRegs) == WordParts && WordParts == 2);
Show("ordered_signed_value", OrderedRegs[1]);
mprotect(Backings + 2 * Page, Page, PROT_NONE);
OrderedRegs[1] = 0x77;
Show("ordered_fault_parts", EmulateOrdered(0xd9400001, SplitPieces, SplitParts, OrderedRegs));
Show("ordered_fault_untouched", OrderedRegs[1]);
Show("gather_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true));
Show("scatter_fault_piece", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, false));
mprotect(Backings + 2 * Page, Page, PROT_READ | PROT_WRITE);
Show("gather_whole", CopyPieces(Window + WindowOffset, SplitPieces, SplitParts, true));
Show("probe_instruction", ProbeInstruction(16));
Show("probe_instruction_low", ProbeInstruction(2));
auto OrderedKind = [](uint32_t Insn) { return static_cast<uint64_t>(IsOrderedAccess(Insn)); };
Show("ordered_kinds", OrderedKind(0xd9400001) << 20 | OrderedKind(0x99800001) << 16 | OrderedKind(0xc8dffc01) << 12 | OrderedKind(0xc89ffc01) << 8 |
OrderedKind(0xf8bfc001) << 4 | OrderedKind(0xf9400001));
Show("ordered_atomics", OrderedKind(0xf8210002) << 8 | OrderedKind(0x48227c04) << 4 | OrderedKind(0xc87f0c01));
auto WriteKind = [](uint32_t Insn) { return static_cast<uint64_t>(IsWrite(Insn)); };
Show("write_loads", WriteKind(0xb9800001) << 20 | WriteKind(0x99800001) << 16 | WriteKind(0x39c00001) << 12 | WriteKind(0xf9400001) << 8 |
WriteKind(0x3dc00401) << 4 | WriteKind(0xd9400001));
Show("write_stores", WriteKind(0xf9000001) << 12 | WriteKind(0xd9000001) << 8 | WriteKind(0x3d800401) << 4 | WriteKind(0x39000001));
Show("extend_signed_half_w", ExtendOrdered(0x59c00001, 0x8001));
Show("extend_signed_half_x", ExtendOrdered(0x59800001, 0x8001));
Show("extend_unsigned_byte", ExtendOrdered(0x19400001, 0x80));
Show("extend_ldar", ExtendOrdered(0x889ffc01 | (1U << 22), 0x80000000));
TestHold Held {};
std::atomic<int> WriterIn {0};
uint64_t HoldResults[4] {};
std::thread Holder([&] {
{
MappingHold Hold {Held};
Hold.Keep();
}
HoldResults[0] = Held.Held;
std::thread Writer([&] {
std::unique_lock Exclusive {FEX::HLE::_SyscallHandler->VMATracking.Mutex};
WriterIn = 1;
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
HoldResults[1] = WriterIn.load();
ReleaseMappings(Held);
Writer.join();
HoldResults[2] = WriterIn.load() * 0x10 + Held.Held;
{
MappingHold Hold {Held};
}
HoldResults[3] = ExclusiveFromAnotherThread() * 0x10 + Held.Held;
});
Holder.join();
Show("hold_kept_held", HoldResults[0]);
Show("hold_blocks_writer", HoldResults[1]);
Show("hold_released", HoldResults[2]);
Show("hold_scoped", HoldResults[3]);
struct sigaction TrapAction {};
TrapAction.sa_sigaction = CountTrap;
TrapAction.sa_flags = SA_SIGINFO;
sigaction(SIGTRAP, &TrapAction, nullptr);
uint64_t DeferResults[12] {};
std::thread Deferring([&] {
siginfo_t User {};
User.si_signo = SIGTRAP;
User.si_code = SI_QUEUE;
User.si_pid = getpid();
User.si_uid = getuid();
User.si_value.sival_int = 0x1234;
siginfo_t Breakpoint {};
Breakpoint.si_signo = SIGTRAP;
Breakpoint.si_code = TRAP_BRKPT;
TestHold Deferred {};
DeferResults[0] = DeferWhileHeld(Deferred, SIGTRAP, &User);
{
MappingHold Hold {Deferred};
Hold.Keep();
}
sigset_t Current;
pthread_sigmask(SIG_BLOCK, nullptr, &Current);
DeferResults[1] = sigismember(&Current, SIGTRAP) * 0x100 + sigismember(&Current, SIGSEGV) * 0x10 + sigismember(&Current, SIGILL);
DeferResults[2] = DeferWhileHeld(Deferred, SIGTRAP, &User) * 0x100 + DeferWhileHeld(Deferred, SIGTRAP, &Breakpoint) * 0x10 +
DeferWhileHeld(Deferred, SIGILL, &User);
DeferResults[3] = TrapsSeen.load();
DeferResults[4] = ReleaseMappings(Deferred);
DeferResults[5] = TrapsSeen.load() * 0x10 + Deferred.Held;
DeferResults[6] = ExclusiveFromAnotherThread();
sigset_t Trap;
sigemptyset(&Trap);
sigaddset(&Trap, SIGTRAP);
pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr);
DeferResults[7] = TrapsSeen.load();
DeferResults[8] = static_cast<uint32_t>(TrapCode.load()) * 0x10000ULL + static_cast<uint32_t>(TrapValue.load());
{
MappingHold Hold {Deferred};
User.si_value.sival_int = 0x5678;
DeferWhileHeld(Deferred, SIGTRAP, &User);
}
DeferResults[9] = TrapsSeen.load();
pthread_sigmask(SIG_BLOCK, nullptr, &Current);
DeferResults[10] = sigismember(&Current, SIGTRAP);
pthread_sigmask(SIG_UNBLOCK, &Trap, nullptr);
DeferResults[11] = TrapsSeen.load() * 0x10000ULL + static_cast<uint32_t>(TrapValue.load());
});
Deferring.join();
Show("defer_unheld", DeferResults[0]);
Show("defer_held_mask", DeferResults[1]);
Show("defer_kinds", DeferResults[2]);
Show("defer_not_run_while_held", DeferResults[3]);
Show("defer_requeued", DeferResults[4]);
Show("defer_after_release", DeferResults[5]);
Show("defer_lock_free", DeferResults[6]);
Show("defer_delivered", DeferResults[7]);
Show("defer_info", DeferResults[8]);
Show("defer_scoped_pending", DeferResults[9]);
Show("defer_scoped_blocked", DeferResults[10]);
Show("defer_scoped_delivered", DeferResults[11]);
const uint64_t Delivering = 0x730000000000ULL;
Map(Delivering, Page, PROT_READ | PROT_WRITE, Anonymous, -1, 0);
static int TrapsBefore;
TrapsBefore = TrapsSeen.load();
FEX::HLE::FaultSafeUserMemAccess::BeforeUserWrite = [] {
siginfo_t User {};
User.si_signo = SIGTRAP;
User.si_code = SI_QUEUE;
User.si_pid = getpid();
User.si_uid = getuid();
DeferWhileHeld(FEX::HLE::TestThread.HighMemoryTrap.Mappings, SIGTRAP, &User);
};
const uint32_t DeliveringValue = 0x5a;
Show("guest_store_deferred_result", CopyToGuest(Delivering, &DeliveringValue, sizeof(DeliveringValue)));
Show("guest_store_deferred_delivered", TrapsSeen.load() - TrapsBefore);
sigset_t AfterStore;
pthread_sigmask(SIG_BLOCK, nullptr, &AfterStore);
Show("guest_store_deferred_unblocked", !sigismember(&AfterStore, SIGTRAP));
Unmap(Delivering, Page);
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("),
block(source, "void RemoveEntry("),
block(source, "bool HasRoomLocked("),
block(source, "void ReleaseRetiredLocked("),
block(source, "void UnmapHost("),
block(source, "int UnmapLocked("),
block(source, "void BeginWrite("),
block(source, "void EndWrite("),
block(source, "constexpr uint8_t TrackedProt("),
block(source, "int SplitLocked("),
block(source, "void CoalesceLocked("),
span(source, " bool FindLocked(", " uint64_t NeighbourHint("),
block(source, "uint64_t NeighbourHint("),
span(source, " constexpr uint32_t RtField(", " constexpr bool IsLoadStore("),
block(source, "constexpr bool IsExclusive("),
span(source, " constexpr bool IsSingleRegister(", " constexpr bool IsExclusiveLoad("),
span(source, " constexpr bool IsExclusiveLoad(", " int PickScratch("),
span(source, " constexpr uint64_t MaxIoVectors", "} // namespace"),
])
public = "\n".join(block(source, signature) for signature in (
"bool Contains(",
"bool ClaimsMapping(",
"uint64_t Map(",
"uint64_t Unmap(",
"uint64_t Protect(",
"uint64_t Advise(",
"bool DiscardsContents(",
"uint64_t ToGuest(",
"bool TranslateRange(",
"uint64_t TranslateSyscallArguments(",
("void FinishSyscallArguments(", "uint64_t 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.replace("HARNESS_SECONDS", str(HARNESS_SECONDS))
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), "-latomic", "-pthread"], check=True)
try:
output = subprocess.run([str(binary)], capture_output=True, text=True, check=True, timeout=HARNESS_SECONDS + 30).stdout
except subprocess.TimeoutExpired as expired:
raise AssertionError(f"harness did not finish within {HARNESS_SECONDS + 30} seconds") from expired
except subprocess.CalledProcessError as failed:
if failed.returncode == -signal.SIGALRM:
raise AssertionError(f"harness did not finish within {HARNESS_SECONDS} seconds") from failed
raise
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(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_element_counts_size_their_buffers(self):
self.assertEqual(self.value("poll_split_result"), self.efault())
self.assertEqual(self.value("poll_fits_result"), 0)
self.assertEqual(self.value("poll_joined_result"), 0)
self.assertEqual(self.value("poll_huge_result"), 0)
self.assertEqual(self.value("epoll_split_result"), self.efault())
self.assertEqual(self.value("epoll_fits_result"), 0)
self.assertEqual(self.value("select_split_result"), self.efault())
self.assertEqual(self.value("select_fits_result"), 0)
self.assertEqual(self.value("select_wide_result"), 0)
def test_exclusive_access_respects_guest_protection(self):
self.assertEqual(self.value("guard_protect"), 0)
self.assertEqual(self.value("guard_low_size"), 4096)
self.assertEqual(self.value("guard_low_prot"), 3)
self.assertEqual(self.value("guard_mid_size"), 4096)
self.assertEqual(self.value("guard_mid_host"), 4096)
self.assertEqual(self.value("guard_mid_prot"), 1)
self.assertEqual(self.value("guard_high_size"), 4096)
self.assertEqual(self.value("guard_high_prot"), 3)
self.assertEqual(self.value("guard_store_readonly"), 0)
self.assertEqual(self.value("guard_load_readonly"), 1)
self.assertEqual(self.value("guard_store_writable"), 1)
self.assertEqual(self.value("guard_load_none"), 0)
self.assertEqual(self.value("guard_pair_store_readonly"), 0)
def test_exclusive_access_on_write_only_pages(self):
self.assertEqual(self.value("writeonly_load"), 1)
self.assertEqual(self.value("writeonly_store"), 1)
self.assertEqual(self.value("writeonly_pair_store"), 1)
self.assertEqual(self.value("exec_only_load"), 0)
def test_protection_changes_merge_regions_back(self):
self.assertEqual(self.value("guard_restore"), 0)
self.assertEqual(self.value("guard_restored_guest"), 0)
self.assertEqual(self.value("guard_restored_size"), 3 * 4096)
self.assertEqual(self.value("guard_restored_merged"), 2)
self.assertEqual(self.value("split_hosts_kept_apart"), 1)
self.assertEqual(self.value("toggle_failures"), 0)
self.assertEqual(self.value("toggle_entries"), 0)
self.assertEqual(self.value("toggle_pages"), 1100)
self.assertEqual(self.value("slot_order_restore"), 0)
self.assertEqual(self.value("slot_order_entries"), 2)
self.assertEqual(self.value("slot_order_second_size"), 2 * 4096)
def test_counted_arrays_must_map_to_one_host_range(self):
self.assertEqual(self.value("semop_split_result"), self.efault())
self.assertEqual(self.value("semop_fits_result"), 0)
self.assertEqual(self.value("getgroups_split_result"), self.efault())
self.assertEqual(self.value("io_getevents_split_result"), self.efault())
self.assertEqual(self.value("io_getevents_fits_result"), 0)
self.assertEqual(self.value("move_pages_split_result"), self.efault())
def test_message_batches_translate_every_header(self):
self.assertEqual(self.value("sendmmsg_result"), 0)
self.assertEqual(self.value("sendmmsg_copied"), 1)
self.assertEqual(self.value("sendmmsg_high_base"), 256)
self.assertEqual(self.value("sendmmsg_low_base"), 1)
self.assertEqual(self.value("sendmmsg_guest_untouched"), 256)
self.assertEqual(self.value("sendmmsg_submitted"), 1)
self.assertEqual(self.value("sendmmsg_finish"), 2)
self.assertEqual(self.value("sendmmsg_later_sends"), 1)
self.assertEqual(self.value("sendmmsg_lengths"), 0x2010)
self.assertEqual(self.value("sendmmsg_refused_finish"), 1)
self.assertEqual(self.value("sendmmsg_refused_lengths"), 0x2000)
self.assertEqual(self.value("recvmmsg_result"), 0)
self.assertEqual(self.value("recvmmsg_copied"), 1)
self.assertEqual(self.value("recvmmsg_base"), 512)
self.assertEqual(self.value("recvmmsg_first_length"), 40)
self.assertEqual(self.value("recvmmsg_first_flags"), 0x20)
self.assertEqual(self.value("recvmmsg_second_length"), 0)
self.assertEqual(self.value("recvmmsg_guest_iov"), 1)
self.assertEqual(self.value("recvmmsg_wide_result"), 0)
self.assertEqual(self.value("recvmmsg_wide_count"), 1024)
self.assertEqual(self.value("sendmmsg_split_result"), 0)
def test_fixed_size_pointers_must_map_to_one_host_range(self):
self.assertEqual(self.value("fstat_split_result"), self.efault())
self.assertEqual(self.value("fstat_edge_result"), 0)
self.assertEqual(self.value("uname_edge_result"), 0)
self.assertEqual(self.value("uname_over_result"), self.efault())
self.assertEqual(self.value("sigaction_edge_result"), 0)
self.assertEqual(self.value("sigaction_over_result"), self.efault())
self.assertEqual(self.value("sigprocmask_split_result"), self.efault())
self.assertEqual(self.value("sigprocmask_fits_result"), 0)
self.assertEqual(self.value("nanosleep_edge_result"), 0)
self.assertEqual(self.value("nanosleep_over_result"), self.efault())
self.assertEqual(self.value("mincore_split_result"), self.efault())
self.assertEqual(self.value("mincore_fits_result"), 0)
self.assertEqual(self.value("fcntl_lock_split_result"), self.efault())
self.assertEqual(self.value("fcntl_lock_fits_result"), 0)
self.assertEqual(self.value("fcntl_lock_fits_buffer"), 4096 - 32)
def test_strings_are_checked_up_to_their_terminator(self):
self.assertEqual(self.value("open_split_result"), self.efault())
self.assertEqual(self.value("open_joined_result"), 0)
self.assertEqual(self.value("open_joined_path"), 6 * 4096 - 2)
self.assertEqual(self.value("openat_inside_result"), 0)
self.assertEqual(self.value("openat_inside_path"), 3000)
self.assertEqual(self.value("open_unterminated_result"), self.efault())
self.assertEqual(self.value("rename_split_result"), self.efault())
def test_lengths_read_through_pointers(self):
self.assertEqual(self.value("accept_fits_result"), 0)
self.assertEqual(self.value("accept_split_result"), self.efault())
self.assertEqual(self.value("accept_capped_result"), 0)
self.assertEqual(self.value("accept_high_length_result"), self.efault())
self.assertEqual(self.value("getsockopt_split_result"), self.efault())
self.assertEqual(self.value("getsockopt_fits_result"), 0)
def test_message_queue_buffers_include_the_type_word(self):
self.assertEqual(self.value("msgsnd_fits_result"), 0)
self.assertEqual(self.value("msgsnd_split_result"), self.efault())
self.assertEqual(self.value("msgrcv_split_result"), self.efault())
self.assertEqual(self.value("msgsnd_huge_result"), self.efault())
def test_valid_calls_inside_one_mapping_still_succeed(self):
self.assertEqual(self.value("single_valid_failures"), 0)
self.assertEqual(self.value("single_valid_translated"), 10)
def test_aio_submissions_use_private_control_blocks(self):
self.assertEqual(self.value("io_submit_result"), 0)
self.assertEqual(self.value("io_submit_count"), 2)
self.assertEqual(self.value("io_submit_list_copied"), 1)
self.assertEqual(self.value("io_submit_private_blocks"), 1)
self.assertEqual(self.value("io_submit_buffer"), 768)
self.assertEqual(self.value("io_submit_fields_kept"), 1)
self.assertEqual(self.value("io_submit_vector_copied"), 1)
self.assertEqual(self.value("io_submit_vector_base"), 800)
self.assertEqual(self.value("io_submit_vector_low"), 1)
self.assertEqual(self.value("io_submit_guest_key"), 5)
self.assertEqual(self.value("io_submit_accepted_key"), 0)
self.assertEqual(self.value("io_submit_copies"), 2)
self.assertEqual(self.value("io_submit_copies_kept"), 2)
self.assertEqual(self.value("io_submit_high_result"), 0)
self.assertEqual(self.value("io_submit_high_copied"), 1)
self.assertEqual(self.value("io_submit_high_block"), 1536)
self.assertEqual(self.value("io_submit_high_guest_list"), 1536)
self.assertEqual(self.value("io_submit_high_uncopied"), 0)
self.assertEqual(self.value("io_submit_high_copy_result"), 0)
self.assertEqual(self.value("io_submit_high_copy_private"), 1)
self.assertEqual(self.value("io_submit_high_copy_vector"), 1)
self.assertEqual(self.value("low_iocb_result"), 0)
self.assertEqual(self.value("low_iocb_private"), 1)
def test_guest_control_blocks_are_never_patched(self):
for name in ("io_submit_guest_untouched", "io_submit_finished_untouched", "io_getevents_untouched",
"io_submit_partial_untouched", "io_submit_high_copy_untouched", "io_getevents_high_untouched",
"io_submit_read_only_untouched", "low_iocb_untouched", "low_iocb_reaped_untouched",
"io_submit_crowded_untouched"):
self.assertEqual(self.value(name), 1, name)
self.assertEqual(self.value("io_submit_high_copy_hidden"), 0)
self.assertEqual(self.value("io_submit_high_copy_sealed"), 1)
self.assertEqual(self.value("io_getevents_high_sealed"), 1)
for name in ("io_submit_protect_calls", "io_getevents_high_protect_calls", "low_iocb_protect_calls"):
self.assertEqual(self.value(name), 0, name)
text = PATCH.read_text()
for gone in ("PendingRestore", "RestoreInWindow", "ReconcilePending", "ReconcileRestores", "RestoreBeforeProtect",
"SavedWord", "ForceAccess", "/proc/self/mem", "bool Patch("):
self.assertNotIn(gone, text)
smc = "\n".join(added_lines(text, "Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp"))
self.assertIn(" } else {\n Result = ::mprotect(addr, len, prot);\n if (Result == -1) {\n return -errno;\n }", smc)
protect = block(added_lines(text, SOURCE), "uint64_t Protect(")
self.assertTrue(protect.splitlines()[1].strip() == "BeginWrite();")
def test_aio_completions_report_guest_control_blocks(self):
self.assertEqual(self.value("io_getevents_result"), 0)
self.assertEqual(self.value("io_getevents_object"), 1536)
self.assertEqual(self.value("io_getevents_unreported"), 1536)
self.assertEqual(self.value("io_getevents_copy_object"), 1)
self.assertEqual(self.value("io_getevents_vector_object"), 1)
self.assertEqual(self.value("io_getevents_alias_object"), 1536)
self.assertEqual(self.value("io_getevents_copies_freed"), 0)
self.assertEqual(self.value("io_getevents_high_object"), 0)
self.assertEqual(self.value("io_getevents_high_freed"), 0)
def test_aio_cancel_targets_the_submitted_copy(self):
self.assertEqual(self.value("io_cancel_result"), 0)
self.assertEqual(self.value("io_cancel_private"), 1)
self.assertEqual(self.value("io_cancel_other_context"), 1)
self.assertEqual(self.value("io_cancel_high_private"), 1)
self.assertEqual(self.value("io_cancel_accepted_private"), 1)
def test_aio_cancel_on_unreadable_or_unkeyed_blocks_stays_native(self):
self.assertEqual(self.value("io_cancel_hidden_native"), 1)
self.assertEqual(self.value("io_cancel_keyed_native"), 1)
def test_aio_keys_clear_only_for_accepted_submissions(self):
self.assertEqual(self.value("io_submit_keys_prepared"), 1)
self.assertEqual(self.value("io_submit_key_accepted"), 0)
self.assertEqual(self.value("io_submit_key_after_rejected"), 6)
self.assertEqual(self.value("io_submit_key_rejected_released"), 1)
def test_aio_completions_are_reaped_into_emulator_storage(self):
self.assertEqual(self.value("io_getevents_host_buffer"), 1)
self.assertEqual(self.value("low_iocb_quiet_host_buffer"), 1)
self.assertEqual(self.value("io_getevents_sealed_result"), self.efault())
self.assertEqual(self.value("io_getevents_sealed_released"), 0)
def test_aio_reaps_only_into_writable_guest_events(self):
self.assertEqual(self.value("io_getevents_unwritable_staged"), 1)
self.assertEqual(self.value("io_getevents_unwritable_result"), self.efault())
self.assertEqual(self.value("io_getevents_unwritable_kept"), 1)
self.assertEqual(self.value("io_getevents_writable_prefix"), 2)
self.assertEqual(self.value("io_getevents_writable_min"), 2)
self.assertEqual(self.value("io_getevents_writable_buffer"), 2)
def test_aio_wrapped_event_buffers_stay_native(self):
self.assertEqual(self.value("io_getevents_wrapped_staged"), 1)
self.assertEqual(self.value("io_getevents_wrapped_result"), self.efault())
def test_aio_failed_copy_out_is_delivered_on_the_next_reap(self):
self.assertEqual(self.value("io_getevents_sealed_result"), self.efault())
self.assertEqual(self.value("io_getevents_stash_nonblocking"), 1)
self.assertEqual(self.value("io_getevents_stash_ready_failed"), self.efault())
self.assertEqual(self.value("io_getevents_stash_ready_result"), 2)
self.assertEqual(self.value("io_getevents_stash_ready_order"), 1)
self.assertEqual(self.value("io_getevents_stash_result"), 1)
self.assertEqual(self.value("io_getevents_stash_event"), 1)
self.assertEqual(self.value("io_getevents_stash_once"), 1)
self.assertEqual(self.value("io_getevents_stash_plain_failed"), self.efault())
self.assertEqual(self.value("io_getevents_stash_topup_args"), 1)
self.assertEqual(self.value("io_getevents_stash_topup_result"), 2)
self.assertEqual(self.value("io_getevents_stash_topup_order"), 1)
self.assertEqual(self.value("io_getevents_stash_fault_result"), self.efault())
self.assertEqual(self.value("io_getevents_stash_kept_after_fault"), 1)
self.assertEqual(self.value("io_getevents_stash_interrupted"), 1)
self.assertEqual(self.value("io_getevents_stash_interrupted_event"), 1)
self.assertEqual(self.value("io_getevents_stash_destroyed"), 1)
self.assertEqual(self.value("io_getevents_stash_einval_result"), (1 << 64) - 22)
self.assertEqual(self.value("io_getevents_stash_einval_kept"), 1)
self.assertEqual(self.value("io_getevents_stash_recreated_result"), 0)
self.assertEqual(self.value("io_getevents_stash_destroyed_in_flight"), 1)
self.assertEqual(self.value("io_getevents_stash_blocking_kept"), 1)
self.assertEqual(self.value("io_getevents_stash_reserve_released"), 1)
self.assertEqual(self.value("io_getevents_recovery_preallocated"), 1)
self.assertEqual(self.value("io_getevents_recovery_delivered"), 1)
self.assertEqual(self.value("io_destroy_replacement_copies_kept"), 1)
self.assertEqual(self.value("io_destroy_replacement_stash_kept"), 1)
self.assertEqual(self.value("io_destroy_replacement_released"), 0)
self.assertEqual(self.value("io_setup_generation_kept"), 1)
self.assertEqual(self.value("io_setup_unpublished_result"), self.efault())
self.assertEqual(self.value("io_setup_unpublished_destroyed"), 1)
self.assertEqual(self.value("io_getevents_invalid_context_forgotten"), 0)
self.assertEqual(self.value("io_getevents_rejected_sibling_kept"), 1)
self.assertEqual(self.value("io_getevents_stash_many_failed"), self.efault())
self.assertEqual(self.value("io_getevents_stash_many_kept"), 1)
self.assertEqual(self.value("io_getevents_stash_every_context"), 1)
self.assertEqual(self.value("io_getevents_stash_triple_failed"), self.efault())
self.assertEqual(self.value("io_getevents_stash_retry_failed"), self.efault())
self.assertEqual(self.value("io_getevents_stash_ordered_result"), 3)
self.assertEqual(self.value("io_getevents_stash_ordered"), 1)
def test_blocked_aio_reapers_wait_in_bounded_slices(self):
self.assertEqual(self.value("io_getevents_blocking_sliced"), 1)
self.assertEqual(self.value("io_getevents_slices_accumulate"), 1)
self.assertEqual(self.value("io_pgetevents_slices_keep_mask"), 1)
self.assertEqual(self.value("io_getevents_odd_timeout_native"), 1)
def test_stashed_completions_reach_blocked_reapers_without_notification(self):
self.assertEqual(self.value("io_getevents_slice_collects_stash"), 1)
self.assertEqual(self.value("io_getevents_slice_without_notification"), 1)
code = "\n".join(added_lines(PATCH.read_text(), SOURCE))
for gone in ("eventfd", "SYS_io_submit", "WakeBlock", "State.Blocked"):
self.assertNotIn(gone, code)
def test_sliced_aio_waits_keep_linux_timeout_and_signal_semantics(self):
self.assertEqual(self.value("io_getevents_slice_host_eintr"), 1)
self.assertEqual(self.value("io_getevents_slice_deferred_signal"), 1)
self.assertEqual(self.value("io_getevents_zero_timeout"), 1)
self.assertEqual(self.value("io_getevents_timeout_returns_empty"), 1)
def test_io_setup_rollback_uses_the_generation_it_installed(self):
self.assertEqual(self.value("io_setup_rollback_keeps_reused_context"), 1)
def test_io_setup_with_unreadable_output_faults_before_dispatch(self):
self.assertEqual(self.value("io_setup_unreadable_output_faults"), 1)
def test_aio_reaps_never_expose_private_control_blocks(self):
self.assertEqual(self.value("io_getevents_unwritable_first_staged"), 1)
self.assertEqual(self.value("io_getevents_late_writable_result"), 1)
self.assertEqual(self.value("io_getevents_late_writable_object"), 1)
self.assertEqual(self.value("io_getevents_late_writable_released"), 0)
self.assertEqual(self.value("io_getevents_hidden_result"), self.efault())
self.assertEqual(self.value("io_getevents_hidden_no_private"), 1)
self.assertEqual(self.value("io_getevents_hidden_released"), 0)
self.assertEqual(self.value("io_getevents_hidden_retry"), 1)
def test_aio_key_stores_hold_the_guest_mapping(self):
self.assertEqual(self.value("io_submit_key_store_blocked_writer"), 1)
self.assertEqual(self.value("io_submit_key_store_before_unmap"), 0)
self.assertEqual(self.value("io_submit_key_store_stand_in"), 4)
self.assertEqual(self.value("io_submit_key_store_released"), 0)
def test_high_guest_stores_hold_the_mapping_without_relocations(self):
self.assertEqual(self.value("high_store_unmapped_result"), 0)
self.assertEqual(self.value("high_store_unmapped_held"), 1)
self.assertEqual(self.value("high_store_unmapped_released"), 0)
def test_guest_stores_deliver_deferred_user_signals(self):
self.assertEqual(self.value("guest_store_deferred_result"), 1)
self.assertEqual(self.value("guest_store_deferred_delivered"), 1)
self.assertEqual(self.value("guest_store_deferred_unblocked"), 1)
def test_aio_keys_follow_the_kernel_through_the_first_rejection(self):
self.assertEqual(self.value("io_submit_rejected_key_cleared"), 1)
self.assertEqual(self.value("io_submit_unreached_key"), 9)
self.assertEqual(self.value("io_submit_first_rejected_key"), 0)
self.assertEqual(self.value("io_submit_rejected_released"), 1)
def test_aio_keys_are_stored_through_the_current_guest_mapping(self):
self.assertEqual(self.value("io_submit_high_key_accepted"), 0)
self.assertEqual(self.value("io_submit_key_reused_mapped"), 1)
self.assertEqual(self.value("io_submit_key_unmapped_skipped"), 4)
self.assertEqual(self.value("io_submit_keyed_high_released"), 0)
def test_aio_rings_send_userspace_reapers_to_the_kernel(self):
self.assertEqual(self.value("io_setup_magic"), 0)
self.assertEqual(self.value("io_setup_header_kept"), 1)
self.assertEqual(self.value("io_setup_failed_magic"), 0xa10a10a1)
self.assertEqual(self.value("low_quiet_setup_magic"), 0)
def test_aio_copies_follow_completions_without_relocated_mappings(self):
self.assertEqual(self.value("low_iocb_quiet_cancel"), 1)
self.assertEqual(self.value("low_iocb_quiet_object"), 1)
self.assertEqual(self.value("low_iocb_quiet_freed"), 0)
def test_unsubmitted_aio_copies_are_released(self):
self.assertEqual(self.value("io_submit_partial_result"), 0)
self.assertEqual(self.value("io_submit_partial_count"), 1)
self.assertEqual(self.value("io_submit_partial_copies"), 1)
self.assertEqual(self.value("io_submit_partial_released"), 0)
self.assertEqual(self.value("io_submit_short_kept"), 1)
self.assertEqual(self.value("io_submit_short_first_live"), 1)
self.assertEqual(self.value("io_submit_first_bad_result"), self.efault())
self.assertEqual(self.value("io_submit_first_bad_copies"), 0)
def test_destroyed_contexts_release_their_copies(self):
self.assertEqual(self.value("io_destroy_released"), 1)
self.assertEqual(self.value("io_destroy_failed_kept"), 1)
self.assertEqual(self.value("io_destroy_other_released"), 0)
def test_read_only_control_blocks_fault_like_the_kernel(self):
self.assertEqual(self.value("io_submit_read_only_result"), 0)
self.assertEqual(self.value("io_submit_read_only_count"), 1)
self.assertEqual(self.value("io_submit_read_only_passed"), 1)
self.assertEqual(self.value("io_submit_read_only_copies"), 0)
self.assertEqual(self.value("io_submit_read_only_after_copy"), 1)
self.assertEqual(self.value("io_submit_read_only_after_copy_released"), 0)
self.assertEqual(self.value("io_submit_read_only_native_result"), 0)
self.assertEqual(self.value("io_submit_read_only_native_block"), 1)
self.assertEqual(self.value("io_submit_read_only_native_copies"), 0)
def test_aio_copies_are_bounded(self):
self.assertEqual(self.value("io_submit_crowded_result"), (1 << 64) - 11)
self.assertEqual(self.value("io_submit_last_copy_result"), 0)
self.assertEqual(self.value("io_submit_last_copy_count"), 1)
self.assertEqual(self.value("io_submit_last_copy_slot"), 1)
def test_move_pages_translates_own_page_addresses(self):
self.assertEqual(self.value("move_pages_result"), 0)
self.assertEqual(self.value("move_pages_copied"), 1)
self.assertEqual(self.value("move_pages_first"), 16)
self.assertEqual(self.value("move_pages_second"), 1)
self.assertEqual(self.value("move_pages_guest_list"), 16)
self.assertEqual(self.value("move_pages_remote_result"), 0)
self.assertEqual(self.value("move_pages_remote_kept"), 1)
def test_futex_waiters_translate_each_address(self):
self.assertEqual(self.value("futex_waitv_result"), 0)
self.assertEqual(self.value("futex_waitv_copied"), 1)
self.assertEqual(self.value("futex_waitv_first"), 64)
self.assertEqual(self.value("futex_waitv_second"), 1)
self.assertEqual(self.value("futex_waitv_guest"), 64)
self.assertEqual(self.value("futex_waitv_split_result"), self.efault())
self.assertEqual(self.value("futex_requeue_result"), 0)
self.assertEqual(self.value("futex_requeue_second"), 128)
def test_counts_follow_the_kernel_argument_width(self):
self.assertEqual(self.value("getgroups_wide_result"), 0)
self.assertEqual(self.value("getgroups_wide_list"), 4096 - 4)
self.assertEqual(self.value("getgroups_negative_result"), 0)
self.assertEqual(self.value("getgroups_large_result"), self.efault())
self.assertEqual(self.value("poll_wide_result"), 0)
self.assertEqual(self.value("epoll_negative_result"), 0)
self.assertEqual(self.value("io_getevents_negative_result"), 0)
def test_message_batches_keep_the_translated_prefix(self):
self.assertEqual(self.value("sendmmsg_prefix_result"), 0)
self.assertEqual(self.value("sendmmsg_prefix_count"), 1)
self.assertEqual(self.value("sendmmsg_first_bad_result"), self.efault())
self.assertEqual(self.value("sendmmsg_headers_apart_result"), 0)
self.assertEqual(self.value("sendmmsg_headers_apart_count"), 1)
self.assertEqual(self.value("sendmmsg_headers_apart_first"), 11)
self.assertEqual(self.value("sendmmsg_headers_apart_second"), 22)
self.assertEqual(self.value("sendmmsg_headers_apart_finish"), 2)
self.assertEqual(self.value("sendmmsg_headers_apart_sent"), 22)
self.assertEqual(self.value("sendmmsg_headers_apart_lengths"), 0x0B16)
def test_message_results_return_through_the_current_guest_mapping(self):
self.assertEqual(self.value("moved_result"), 0)
self.assertEqual(self.value("moved_unrelated_placed"), 1)
self.assertEqual(self.value("moved_finish"), 1)
self.assertEqual(self.value("moved_unrelated_length"), 0)
self.assertEqual(self.value("moved_new_length"), 32)
def test_unwritable_message_lengths_are_not_counted(self):
self.assertEqual(self.value("sealed_result"), 0)
self.assertEqual(self.value("sealed_submitted"), 1)
self.assertEqual(self.value("sealed_finish"), 1)
self.assertEqual(self.value("sealed_later_sends"), 1)
self.assertEqual(self.value("sealed_first_length"), 32)
self.assertEqual(self.value("sealed_second_length"), 0)
self.assertEqual(self.value("sealed_third_length"), 0)
self.assertEqual(self.value("sealed_only_result"), 0)
self.assertEqual(self.value("sealed_only_finish"), self.efault())
def test_structures_are_sized_by_their_own_size_fields(self):
self.assertEqual(self.value("perf_attr_fits_result"), 0)
self.assertEqual(self.value("perf_attr_default_result"), 0)
self.assertEqual(self.value("perf_attr_large_result"), self.efault())
self.assertEqual(self.value("sched_attr_fits_result"), 0)
self.assertEqual(self.value("sched_attr_large_result"), self.efault())
self.assertEqual(self.value("capget_v1_result"), 0)
self.assertEqual(self.value("capget_v1_data"), 3 * 4096 - 12)
self.assertEqual(self.value("capget_v3_result"), self.efault())
self.assertEqual(self.value("capset_v3_result"), self.efault())
self.assertEqual(self.value("name_to_handle_fits_result"), 0)
self.assertEqual(self.value("name_to_handle_large_result"), self.efault())
self.assertEqual(self.value("open_by_handle_fits_result"), 0)
self.assertEqual(self.value("open_by_handle_large_result"), self.efault())
self.assertEqual(self.value("name_to_handle_header_split_result"), self.efault())
self.assertEqual(self.value("open_by_handle_header_split_result"), self.efault())
self.assertEqual(self.value("open_by_handle_header_fits_result"), 0)
self.assertEqual(self.value("statmount_fits_result"), 0)
self.assertEqual(self.value("statmount_large_result"), self.efault())
self.assertEqual(self.value("landlock_path_result"), 0)
self.assertEqual(self.value("landlock_port_result"), self.efault())
def test_capability_calls_use_one_private_header(self):
self.assertEqual(self.value("capget_copy_result"), 0)
self.assertEqual(self.value("capget_copy_private"), 1)
self.assertEqual(self.value("capget_copy_version"), 0x19980330)
self.assertEqual(self.value("capget_copy_finish"), 0)
self.assertEqual(self.value("capget_copy_guest_version"), 0x20080522)
self.assertEqual(self.value("capget_invalid_result"), 0)
self.assertEqual(self.value("capget_invalid_finish"), (1 << 64) - 22)
self.assertEqual(self.value("capget_invalid_version"), 0x20080522)
def test_capability_header_write_back_faults(self):
self.assertEqual(self.value("capget_sealed_result"), 0)
self.assertEqual(self.value("capget_sealed_finish"), self.efault())
self.assertEqual(self.value("capget_sealed_version"), 0x1234)
def test_short_sends_end_the_message_batch(self):
self.assertEqual(self.value("sendmmsg_short_first_result"), 0)
self.assertEqual(self.value("sendmmsg_short_first_finish"), 1)
self.assertEqual(self.value("sendmmsg_short_first_sends"), 0)
self.assertEqual(self.value("sendmmsg_short_first_lengths"), 0x0A0000)
self.assertEqual(self.value("sendmmsg_short_second_result"), 0)
self.assertEqual(self.value("sendmmsg_short_second_finish"), 2)
self.assertEqual(self.value("sendmmsg_short_second_sends"), 1)
self.assertEqual(self.value("sendmmsg_short_second_lengths"), 0x200500)
def test_short_sends_compare_the_lengths_given_to_the_kernel(self):
self.assertEqual(self.value("sendmmsg_grown_result"), 0)
self.assertEqual(self.value("sendmmsg_grown_private"), 1)
self.assertEqual(self.value("sendmmsg_grown_finish"), 3)
self.assertEqual(self.value("sendmmsg_grown_sends"), 2)
self.assertEqual(self.value("sendmmsg_grown_lengths"), 0x201010)
self.assertEqual(self.value("sendmmsg_vanished_result"), 0)
self.assertEqual(self.value("sendmmsg_vanished_finish"), 2)
self.assertEqual(self.value("sendmmsg_vanished_sends"), 1)
self.assertEqual(self.value("sendmmsg_vanished_unmapped"), 1)
self.assertEqual(self.value("sendmmsg_vanished_lengths"), 0x200500)
def test_message_batches_pin_their_socket(self):
self.assertEqual(self.value("sendmmsg_short_second_submitted"), 1)
self.assertEqual(self.value("sendmmsg_pinned_distinct"), 1)
self.assertEqual(self.value("sendmmsg_pinned_dispatched"), 1)
self.assertEqual(self.value("sendmmsg_pinned_used"), 1)
self.assertEqual(self.value("sendmmsg_pinned_closed"), 1)
self.assertEqual(self.value("sendmmsg_error_finish"), (1 << 64) - 11)
self.assertEqual(self.value("sendmmsg_error_closed"), 1)
def test_batches_without_a_spare_descriptor_still_send_one_message_at_a_time(self):
self.assertEqual(self.value("sendmmsg_emfile_result"), 0)
self.assertEqual(self.value("sendmmsg_emfile_submitted"), 1)
self.assertEqual(self.value("sendmmsg_emfile_original"), 1)
self.assertEqual(self.value("sendmmsg_emfile_first_only"), 0)
self.assertEqual(self.value("sendmmsg_emfile_finish"), 1)
self.assertEqual(self.value("sendmmsg_emfile_received"), 0x41)
self.assertEqual(self.value("sendmmsg_emfile_lengths"), 0x040000)
def test_batches_without_a_spare_descriptor_stop_at_an_unwritable_length(self):
self.assertEqual(self.value("sendmmsg_emfile_readonly_result"), 0)
self.assertEqual(self.value("sendmmsg_emfile_readonly_submitted"), 1)
self.assertEqual(self.value("sendmmsg_emfile_readonly_finish"), 1)
self.assertEqual(self.value("sendmmsg_emfile_readonly_received"), 0x41)
self.assertEqual(self.value("sendmmsg_emfile_readonly_lengths"), 0x040000)
self.assertEqual(self.value("sendmmsg_emfile_only_result"), 0)
self.assertEqual(self.value("sendmmsg_emfile_only_finish"), self.efault())
self.assertEqual(self.value("sendmmsg_emfile_only_received"), 0x42)
def test_unreadable_later_vectors_end_the_prepared_batch(self):
self.assertEqual(self.value("sendmmsg_unreadable_middle_result"), 0)
self.assertEqual(self.value("sendmmsg_unreadable_middle_submitted"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_middle_queued"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_middle_finish"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_middle_received"), 0x41)
self.assertEqual(self.value("sendmmsg_unreadable_middle_lengths"), 0x040000)
self.assertEqual(self.value("sendmmsg_unreadable_last_result"), 0)
self.assertEqual(self.value("sendmmsg_unreadable_last_submitted"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_last_queued"), 2)
self.assertEqual(self.value("sendmmsg_unreadable_last_pinned"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_last_finish"), 2)
self.assertEqual(self.value("sendmmsg_unreadable_last_received"), 0x4142)
self.assertEqual(self.value("sendmmsg_unreadable_last_lengths"), 0x040400)
def test_an_unreadable_first_vector_reaches_the_kernel_natively(self):
self.assertEqual(self.value("sendmmsg_unreadable_first_result"), 0)
self.assertEqual(self.value("sendmmsg_unreadable_first_native"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_first_error"), 1)
self.assertEqual(self.value("sendmmsg_unreadable_first_received"), 0)
def test_received_fields_follow_the_kernel_write_order(self):
self.assertEqual(self.value("recvmsg_nameless_result"), 0)
self.assertEqual(self.value("recvmsg_nameless_finish"), 64)
self.assertEqual(self.value("recvmsg_nameless_flags"), 0x20)
self.assertEqual(self.value("recvmsg_named_result"), 0)
self.assertEqual(self.value("recvmsg_named_private"), 1)
self.assertEqual(self.value("recvmsg_named_name_kept"), 1)
self.assertEqual(self.value("recvmsg_named_finish"), self.efault())
self.assertEqual(self.value("recvmsg_flags_first_result"), 0)
self.assertEqual(self.value("recvmsg_flags_first_finish"), self.efault())
self.assertEqual(self.value("recvmsg_flags_first_controllen"), 99)
def test_newer_syscalls_have_fallback_numbers(self):
names = set(re.findall(r"SYSCALL_x64_(\w+)", "\n".join(added_lines(PATCH.read_text(), SOURCE))))
headers = [Path("/usr/include/x86_64-linux-gnu/asm/unistd_64.h"), Path("/usr/include/asm/unistd_64.h")]
header = next((path for path in headers if path.exists()), None)
if header is None:
self.skipTest("needs x86-64 syscall headers")
numbers = {name: int(number) for name, number in re.findall(r"#define __NR_(\w+) (\d+)", header.read_text())}
for name in sorted(names):
number = numbers.get(KERNEL_NAMES.get(name, name))
if number is not None and number > OLDEST_HEADERS_LAST_SYSCALL:
self.assertEqual(NEWER_SYSCALLS.get(name), number, name)
def test_new_mappings_merge_with_matching_neighbours(self):
self.assertEqual(self.value("map_result"), 0)
self.assertEqual(self.value("map_unmap"), 0)
self.assertEqual(self.value("map_again"), 4096)
self.assertEqual(self.value("map_merged_size"), 2 * 4096)
self.assertEqual(self.value("map_merged_entries"), 0)
self.assertEqual(self.value("map_unmap_again"), 0)
self.assertEqual(self.value("map_readonly"), 4096)
self.assertEqual(self.value("map_readonly_size"), 4096)
self.assertEqual(self.value("map_readonly_entries"), 1)
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_exclusive_pairs_become_compare_and_swap(self):
self.assertEqual(self.value("ldxr_value"), 5)
self.assertEqual([self.value("stxr_status"), self.value("stxr_memory")], [0, 9])
self.assertEqual([self.value("contended_status"), self.value("contended_memory")], [1, 11])
self.assertEqual([self.value("unarmed_status"), self.value("unarmed_memory")], [1, 11])
self.assertEqual([self.value("ldxp_low"), self.value("ldxp_high")], [1, 2])
self.assertEqual([self.value("stxp_status"), self.value("stxp_memory")], [0, 7 * 16 + 8])
self.assertEqual(self.value("ldxrb_value"), 0x88)
self.assertEqual([self.value("stlxrb_status"), self.value("stlxrb_memory")], [0, 0x11223344556677AB])
self.assertEqual(self.value("misaligned"), 0)
def test_every_host_relocates_high_mappings(self):
text = PATCH.read_text()
self.assertNotIn("SetHostAtomics", text)
self.assertNotIn("HostAtomics", text)
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 \(IsExclusive\(Insn\)\) \{\n\+ if \(Parts != 1 \|\| !ExclusiveReachable\(Insn, Pieces\[0\]\.Prot\) \|\|\n\+ !EmulateExclusive\(")
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\);")
fault = block(added_lines(text, SOURCE), "bool HandleFault(")
self.assertIn("for (auto FaultBase = FEXCore::AlignDown(Pieces[i].Guest, FEXCore::Utils::FEX_PAGE_SIZE); FaultBase <= Last;", fault)
def access(self, name):
if not self.value(f"decode_{name}_known"):
return None
offset = self.value(f"decode_{name}_offset")
if offset >= 1 << 63:
offset -= 1 << 64
return offset, self.value(f"decode_{name}_size"), self.value(f"decode_{name}_plain")
def test_fault_accesses_decode_their_whole_range(self):
self.assertEqual(self.access("str_x_imm"), (8, 8, 1))
self.assertEqual(self.access("ldr_x_pre"), (-4, 8, 1))
self.assertEqual(self.access("ldr_x_post"), (0, 8, 1))
self.assertEqual(self.access("stur_x"), (-4, 8, 1))
self.assertEqual(self.access("ldr_w_lsl"), (0xfffffffe << 2, 4, 1))
self.assertEqual(self.access("ldr_w_sxtw"), (-2, 4, 1))
self.assertEqual(self.access("ldr_w_uxtw"), (0xfffffffe, 4, 1))
self.assertIsNone(self.access("ldr_w_reserved"))
self.assertEqual(self.access("stp_x"), (16, 16, 1))
self.assertEqual(self.access("ldp_w_negative"), (-8, 8, 1))
self.assertEqual(self.access("ldp_q_post"), (0, 32, 1))
self.assertEqual(self.access("str_q"), (16, 16, 1))
self.assertEqual(self.access("ld1_four"), (0, 64, 1))
self.assertEqual(self.access("st1_post"), (0, 16, 1))
self.assertEqual(self.access("ld1_lane"), (0, 4, 1))
self.assertEqual(self.access("ld4r"), (0, 16, 1))
self.assertEqual(self.access("ldadd"), (0, 8, 0))
self.assertEqual(self.access("ldar"), (0, 8, 0))
self.assertEqual(self.access("casp"), (0, 16, 0))
self.assertEqual(self.access("ldxp"), (0, 16, 0))
self.assertEqual(self.access("ldapur"), (-4, 4, 0))
self.assertIsNone(self.access("ldraa"))
def test_accesses_across_separate_backings_reach_each_backing(self):
self.assertEqual(self.value("split_access_parts"), 2)
self.assertEqual(self.value("split_access_first"), 4096 - 4)
self.assertEqual(self.value("split_access_second"), 2 * 4096)
self.assertEqual(self.value("split_access_sizes"), 0x44)
self.assertEqual(self.value("split_access_guests"), 0x11)
self.assertEqual(self.value("split_access_contiguous"), 0)
self.assertEqual(self.value("split_access_store_reachable"), 1)
self.assertEqual(self.value("split_store_low"), 0x55667788)
self.assertEqual(self.value("split_store_high"), 0x11223344)
self.assertEqual(self.value("split_store_neighbour"), 0xeeeeeeee)
self.assertEqual(self.value("split_load_value"), 0x1122334455667788)
self.assertEqual(self.value("split_readonly_store"), 0)
self.assertEqual(self.value("split_readonly_load"), 1)
self.assertEqual(self.value("split_none_load"), 0)
self.assertEqual(self.value("split_unmapped_parts"), 0)
self.assertEqual(self.value("split_inside_parts"), 1)
self.assertEqual(self.value("split_inside_host"), 16)
self.assertEqual(self.value("joined_access_parts"), 2)
self.assertEqual(self.value("joined_access_contiguous"), 1)
self.assertEqual(self.value("joined_access_delta"), 1)
def test_fault_replay_translates_the_whole_access(self):
lines = added_lines(PATCH.read_text(), SOURCE)
fault = block(lines, "bool HandleFault(")
self.assertNotIn("View.Host - View.Guest", fault)
self.assertIn("const auto Parts = ReadConsistent([&] { return PlanAccessLocked(Address, Size, Pieces); });", fault)
self.assertIn("if (Bounced && (!PiecesReachable(Pieces, Parts, Write) || (!Plain && !IsOrderedAccess(Insn)))) {", fault)
self.assertIn("Failed = CopyPieces(Window, Trap.Pieces, Parts, true);", fault)
self.assertIn("Trap.Delta = reinterpret_cast<uint64_t>(Window) - Address;", fault)
self.assertIn("const auto Failed = CopyPieces(Trap.Bounce + Trap.BounceOffset, Trap.Pieces, Trap.Parts, false);", block(lines, "bool HandleTrap("))
def test_split_ordered_accesses_keep_their_ordering(self):
self.assertEqual(self.value("ordered_load_parts"), 2)
self.assertEqual(self.value("ordered_load_value"), 0x1122334455667788)
self.assertEqual(self.value("ordered_store_parts"), 2)
self.assertEqual(self.value("ordered_store_low"), 0xb5b6b7b8)
self.assertEqual(self.value("ordered_store_high"), 0xa1a2a3a4)
self.assertEqual(self.value("ordered_signed_parts"), 1)
self.assertEqual(self.value("ordered_signed_value"), 0xffffffffa3a4b5b6)
self.assertEqual(self.value("ordered_kinds"), 0x111110)
self.assertEqual(self.value("ordered_atomics"), 0)
self.assertEqual(self.value("extend_signed_half_w"), 0xffff8001)
self.assertEqual(self.value("extend_signed_half_x"), 0xffffffffffff8001)
self.assertEqual(self.value("extend_unsigned_byte"), 0x80)
self.assertEqual(self.value("extend_ldar"), 0x80000000)
fault = block(added_lines(PATCH.read_text(), SOURCE), "bool HandleFault(")
self.assertIn("Failed = EmulateOrdered(Insn, Pieces, Parts, UContext);", fault)
self.assertLess(fault.index("if (IsExclusive(Insn)) {"), fault.index("EmulateOrdered("))
def test_loads_are_never_classified_as_writes(self):
self.assertEqual(self.value("write_loads"), 0)
self.assertEqual(self.value("write_stores"), 0x1111)
def test_bounce_faults_are_delivered_at_the_guest_instruction(self):
self.assertEqual(self.value("ordered_fault_parts"), 1)
self.assertEqual(self.value("ordered_fault_untouched"), 0x77)
self.assertEqual(self.value("gather_fault_piece"), 1)
self.assertEqual(self.value("scatter_fault_piece"), 1)
self.assertEqual(self.value("gather_whole"), 2)
self.assertEqual(self.value("probe_instruction"), 0x39400210)
self.assertEqual(self.value("probe_instruction_low"), 0x39400042)
text = PATCH.read_text()
lines = added_lines(text, SOURCE)
fault = block(lines, "bool HandleFault(")
self.assertIn("ArmProbe(", fault)
trap = block(lines, "bool HandleTrap(")
self.assertIn("ArmProbe(", trap)
self.assertIn("Trap.Base, Trap.BaseBefore", trap)
bus = block(lines, "bool HandleBusFault(")
self.assertIn("RedeliverFromTrap(", bus)
self.assertIn("IsFaultLocation(", bus)
self.assertIn("si_code <= SI_USER", bus)
redeliver = block(lines, "void RedeliverFromTrap(")
self.assertIn("Trap.ResumePC - 4", redeliver)
self.assertIn("- Trap.Delta", redeliver)
syscalls = added_lines(text, "Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp")
self.assertIn(" SignalDelegation->RegisterHostSignalHandler(SIGBUS, FEX::HLE::GuestHighMemory::HandleBusFault, true);", syscalls)
def test_mappings_stay_locked_until_the_scatter_finishes(self):
self.assertEqual(self.value("hold_kept_held"), 1)
self.assertEqual(self.value("hold_blocks_writer"), 0)
self.assertEqual(self.value("hold_released"), 0x10)
self.assertEqual(self.value("hold_scoped"), 0x10)
text = PATCH.read_text()
lines = added_lines(text, SOURCE)
fault = block(lines, "bool HandleFault(")
hold = fault.index("MappingHold Hold {Trap.Mappings};")
self.assertLess(hold, fault.index("ReadConsistent([&] { return PlanAccessLocked(Address, Size, Pieces); })"))
self.assertIn("Hold.Keep();", fault)
self.assertIn("ReleaseMappings(Trap.Mappings);", block(lines, "void LeaveTrap("))
smc = added_lines(text, "Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp")
self.assertIn(" if (FEX::HLE::GuestHighMemory::Contains(FaultAddress) || FEX::HLE::GuestHighMemory::HoldsMappings(Thread)) {", smc)
def test_user_faults_skip_replay(self):
fault = block(added_lines(PATCH.read_text(), SOURCE), "bool HandleFault(")
check = fault.index("SigInfo->si_code <= SI_USER")
self.assertLess(fault.index("DeferWhileHeld("), check)
self.assertLess(check, fault.index("MappingHold Hold {Trap.Mappings};"))
def test_user_signals_wait_until_the_mappings_are_released(self):
self.assertEqual(self.value("defer_unheld"), 0)
self.assertEqual(self.value("defer_held_mask"), 0x001)
self.assertEqual(self.value("defer_kinds"), 0x100)
self.assertEqual(self.value("defer_not_run_while_held"), 0)
self.assertEqual(self.value("defer_requeued"), 1 << (signal.SIGTRAP - 1))
self.assertEqual(self.value("defer_after_release"), 0)
self.assertEqual(self.value("defer_lock_free"), 1)
self.assertEqual(self.value("defer_delivered"), 1)
self.assertEqual(self.value("defer_info"), ((-1) & 0xffffffff) * 0x10000 + 0x1234)
self.assertEqual(self.value("defer_scoped_pending"), 1)
self.assertEqual(self.value("defer_scoped_blocked"), 1)
self.assertEqual(self.value("defer_scoped_delivered"), 2 * 0x10000 + 0x5678)
lines = added_lines(PATCH.read_text(), SOURCE)
for signature in ("bool HandleFault(", "bool HandleBusFault(", "bool HandleTrap("):
handler = block(lines, signature)
self.assertIn("if (DeferWhileHeld(Trap.Mappings, Signal, SigInfo)) {", handler)
self.assertLess(handler.index("DeferWhileHeld("), handler.index("Trap.Active"))
def test_only_the_trampoline_breakpoint_completes_a_replay(self):
trap = block(added_lines(PATCH.read_text(), SOURCE), "bool HandleTrap(")
self.assertIn("SigInfo->si_code != TRAP_BRKPT", trap)
self.assertIn("reinterpret_cast<uint64_t>(Trap.Code) + 4", trap)
self.assertLess(trap.index("TRAP_BRKPT"), trap.index("if (Trap.Probe) {"))
def test_the_harness_is_bounded_by_a_timeout(self):
self.assertIn(" alarm(HARNESS_SECONDS);", MAIN)
self.assertIn("timeout=HARNESS_SECONDS + 30", Path(__file__).read_text())
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_full_retired_list_keeps_the_mapping(self):
self.assertEqual(self.value("retire_full_unmap"), (1 << 64) - 12)
self.assertEqual(self.value("retire_full_tracked"), 1)
self.assertEqual(self.value("retire_full_host_held"), 1)
self.assertEqual(self.value("retire_full_after"), 0)
self.assertEqual(self.value("retire_full_gone"), 1)
def test_failed_host_unmap_is_released_later(self):
self.assertEqual(self.value("retire_unmap"), 0)
self.assertEqual(self.value("retire_pending"), 1)
self.assertEqual(self.value("retire_untracked"), 1)
self.assertEqual(self.value("retire_host_held"), 1)
self.assertEqual(self.value("retire_second"), 0)
self.assertEqual(self.value("retire_released"), 0)
self.assertEqual(self.value("retire_host_gone"), 1)
self.assertEqual(self.value("retire_rest_gone"), 1)
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()