Files
reims-vgpu/guest/bundle/tests/serializer_tests.cpp
T
Anees Iqbal ad831c411e 🐎 Post the Metal processes' object lifecycle on ring 0
Each process's creates and destroys now reach the host on the control ring,
which the accelerator kext posts for it under the framebuffer's ring lock, in
place of a device queue per process and the BAR 0 mailbox. Ring 0 keeps one
producer, the kexts, and one consumer, the host's control thread, so the
lifecycle of every process is in one order with the display commands.

The bundle hands each message to the kext by a user-client call (selector
0x105, struct in). The kext checks the object is in the caller's context,
stamps the seqno and posts it; for a pipeline create it waits for the
reflection, which the work loop routes by seqno, and hands it back as struct
out. QUEUE_CREATE (selector 0x103) is posted and answered with COMPLETE once
the host has the queue's rings. At a close the kext posts each queue's
OBJECT_DESTROY, then CONTEXT_CLOSE, which the host answers once the context's
objects are dropped, then frees the blocks.

The host carries out lifecycle messages on the control thread with no ring
held, and a command buffer waits until every ring-0 message published before
its queue's thread took it is carried out. The Host trait's queue_message
becomes stage3_message, and its poster (CompletionPoster) also targets the
control completion ring.
2026-11-05 21:58:30 -08:00

769 lines
28 KiB
C++

/*
* serializer_tests: the reims-graphics guest serialiser's self-contained check,
* run on the Mac (guest/bundle/Makefile `test`). It builds a plain-buffer region,
* a ring writer over it, and a serialiser, posts every message the slice covers,
* and reads each back with a minimal host-side consumer (the mirror of
* crates/reims-graphics/src/ring.rs), asserting the type, size and fields on the
* wire. No Metal, no device: this validates the serialiser's bytes alone.
*
* Exits 0 and prints a one-line summary when every check passes; aborts on the
* first failure.
*/
#include <atomic>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <vector>
#include "RgfxCaps.hpp"
#include "RgfxEncoder.hpp"
#include "RgfxObjectModel.hpp"
#include "RgfxReplyReader.hpp"
#include "RgfxRingWriter.hpp"
#include "RgfxSerializer.hpp"
#include "reims_graphics_wire.h"
#include "rgfx_test_ring.hpp" // CHECK, g_checks, TestRing, expectMessage
namespace {
void test_id_space()
{
RgfxIdSpace ids;
CHECK(ids.allocObjId() == 1);
CHECK(ids.allocObjId() == 2);
CHECK(ids.allocResourceId() == 1);
CHECK(ids.allocResourceId() == 2);
uint64_t a = ids.allocAddress(100, 256);
uint64_t b = ids.allocAddress(1, 4096);
CHECK(a >= RgfxIdSpace::kDefaultAddressBase);
CHECK((a % 256) == 0);
CHECK((b % 4096) == 0);
CHECK(b >= a + 100); // disjoint ranges, b after a
}
void test_caps()
{
RgfxCaps caps;
// A bad version is refused and leaves the caps invalid.
RgfxDeviceInfo bad = {};
bad.version = RGFX_DEVICE_INFO_VERSION + 1;
CHECK(!caps.load(bad));
CHECK(!caps.valid());
RgfxDeviceInfo info = {};
info.version = RGFX_DEVICE_INFO_VERSION;
info.registry_id = 0xabcd;
info.gpu_core_count = 16;
info.max_threads_per_threadgroup[0] = 1024;
info.max_threads_per_threadgroup[1] = 512;
info.max_threads_per_threadgroup[2] = 64;
info.max_vertex_amplification_count = 2;
info.families[kRgfxFamilyApple5] = 1;
info.families[kRgfxFamilyMinus1009] = 1; // last by position
info.sample_counts[0] = 1; // count 1
info.sample_counts[2] = 1; // count 4
info.primitive_types[3] = 1;
info.write_rounding_modes[1] = 1; // mode 2
info.limits[kRgfxLimitDeviceLinearTextureAlignmentBytes] = 64;
info.limits[kRgfxLimitMaxViewportCount] = 16; // last by position
info.flags[kRgfxFlagAreRasterOrderGroupsSupported] = 1; // first by position
info.flags[kRgfxFlagSupportsTileShaders] = 1; // last by position
const char *nm = "Test GPU";
info.name_len = static_cast<uint32_t>(std::strlen(nm));
std::memcpy(info.name, nm, info.name_len);
CHECK(caps.load(info));
CHECK(caps.valid());
CHECK(caps.registryId() == 0xabcd);
CHECK(caps.gpuCoreCount() == 16);
CHECK(caps.maxThreadsPerThreadgroup(0) == 1024);
CHECK(caps.maxThreadsPerThreadgroup(2) == 64);
CHECK(caps.maxVertexAmplificationCount() == 2);
CHECK(caps.supportsFamily(kRgfxFamilyApple5));
CHECK(caps.supportsFamily(kRgfxFamilyMinus1009));
CHECK(!caps.supportsFamily(kRgfxFamilyApple6));
CHECK(caps.supportsSampleCount(1));
CHECK(caps.supportsSampleCount(4));
CHECK(!caps.supportsSampleCount(2));
CHECK(!caps.supportsSampleCount(8));
CHECK(!caps.supportsSampleCount(3)); // not a power the blob holds
CHECK(caps.supportsPrimitiveType(3));
CHECK(!caps.supportsPrimitiveType(0));
CHECK(caps.supportsWriteRoundingMode(2));
CHECK(!caps.supportsWriteRoundingMode(1));
CHECK(caps.limit(kRgfxLimitDeviceLinearTextureAlignmentBytes) == 64);
CHECK(caps.limit(kRgfxLimitMaxViewportCount) == 16);
CHECK(caps.flag(kRgfxFlagAreRasterOrderGroupsSupported));
CHECK(caps.flag(kRgfxFlagSupportsTileShaders));
CHECK(!caps.flag(kRgfxFlagSupportsImageBlocks));
CHECK(std::strcmp(caps.name(), "Test GPU") == 0);
}
void test_lifecycle_messages()
{
TestRing ring(0x8000);
ring.setConsumerIdle(1); // the host is idle, so each post rings the doorbell
int before = TestRing::doorbells.load();
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
// Queue.
RgfxCreated q = ser.createQueue(0x20000, 0x30000, 0x1000, 0x1000, 2, 1);
CHECK(q.posted);
CHECK(q.obj_id == 1);
CHECK(q.seqno == 1); // the first message on the ring
auto qm = expectMessage<RgfxQueueCreate>(ring, RGFX_CMD_QUEUE_CREATE);
CHECK(qm.header.seqno == 1);
CHECK(qm.obj_id == 1);
CHECK(qm.submit_offset == 0x20000 && qm.complete_offset == 0x30000);
CHECK(qm.submit_data_size == 0x1000 && qm.complete_data_size == 0x1000);
CHECK(qm.priority == 2 && qm.vector == 1);
// Heap (device) and heap over host memory.
RgfxCreated h = ser.createHeap(0x10000, 0, 1 /*Placement*/, 4096);
CHECK(h.posted && (h.gpu_address % 4096) == 0);
auto hm = expectMessage<RgfxHeapCreate>(ring, RGFX_CMD_HEAP_CREATE);
CHECK(hm.obj_id == h.obj_id && hm.gpu_address == h.gpu_address);
CHECK(hm.size_bytes == 0x10000 && hm.heap_type == 1);
RgfxCreated hh = ser.createHeapOverHostMemory(0x2000, 0, 0, 0x40000);
CHECK(hh.posted);
auto hhm = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY);
CHECK(hhm.obj_id == hh.obj_id && hhm.region_offset == 0x40000 && hhm.size_bytes == 0x2000);
// Buffers: device, over host memory, at offset in a heap.
RgfxCreated b = ser.createBuffer(0x1000, 0);
CHECK(b.posted && b.gpu_address != 0);
auto bm = expectMessage<RgfxBufferCreate>(ring, RGFX_CMD_BUFFER_CREATE);
CHECK(bm.obj_id == b.obj_id && bm.gpu_address == b.gpu_address && bm.length == 0x1000);
CHECK(bm.reserved_2c == 0);
RgfxCreated bh = ser.createBufferOverHostMemory(0x800, 0, 0x50000);
CHECK(bh.posted);
auto bhm = expectMessage<RgfxBufferOverHostMemory>(ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(bhm.obj_id == bh.obj_id && bhm.region_offset == 0x50000 && bhm.length == 0x800);
RgfxCreated bo = ser.createBufferAtOffset(h.obj_id, 0x100, 0x200, 0);
CHECK(bo.posted && bo.gpu_address == 0); // derived host-side from the heap
auto bom = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(bom.obj_id == bo.obj_id && bom.heap_obj_id == h.obj_id);
CHECK(bom.offset == 0x100 && bom.length == 0x200);
// Textures: device-placed and heap-placed and from a buffer.
RgfxTextureDescriptor desc = {};
desc.pixel_format = 80; // MTLPixelFormatBGRA8Unorm
desc.texture_type = 2; // MTLTextureType2D
desc.width = 1920;
desc.height = 1080;
desc.depth = 1;
desc.mipmap_level_count = 1;
desc.array_length = 1;
desc.sample_count = 1;
desc.usage = 4; // MTLTextureUsageRenderTarget
RgfxCreated t = ser.createTexture(desc);
CHECK(t.posted && t.resource_id != 0 && t.gpu_address != 0);
auto tm = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(tm.obj_id == t.obj_id && tm.resource_id == t.resource_id);
CHECK(tm.gpu_address == t.gpu_address && tm.heap_obj_id == 0);
CHECK(tm.desc.width == 1920 && tm.desc.height == 1080 && tm.desc.pixel_format == 80);
RgfxCreated th = ser.createTexture(desc, h.obj_id, 0x400);
CHECK(th.posted && th.gpu_address == 0); // heap-placed: no device address
auto thm = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(thm.heap_obj_id == h.obj_id && thm.heap_offset == 0x400);
RgfxCreated tb = ser.createTextureFromBuffer(b.obj_id, 0x10, 7680, desc);
CHECK(tb.posted);
auto tbm = expectMessage<RgfxTextureFromBuffer>(ring, RGFX_CMD_TEXTURE_FROM_BUFFER);
CHECK(tbm.buffer_obj_id == b.obj_id && tbm.offset == 0x10 && tbm.bytes_per_row == 7680);
CHECK(tbm.resource_id == tb.resource_id && tbm.desc.width == 1920);
// Sampler: the float clamps are stored as bits.
RgfxSamplerParams sp = {};
sp.min_filter = 1;
sp.mag_filter = 1;
sp.mip_filter = 1;
sp.max_anisotropy = 4;
sp.lod_min_clamp = 0.0f;
sp.lod_max_clamp = 7.5f;
sp.flags = 0x1;
RgfxCreated s = ser.createSampler(sp);
CHECK(s.posted);
auto sm = expectMessage<RgfxSamplerCreate>(ring, RGFX_CMD_SAMPLER_CREATE);
CHECK(sm.obj_id == s.obj_id && sm.max_anisotropy == 4 && sm.flags == 0x1);
float lodMax;
std::memcpy(&lodMax, &sm.lod_max_clamp_bits, 4);
CHECK(lodMax == 7.5f);
// Depth/stencil.
RgfxStencilDescriptor front = {};
front.stencil_compare = 7;
front.read_mask = 0xff;
front.write_mask = 0xff;
RgfxStencilDescriptor back = {};
RgfxCreated ds = ser.createDepthStencil(4 /*compare*/, true, front, back);
CHECK(ds.posted);
auto dsm = expectMessage<RgfxDepthStencilCreate>(ring, RGFX_CMD_DEPTH_STENCIL_CREATE);
CHECK(dsm.obj_id == ds.obj_id && dsm.depth_compare == 4 && dsm.depth_write_enabled == 1);
CHECK(dsm.front.stencil_compare == 7 && dsm.front.read_mask == 0xff);
// Sync objects.
RgfxCreated ev = ser.createEvent();
CHECK(ev.posted);
auto evm = expectMessage<RgfxObjectCreate>(ring, RGFX_CMD_EVENT_CREATE);
CHECK(evm.obj_id == ev.obj_id);
RgfxCreated fe = ser.createFence();
CHECK(fe.posted);
auto fem = expectMessage<RgfxObjectCreate>(ring, RGFX_CMD_FENCE_CREATE);
CHECK(fem.obj_id == fe.obj_id);
RgfxCreated se = ser.createSharedEvent(42);
CHECK(se.posted);
auto sem = expectMessage<RgfxSharedEventCreate>(ring, RGFX_CMD_SHARED_EVENT_CREATE);
CHECK(sem.obj_id == se.obj_id && sem.initial_value == 42);
// Destroy carries the id alone.
CHECK(ser.destroy(b.obj_id));
auto dm = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
CHECK(dm.obj_id == b.obj_id);
// The ring is now drained and every post rang the idle host's doorbell.
RgfxMsgHeader spare = {};
std::vector<uint8_t> none;
CHECK(!ring.next(&spare, &none));
CHECK(TestRing::doorbells.load() > before);
}
void test_library_message()
{
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, nullptr, nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
const uint8_t air[6] = { 1, 2, 3, 4, 5, 6 };
RgfxCreated lib = ser.createLibrary(air, sizeof(air));
CHECK(lib.posted);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(ring.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_LIBRARY_CREATE);
// header struct (32) + 6 bytes, rounded up to a multiple of 8 = 40.
CHECK(h.size == 40);
RgfxLibraryCreate head;
std::memcpy(&head, bytes.data(), sizeof(head));
CHECK(head.obj_id == lib.obj_id && head.byte_length == 6);
CHECK(std::memcmp(bytes.data() + RGFX_LIBRARY_BYTES_OFFSET, air, sizeof(air)) == 0);
// A library larger than the ring cannot be posted in one message.
std::vector<uint8_t> huge(ring.dataSize, 0xcc);
RgfxCreated big = ser.createLibrary(huge.data(), huge.size());
CHECK(!big.posted);
}
void test_pipeline_messages()
{
TestRing ring(0x8000);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, nullptr, nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
// A render pipeline: two function names, a label, one colour attachment with
// source-over blend, and a one-entry vertex descriptor, all in the tail.
RgfxRenderPipelineParams rp = {};
rp.vertex.library = 10;
rp.vertex.entry_point = "vmain";
rp.fragment.library = 10;
rp.fragment.entry_point = "frag_main";
rp.label = "pipe";
rp.raster_sample_count = 1;
rp.color_attachment_count = 1;
rp.colors[0].pixel_format = 80; // BGRA8Unorm
rp.colors[0].blending_enabled = 1;
rp.colors[0].source_rgb_blend_factor = 1; // One
rp.colors[0].destination_rgb_blend_factor = 5; // OneMinusSourceAlpha
rp.colors[0].write_mask = 0xf;
rp.depth_pixel_format = 252; // Depth32Float
RgfxVertexBufferLayout layout = {};
layout.buffer_index = 0;
layout.stride = 32;
layout.step_function = 1;
rp.vertex_layouts = &layout;
rp.vertex_layout_count = 1;
RgfxVertexAttribute attr = {};
attr.format = 29; // Float4
rp.vertex_attributes = &attr;
rp.vertex_attribute_count = 1;
rp.flags = RGFX_RENDER_PIPELINE_RASTERIZATION_ENABLED;
RgfxCreated r = ser.createRenderPipeline(rp);
CHECK(r.posted);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(ring.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_RENDER_PIPELINE_CREATE);
CHECK(h.size == bytes.size());
CHECK(h.size % 8 == 0);
RgfxRenderPipelineCreate rc;
std::memcpy(&rc, bytes.data(), sizeof(rc));
CHECK(rc.obj_id == r.obj_id);
CHECK(rc.vertex_library_obj_id == 10 && rc.fragment_library_obj_id == 10);
CHECK(rc.color_attachment_count == 1 && rc.colors[0].pixel_format == 80);
CHECK(rc.colors[0].destination_rgb_blend_factor == 5);
CHECK(rc.depth_pixel_format == 252);
CHECK(rc.vertex_layout_count == 1 && rc.vertex_attribute_count == 1);
CHECK(rc.vertex_name_len == 5);
CHECK(std::memcmp(bytes.data() + rc.vertex_name_offset, "vmain", 5) == 0);
CHECK(rc.fragment_name_len == 9);
CHECK(std::memcmp(bytes.data() + rc.fragment_name_offset, "frag_main", 9) == 0);
CHECK(rc.label_len == 4);
CHECK(std::memcmp(bytes.data() + rc.label_offset, "pipe", 4) == 0);
RgfxVertexBufferLayout gotLayout;
std::memcpy(&gotLayout, bytes.data() + rc.vertex_layouts_offset, sizeof(gotLayout));
CHECK(gotLayout.stride == 32 && gotLayout.step_function == 1);
RgfxVertexAttribute gotAttr;
std::memcpy(&gotAttr, bytes.data() + rc.vertex_attributes_offset, sizeof(gotAttr));
CHECK(gotAttr.format == 29);
// A compute pipeline specialised by one function constant.
RgfxFunctionConstant k = {};
k.index = 2;
k.data_type = 30; // Bool
k.value = 1;
RgfxComputePipelineParams cp = {};
cp.function.library = 10;
cp.function.entry_point = "cmain";
cp.function.constants = &k;
cp.function.constant_count = 1;
cp.max_total_threads_per_threadgroup = 256;
cp.flags = RGFX_COMPUTE_PIPELINE_SUPPORT_ICB;
RgfxCreated c = ser.createComputePipeline(cp);
CHECK(c.posted);
CHECK(ring.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMPUTE_PIPELINE_CREATE);
CHECK(h.size == bytes.size());
RgfxComputePipelineCreate cc;
std::memcpy(&cc, bytes.data(), sizeof(cc));
CHECK(cc.obj_id == c.obj_id && cc.function_library_obj_id == 10);
CHECK(cc.name_len == 5);
CHECK(std::memcmp(bytes.data() + cc.name_offset, "cmain", 5) == 0);
CHECK(cc.constant_count == 1);
RgfxFunctionConstant gotK;
std::memcpy(&gotK, bytes.data() + cc.constants_offset, sizeof(gotK));
CHECK(gotK.index == 2 && gotK.data_type == 30 && gotK.value == 1);
CHECK(cc.max_total_threads_per_threadgroup == 256);
// The host's reflection reply, matched to the create by its seqno: built as
// the host would and read back, asserting the reply layout the guest reads.
RgfxPipelineReflection refl = {};
refl.header.type = RGFX_EVT_PIPELINE_REFLECTION;
refl.header.size = sizeof(refl);
refl.header.seqno = c.seqno;
refl.obj_id = c.obj_id;
refl.status = RGFX_PIPELINE_OK;
refl.kind = RGFX_PIPELINE_KIND_COMPUTE;
refl.max_total_threads_per_threadgroup = 1024;
refl.thread_execution_width = 32;
std::vector<uint8_t> wire(sizeof(refl), 0);
std::memcpy(wire.data(), &refl, sizeof(refl));
RgfxPipelineReflection back;
std::memcpy(&back, wire.data(), sizeof(back));
CHECK(back.header.seqno == c.seqno && back.obj_id == c.obj_id);
CHECK(back.status == RGFX_PIPELINE_OK && back.kind == RGFX_PIPELINE_KIND_COMPUTE);
CHECK(back.thread_execution_width == 32);
}
void test_ring_wrap_and_no_room()
{
// A small ring so a message must pad to the end and wrap.
const uint32_t kData = 256;
TestRing ring(kData);
RgfxRingWriter writer(ring.base(), kData, RGFX_CONTROL_RING_ID, nullptr, nullptr);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
// Each OBJECT_DESTROY is 24 bytes. Post and drain to push the producer near
// the ring's end, then post one that must pad over the tail.
for (int i = 0; i < 10; i++) {
CHECK(ser.destroy(100 + i));
auto m = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
CHECK(m.obj_id == static_cast<uint64_t>(100 + i));
}
// 10 * 24 = 240; 16 bytes to the end. The next 24-byte message pads and wraps.
CHECK(ser.destroy(999));
auto wrapped = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
CHECK(wrapped.obj_id == 999);
// Fill the ring without draining until a post finds no room.
TestRing full(kData);
RgfxRingWriter fw(full.base(), kData, RGFX_CONTROL_RING_ID, nullptr, nullptr);
RgfxIdSpace fids;
RgfxSerializer fser(fw, fids);
int posted = 0;
bool hitNoRoom = false;
for (int i = 0; i < 100; i++) {
if (fser.destroy(i)) {
posted++;
} else {
hitNoRoom = true;
break;
}
}
CHECK(hitNoRoom);
CHECK(posted == static_cast<int>(kData / sizeof(RgfxObjectDestroy))); // 256/24 = 10
}
// A minimal host-side op-stream consumer, the mirror of
// crates/reims-vgpu/src/graphics/decode/cmdbuf.rs's walk: it reads each
// RgfxOpHeader, checks `len`, splits the body, and tracks which encoder is open.
struct OpWalk {
const uint8_t *ops;
size_t size; // op_bytes
size_t pos = 0;
OpWalk(const uint8_t *p, size_t n) : ops(p), size(n) {}
bool done() const { return pos >= size; }
// Reads the next op; fills `tag`, `flags`, `len` and points `body`/`body_len`
// at its body. Returns false (and does not advance) on a structural fault.
bool next(uint16_t *tag, uint16_t *flags, uint32_t *len, const uint8_t **body,
size_t *body_len)
{
if (size - pos < sizeof(RgfxOpHeader))
return false;
RgfxOpHeader h;
std::memcpy(&h, ops + pos, sizeof(h));
if (h.len < RGFX_OP_BODY_OFFSET || (h.len % 8) != 0 || h.len > size - pos)
return false;
*tag = h.tag;
*flags = h.flags;
*len = h.len;
*body = ops + pos + RGFX_OP_BODY_OFFSET;
*body_len = h.len - RGFX_OP_BODY_OFFSET;
pos += h.len;
return true;
}
};
// `tag >> 12`, the op's group, as the host splits it.
uint16_t opGroup(uint16_t tag) { return static_cast<uint16_t>(tag >> 12); }
void test_command_buffer_encoder()
{
TestRing ring(0x8000);
ring.setConsumerIdle(1);
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
nullptr);
RgfxEncoder enc(writer, /*queue*/ 1, /*cb*/ 100);
// Render encoder: a pass with one colour attachment, then a scalar op, an
// array-tailed op (setVertexBuffers), a no-arg op (setDepthCleared) and a draw.
RgfxRenderPassDesc pass = {};
pass.flags = RGFX_PASS_FLAG_RT_SIZE;
pass.render_target_width = 1920;
pass.render_target_height = 1080;
RgfxRenderPassColorAttachment color = {};
color.texture_obj_id = 4;
color.load_action = 2; // Clear
color.store_action = 1; // Store
double one = 1.0;
std::memcpy(&color.clear_color_bits[3], &one, 8);
enc.beginRenderPass(pass, &color, 1);
enc.renderSetRenderPipelineState(7);
enc.renderSetVertexBuffer(2, 0, 0);
enc.renderSetViewport(0.0, 0.0, 1920.0, 1080.0, 0.0, 1.0);
RgfxBufferBinding vbs[2] = {};
vbs[0].buffer_obj_id = 2;
vbs[0].offset = 0;
vbs[1].buffer_obj_id = 3;
vbs[1].offset = 256;
enc.renderSetVertexBuffers(0, vbs, 2);
enc.renderSetDepthCleared();
enc.renderDrawPrimitives(3, 0, 3);
enc.endEncoder();
// Compute encoder: default pass, a scalar, a dispatch, an array-tailed op and a
// no-body op.
enc.beginComputePass();
enc.computeSetComputePipelineState(8);
enc.computeDispatchThreadgroups(16, 8, 1, 32, 1, 1);
RgfxComputeBufferBinding cbs[2] = {};
cbs[0].buffer_obj_id = 2;
cbs[0].offset = 0;
cbs[1].buffer_obj_id = 3;
cbs[1].offset = 512;
enc.computeSetBuffers(0, cbs, 2);
enc.computeEncodeStartElse();
enc.endEncoder();
// Blit encoder: a copy, a fill-texture (trailing bytes), and a fence wait.
enc.beginBlitPass();
enc.blitCopyBufferToBuffer(2, 3, 16, 32, 4096);
const uint8_t fill[5] = { 0xde, 0xad, 0xbe, 0xef, 0x01 };
enc.blitFillTexture(4, 0, 0, 0, 0, 0, 32, 32, 1, fill, sizeof(fill));
enc.blitWaitForFence(9);
enc.endEncoder();
uint64_t seqno = 0;
CHECK(enc.finish(&seqno));
CHECK(seqno == 1);
// Read the command-buffer message back off the ring and check its framing.
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(ring.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
CHECK(h.size == bytes.size());
CHECK(h.size % 8 == 0);
CHECK(h.seqno == 1);
RgfxCommandBuffer cb = {};
std::memcpy(&cb, bytes.data(), sizeof(cb));
CHECK(cb.queue_obj_id == 1);
CHECK(cb.cb_obj_id == 100);
CHECK(cb.op_bytes == bytes.size() - RGFX_COMMAND_BUFFER_OPS_OFFSET);
CHECK(cb.op_bytes == enc.opBytes());
// The op stream follows the header at RGFX_COMMAND_BUFFER_OPS_OFFSET.
OpWalk walk(bytes.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cb.op_bytes);
// The exact op sequence the encoder wrote.
const uint16_t want[] = {
RGFX_OP_ENCODER_BEGIN_RENDER,
RGFX_OP_RENDER_SET_RENDER_PIPELINE_STATE,
RGFX_OP_RENDER_SET_VERTEX_BUFFER,
RGFX_OP_RENDER_SET_VIEWPORT,
RGFX_OP_RENDER_SET_VERTEX_BUFFERS,
RGFX_OP_RENDER_SET_DEPTH_CLEARED,
RGFX_OP_RENDER_DRAW_PRIMITIVES,
RGFX_OP_ENCODER_END,
RGFX_OP_ENCODER_BEGIN_COMPUTE,
RGFX_OP_COMPUTE_SET_COMPUTE_PIPELINE_STATE,
RGFX_OP_COMPUTE_DISPATCH_THREADGROUPS,
RGFX_OP_COMPUTE_SET_BUFFERS,
RGFX_OP_COMPUTE_ENCODE_START_ELSE,
RGFX_OP_ENCODER_END,
RGFX_OP_ENCODER_BEGIN_BLIT,
RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER,
RGFX_OP_BLIT_FILL_TEXTURE,
RGFX_OP_BLIT_WAIT_FOR_FENCE,
RGFX_OP_ENCODER_END,
};
const size_t want_n = sizeof(want) / sizeof(want[0]);
int open = 0; // 0 none, 1 render, 2 compute, 3 blit
int begins = 0, ends = 0;
size_t i = 0;
while (!walk.done()) {
uint16_t tag = 0, flags = 0;
uint32_t len = 0;
const uint8_t *body = nullptr;
size_t body_len = 0;
CHECK(walk.next(&tag, &flags, &len, &body, &body_len));
CHECK(len % 8 == 0);
CHECK(i < want_n);
CHECK(tag == want[i]);
// Framing is balanced: a begin opens exactly one encoder, an end closes it,
// and every body op's group matches the open encoder.
if (opGroup(tag) == RGFX_OP_GROUP_FRAMING) {
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER) {
CHECK(open == 0);
open = 1;
begins++;
} else if (tag == RGFX_OP_ENCODER_BEGIN_COMPUTE) {
CHECK(open == 0);
open = 2;
begins++;
} else if (tag == RGFX_OP_ENCODER_BEGIN_BLIT) {
CHECK(open == 0);
open = 3;
begins++;
} else if (tag == RGFX_OP_ENCODER_END) {
CHECK(open != 0);
open = 0;
ends++;
}
} else {
CHECK(static_cast<int>(opGroup(tag)) == open);
}
// Spot-check the bodies of representative ops across all three encoders.
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER) {
CHECK(len == 8 + sizeof(RgfxRenderPassDesc) + 1 * sizeof(RgfxRenderPassColorAttachment));
RgfxRenderPassDesc gotPass;
std::memcpy(&gotPass, body, sizeof(gotPass));
CHECK(gotPass.color_count == 1);
CHECK(gotPass.flags == RGFX_PASS_FLAG_RT_SIZE);
CHECK(gotPass.render_target_width == 1920 && gotPass.render_target_height == 1080);
RgfxRenderPassColorAttachment gotColor;
std::memcpy(&gotColor, body + RGFX_RENDER_PASS_COLOR_OFFSET, sizeof(gotColor));
CHECK(gotColor.texture_obj_id == 4);
CHECK(gotColor.load_action == 2 && gotColor.store_action == 1);
double a;
std::memcpy(&a, &gotColor.clear_color_bits[3], 8);
CHECK(a == 1.0);
} else if (tag == RGFX_OP_RENDER_SET_VERTEX_BUFFER) {
RgfxOpSetVertexBuffer b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.buffer_obj_id == 2 && b.offset == 0 && b.index == 0);
} else if (tag == RGFX_OP_RENDER_SET_VERTEX_BUFFERS) {
// Array-tailed: head's range then two RgfxBufferBinding records.
CHECK(len == 8 + sizeof(RgfxOpSetVertexBuffers) + 2 * sizeof(RgfxBufferBinding));
RgfxOpSetVertexBuffers head;
std::memcpy(&head, body, sizeof(head));
CHECK(head.range_location == 0 && head.range_length == 2);
RgfxBufferBinding e0, e1;
std::memcpy(&e0, body + sizeof(head), sizeof(e0));
std::memcpy(&e1, body + sizeof(head) + sizeof(e0), sizeof(e1));
CHECK(e0.buffer_obj_id == 2 && e0.offset == 0);
CHECK(e1.buffer_obj_id == 3 && e1.offset == 256);
} else if (tag == RGFX_OP_RENDER_SET_DEPTH_CLEARED) {
CHECK(len == 8 && body_len == 0); // no-arg render op: header only
} else if (tag == RGFX_OP_RENDER_DRAW_PRIMITIVES) {
RgfxOpDrawPrimitives b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.primitive_type == 3 && b.vertex_start == 0 && b.vertex_count == 3);
} else if (tag == RGFX_OP_ENCODER_BEGIN_COMPUTE) {
CHECK(len == 8 && body_len == 0); // default pass: empty body
} else if (tag == RGFX_OP_COMPUTE_DISPATCH_THREADGROUPS) {
RgfxComputeOpDispatchThreadgroups b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.threadgroups_width == 16 && b.threadgroups_height == 8);
CHECK(b.threads_width == 32 && b.threads_height == 1 && b.threads_depth == 1);
} else if (tag == RGFX_OP_COMPUTE_SET_BUFFERS) {
CHECK(len == 8 + sizeof(RgfxComputeOpSetBuffers) +
2 * sizeof(RgfxComputeBufferBinding));
RgfxComputeOpSetBuffers head;
std::memcpy(&head, body, sizeof(head));
CHECK(head.location == 0 && head.length == 2);
RgfxComputeBufferBinding e1;
std::memcpy(&e1, body + sizeof(head) + sizeof(e1), sizeof(e1));
CHECK(e1.buffer_obj_id == 3 && e1.offset == 512);
} else if (tag == RGFX_OP_COMPUTE_ENCODE_START_ELSE) {
CHECK(len == 8 && body_len == 0); // no-body compute op
} else if (tag == RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER) {
RgfxBlitOpCopyBufferToBuffer b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.source_buffer_obj_id == 2 && b.destination_buffer_obj_id == 3);
CHECK(b.source_offset == 16 && b.destination_offset == 32 && b.size == 4096);
} else if (tag == RGFX_OP_BLIT_FILL_TEXTURE) {
// Head then `length` fill bytes at offset 80, padded to a multiple of 8.
CHECK(len == 8 + 88); // 80-byte head + 5 fill bytes padded to 88
RgfxBlitOpFillTexture head;
std::memcpy(&head, body, sizeof(head));
CHECK(head.texture_obj_id == 4 && head.length == 5);
CHECK(head.region_size_width == 32 && head.region_size_height == 32);
const uint8_t expect[5] = { 0xde, 0xad, 0xbe, 0xef, 0x01 };
CHECK(std::memcmp(body + RGFX_OP_BLIT_FILL_TEXTURE_BYTES_OFFSET, expect, 5) == 0);
} else if (tag == RGFX_OP_BLIT_WAIT_FOR_FENCE) {
RgfxBlitOpWaitForFence b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.fence_obj_id == 9);
}
i++;
}
// The whole stream was consumed: the tag sequence matched and the framing is
// balanced (three encoders opened and closed).
CHECK(i == want_n);
CHECK(open == 0);
CHECK(begins == 3 && ends == 3);
// op_bytes is the stream the walk consumed, 8-aligned.
CHECK(walk.pos == cb.op_bytes);
CHECK(cb.op_bytes % 8 == 0);
}
} // namespace
// A forwarding writer hands each whole message, its type and size stamped, to its forward,
// whose seqno it returns; a refusal posts nothing. A reflection the kext hands back before its
// wrapper registers is kept for the registration.
struct ForwardLog {
std::vector<std::vector<uint8_t>> messages;
bool refuse = false;
uint64_t nextSeqno = 41;
};
bool forwardTo(void *context, const void *message, uint32_t size, uint64_t *out_seqno)
{
ForwardLog *log = static_cast<ForwardLog *>(context);
if (log->refuse)
return false;
const uint8_t *b = static_cast<const uint8_t *>(message);
log->messages.emplace_back(b, b + size);
*out_seqno = log->nextSeqno++;
return true;
}
void test_forwarded_lifecycle()
{
ForwardLog log;
RgfxRingWriter writer(&forwardTo, &log, 4096);
CHECK(writer.dataSize() == 4096);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxCreated ev = ser.createEvent();
CHECK(ev.posted);
CHECK(ev.seqno == 41);
CHECK(log.messages.size() == 1);
RgfxObjectCreate m = {};
std::memcpy(&m, log.messages[0].data(), sizeof(m));
CHECK(m.header.type == RGFX_CMD_EVENT_CREATE);
CHECK(m.header.size == sizeof(RgfxObjectCreate));
CHECK(m.header.seqno == 0); // the kext stamps it
CHECK(m.obj_id == ev.obj_id);
log.refuse = true;
CHECK(!ser.createEvent().posted);
CHECK(log.messages.size() == 1);
// Too large for the forward: refused before it is handed over.
std::vector<uint8_t> big(8192, 0);
CHECK(!writer.tryPost(RGFX_CMD_LIBRARY_CREATE, big.data(), 8192, nullptr));
RgfxReplyReader reader;
CHECK(reader.pump() == 0);
RgfxPipelineReflection r = {};
r.header.type = RGFX_EVT_PIPELINE_REFLECTION;
r.header.size = sizeof(r);
r.header.seqno = 7;
r.obj_id = 99;
reader.deliver(&r, sizeof(r));
uint64_t got = 0;
reader.expectReflection(7, [&got](const RgfxPipelineReflection &m) { got = m.obj_id; });
CHECK(got == 99);
CHECK(!reader.awaitingReflection(7));
reader.expectReflection(8, [&got](const RgfxPipelineReflection &m) { got = m.obj_id + 1; });
CHECK(reader.awaitingReflection(8));
r.header.seqno = 8;
reader.deliver(&r, sizeof(r));
CHECK(got == 100);
CHECK(!reader.awaitingReflection(8));
}
int main()
{
test_id_space();
test_caps();
test_lifecycle_messages();
test_library_message();
test_pipeline_messages();
test_ring_wrap_and_no_room();
test_command_buffer_encoder();
test_forwarded_lifecycle();
std::printf("serializer_tests: OK (%d checks)\n", g_checks);
return 0;
}