Triforce v0.8.0

Evil HD (SMAA Ultra, 16x filtering, full textures, ambient occlusion with bounce light, sunlight shafts, foliage drawn 4x as far, the remastered texture pack's loader and the launcher's download of it), FSR 3.1 frame generation for every GPU, Intel XeSS, FSR 4 model choice, ReShade presets, Auto (this PC), HUD placement, the options menu in 13 languages, a second input for every control, hold to toggle, DualSense speaker and haptics, NFC from the player's own dumps, the above-60 fps game fixes, the Debug tab's flight and Inventory fixes, the launcher's full settings, and over 250 fixes.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-25 10:21:32 -06:00
parent 861702476a
commit 4fa4f9188b
881 changed files with 179428 additions and 15581 deletions

View File

@@ -262,7 +262,83 @@ static void test_game(void) {
}
}
/* ((Triforce) a Flipper Zero NFC file of the tag: its pages as text; the same figure as the tag's bytes */
static size_t flipper_text(char *out, size_t cap, int pages, int unread_page) {
uint8_t d[540];
tag_dump(d, sizeof d);
size_t o = (size_t)snprintf(out, cap, "Filetype: Flipper NFC device\nVersion: 4\nDevice type: NTAG/Ultralight\nUID: 04 A1\nPages total: 135\n");
for (int p = 0; p < pages && o < cap; p++) {
if (p == unread_page) o += (size_t)snprintf(out + o, cap - o, "Page %d: ?? ?? ?? ??\n", p);
else o += (size_t)snprintf(out + o, cap - o, "Page %d: %02X %02X %02X %02x\n", p, d[4 * p], d[4 * p + 1], d[4 * p + 2], d[4 * p + 3]);
}
return o;
}
static void test_flipper(void) {
static char text[8192];
uint8_t pages[540], d[540];
AmiiboTag t;
tag_dump(d, sizeof d);
size_t n = flipper_text(text, sizeof text, 135, -1);
char *g = (char *)guarded(n);
memcpy(g, text, n); /* (no 0 at its end, and a read past it stops the test) */
CHECK(amiibo_flipper(g, n, pages) == 540 && !memcmp(pages, d, 540), "a Flipper NFC file's pages are not the tag's bytes");
CHECK(amiibo_parse(pages, 540, &t) == AMIIBO_OK && !memcmp(t.uid, kUid, 7) && !memcmp(t.model, kModel, 8), "a Flipper NFC file's figure is not taken");
for (size_t cut = 0; cut < n; cut += 97) amiibo_flipper(g + n - cut, cut, pages); /* (cut short anywhere: no read past it) */
n = flipper_text(text, sizeof text, 135, 22); /* (page 22, the end of the figure's bytes, unread: no figure there) */
CHECK(amiibo_flipper(text, n, pages) == 540 && amiibo_parse(pages, 540, &t) == AMIIBO_NOT_A_FIGURE, "an unread page is read");
n = flipper_text(text, sizeof text, 120, -1);
CHECK(amiibo_flipper(text, n, pages) == 0, "a Flipper NFC file of another tag (120 pages) is taken");
CHECK(amiibo_flipper("Filetype", 8, pages) == 0 && amiibo_flipper((const char *)d, sizeof d, pages) == 0, "a tag's bytes are read as text");
}
/* ((Triforce) the application area: made, opened by its game, kept across a lift, written out only when made or flushed */
static void test_area(void) {
const int64_t ms = 1000000;
uint8_t model[NFP_MODEL_INFO_SIZE], out[NFP_AREA_SIZE + 8], file[NFP_AREA_FILE], data[300];
uint64_t size = 0;
int save = 7;
Nfp n;
nfp_reset(&n);
const AmiiboTag t = figure();
nfp_choose(&n, &t);
CHECK(nfp_area_open(&n, 0, 1 * ms, 0x1234) == NFP_WRONG_STATE && nfp_flush(&n, 0, 1 * ms, &save) == NFP_WRONG_STATE && !save,
"the area answers with no figure mounted");
nfp_start(&n, 0, 2 * ms), nfp_mount(&n, 0, 3 * ms), nfp_model_info(&n, 0, 3 * ms, model);
CHECK(nfp_area_open(&n, 0, 4 * ms, 0x1234) == NFP_AREA_NEEDS_CREATE, "a figure with no area opens one");
CHECK(nfp_area_get(&n, 0, 4 * ms, out, sizeof out, &size) == NFP_WRONG_STATE, "an area not opened is read");
for (int i = 0; i < (int)sizeof data; i++) data[i] = (uint8_t)(i + 1);
CHECK(nfp_area_create(&n, 0, 5 * ms, 0x1234, data, 3, 0, &save) == 0 && save == 1, "the area is not made, or not written out");
CHECK(nfp_area_create(&n, 0, 5 * ms, 0x1234, data, 3, 0, &save) == NFP_AREA_EXISTS && !save, "an area is made twice");
memset(out, 0xee, sizeof out);
CHECK(nfp_area_get(&n, 0, 6 * ms, out, sizeof out, &size) == 0 && size == NFP_AREA_SIZE && out[0] == 1 && out[2] == 3 && !out[3] &&
out[NFP_AREA_SIZE] == 0xee, "the area's first data is not what the game gave, or more than the area is written");
CHECK(nfp_area_set(&n, 0, 7 * ms, data, sizeof data) == 0 && nfp_area_get(&n, 0, 7 * ms, out, 4, &size) == 0 && out[3] == 4 &&
n.area.data[NFP_AREA_SIZE - 1] == (uint8_t)NFP_AREA_SIZE, "a set area is not the game's data, cut to its size");
CHECK(nfp_flush(&n, 0, 8 * ms, &save) == 0 && save == 1, "Flush does not write the area out");
CHECK(nfp_state(&n, 0, 8 * ms + NFP_HOLD_NS - 1) == NFP_MOUNT, "the figure is lifted off while the game uses its area");
amiibo_area_bytes(&n.area, file);
CHECK(nfp_state(&n, 0, 9 * ms + NFP_HOLD_NS) == NFP_DEACTIVE && !n.area.open, "the area stays open after the figure is lifted off");
NfpArea back;
memset(&back, 0, sizeof back);
CHECK(amiibo_area_parse(file, sizeof file, &back) && back.there && !back.open && back.id == 0x1234 && !memcmp(back.data, n.area.data, NFP_AREA_SIZE),
"the area's file does not give the area back");
CHECK(!amiibo_area_parse(file, sizeof file - 1, &back) && !amiibo_area_parse(data, sizeof file, &back), "a file that is not an area's is taken");
/* another game's ID; the same figure chosen again with its file */
nfp_choose(&n, &t);
CHECK(!n.area.there, "another choice keeps the last figure's area");
amiibo_area_parse(file, sizeof file, &n.area);
nfp_stop(&n, 0), nfp_start(&n, 0, 20 * ms), nfp_mount(&n, 0, 20 * ms);
CHECK(nfp_area_open(&n, 0, 21 * ms, 0x9999) == NFP_WRONG_ACCESS_ID && nfp_area_open(&n, 0, 21 * ms, 0x1234) == 0, "the access ID is not checked");
CHECK(nfp_area_create(&n, 0, 22 * ms, 0x9999, NULL, 0, 1, &save) == 0 && save && n.area.id == 0x9999 && !n.area.data[0],
"Recreate does not make the area anew");
char name[20];
amiibo_area_name(&t, name);
CHECK(!strcmp(name, "04a1b2c3d4e5f6.area") && amiibo_name_ok(name), "the area's file is not named by the serial number");
}
int main(void) {
test_flipper();
test_area();
test_parse();
test_infos();
test_names();

237
tests/audio_aux_test.c Normal file
View File

@@ -0,0 +1,237 @@
/* The actual Aux entry points and effect code of host/nn_audio.c around authored memory and a worker that applies a
known gain. No audio device or game is opened. Run with HOS_AUDIO_AUX=0 it checks that an Aux is accepted and passed
through, as before. */
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); exit(1); } } while (0)
typedef struct { uint64_t x[32]; uint8_t vreg[32][16]; } Ctx;
typedef int CRITICAL_SECTION;
static void InitializeCriticalSection(int *lock) { *lock = 0; }
static void EnterCriticalSection(int *lock) { CHECK(!*lock); *lock = 1; }
static void LeaveCriticalSection(int *lock) { CHECK(*lock); *lock = 0; }
static void hos_log(const char *format, ...) { (void)format; }
/* (the fixture's "guest memory" is the host's own: an address is its pointer) */
static void *hos_guest_range(uint64_t a, uint64_t n) { (void)n; return (void *)(uintptr_t)a; }
#define HLE(name) void imp_##name(Ctx *c)
#define ARG(n) (c->x[n])
#define RET(value) (c->x[0] = (uint64_t)(value))
#define GP(value) ((void *)(uintptr_t)(value))
#define G64(value) (*(uint64_t *)GP(value))
#define G32(value) (*(uint32_t *)GP(value))
#include "audio_aux.inc"
#define AUX_ADD imp__ZN2nn5audio6AddAuxEPNS0_19AudioRendererConfigEPNS0_7AuxTypeEPNS0_10SubMixTypeEPvS7_m
#define AUX_COUNT imp__ZN2nn5audio17GetAuxSampleCountEPKNS0_7AuxTypeE
#define AUX_READ imp__ZN2nn5audio17ReadAuxSendBufferEPNS0_7AuxTypeEPii
#define AUX_WRITE imp__ZN2nn5audio20WriteAuxReturnBufferEPNS0_7AuxTypeEPKii
#define AUX_MAP imp__ZN2nn5audio17SetAuxInputOutputEPNS0_7AuxTypeEPKaS4_i
#define AUX_ENABLE imp__ZN2nn5audio13SetAuxEnabledEPNS0_7AuxTypeEb
#define AUX_ENABLED imp__ZN2nn5audio12IsAuxEnabledEPKNS0_7AuxTypeE
#define AUX_REMOVE imp__ZN2nn5audio9RemoveAuxEPNS0_19AudioRendererConfigEPNS0_7AuxTypeEPNS0_10SubMixTypeE
#define AUX_REMOVABLE imp__ZN2nn5audio14IsAuxRemovableEPKNS0_7AuxTypeE
#define AUX_SIZE imp__ZN2nn5audio43GetRequiredBufferSizeForAuxSendReturnBufferEPKNS0_22AudioRendererParameterEii
static uint64_t mix_object, aux_object;
static int32_t send_storage[32 + FRAME * 4 + 4], return_storage[32 + FRAME * 4 + 4];
static const size_t buffer_bytes = 128 + FRAME * 4 * sizeof(int32_t);
static int32_t data[FRAME * MAX_BUF];
static uint64_t call(void (*fn)(Ctx *), uint64_t object, uint64_t arg1, uint64_t arg2) {
Ctx c;
memset(&c, 0, sizeof c);
c.x[0] = object; c.x[1] = arg1; c.x[2] = arg2;
fn(&c);
return c.x[0];
}
static void fill(float left, float right) {
for (int i = 0; i < FRAME; i++) mixes[0].buf[0][i] = left, mixes[0].buf[1][i] = right;
}
static void mapping(int cross) {
int8_t in[2] = {0, 1}, out[2] = {(int8_t)cross, (int8_t)!cross};
Ctx c;
memset(&c, 0, sizeof c);
c.x[0] = (uintptr_t)&aux_object; c.x[1] = (uintptr_t)in; c.x[2] = (uintptr_t)out; c.x[3] = 2;
AUX_MAP(&c);
in[0] = out[0] = -1; /* (the caller may use these arrays again before the update) */
}
static void add(void) {
Ctx c;
memset(&c, 0, sizeof c);
c.x[1] = (uintptr_t)&aux_object; c.x[2] = (uintptr_t)&mix_object;
c.x[3] = (uintptr_t)send_storage; c.x[4] = (uintptr_t)return_storage; c.x[5] = buffer_bytes;
AUX_ADD(&c);
CHECK(c.x[0] == 0);
}
static void setup(void) {
memset(mixes, 0, sizeof mixes);
memset(reverbs, 0, sizeof reverbs);
memset(auxes, 0, sizeof auxes);
memset(send_storage, 0x5a, sizeof send_storage);
memset(return_storage, 0x5a, sizeof return_storage);
ncmds = 0;
mixes[0].used = 1; mixes[0].buffers = 2;
put_handle((uintptr_t)&mix_object, K_MIX, 0);
aux_object = 0;
add();
mapping(1);
}
static int read_samples(int n) { return (int)call(AUX_READ, (uintptr_t)&aux_object, (uintptr_t)data, (uint64_t)n); }
static int write_samples(int n) { return (int)call(AUX_WRITE, (uintptr_t)&aux_object, (uintptr_t)data, (uint64_t)n); }
static void enable(int enabled) { call(AUX_ENABLE, (uintptr_t)&aux_object, (uint64_t)enabled, 0); }
/* HOS_AUDIO_AUX=0 (or HOS_AUDIO_EFFECTS=0): no Aux of ours is made, and every call answers as the old stubs did */
static int passed_through(void) {
setup();
CHECK(!aux_object && !auxes[0].used && send_storage[0] == 0x5a5a5a5a);
commit();
fill(0.25f, -0.5f);
effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0.25f && mixes[0].buf[1][0] == -0.5f);
CHECK(read_samples(FRAME * 2) == 0 && write_samples(FRAME * 2) == FRAME * 2);
CHECK(call(AUX_ENABLED, (uintptr_t)&aux_object, 0, 0) == 1 && call(AUX_REMOVABLE, (uintptr_t)&aux_object, 0, 0) == 1);
CHECK(call(AUX_COUNT, (uintptr_t)&aux_object, 0, 0) == 0);
puts("PASS (HOS_AUDIO_AUX=0 or HOS_AUDIO_EFFECTS=0): an Aux is accepted and passed through, as before");
return 0;
}
int main(void) {
uint32_t parameter[2] = {48000, 240};
Ctx c;
memset(&c, 0, sizeof c);
c.x[0] = (uintptr_t)parameter; c.x[1] = 6; c.x[2] = 5;
AUX_SIZE(&c);
CHECK(c.x[0] == 28928); /* (30 whole channel frames and the 128 bytes before them; it was 376) */
parameter[1] = 241;
c.x[0] = (uintptr_t)parameter; c.x[1] = 1; c.x[2] = 1;
AUX_SIZE(&c);
CHECK(c.x[0] == 1152); /* (964 bytes up to a cache line) */
c.x[0] = (uintptr_t)parameter; c.x[1] = UINT32_MAX; c.x[2] = 1;
AUX_SIZE(&c);
CHECK(c.x[0] == 0x100); /* (no size it can count: as before, never a wrapped one) */
c.x[0] = (uintptr_t)parameter; c.x[1] = 0x7fffffff; c.x[2] = 0x7fffffff;
AUX_SIZE(&c);
CHECK(c.x[0] == (uint64_t)0x7fffffff * 0x7fffffff * 4 + 0x100);
if (!aux_on()) return passed_through();
setup();
CHECK(aux_object);
CHECK(call(AUX_COUNT, (uintptr_t)&aux_object, 0, 0) == FRAME * 4);
CHECK(call(AUX_ENABLED, (uintptr_t)&aux_object, 0, 0) == 1);
fill(0.25f, -0.5f);
effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0.25f); /* (the graph's change waits for the update) */
commit();
effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0 && mixes[0].buf[1][0] == 0); /* (the return, never the dry send) */
CHECK(read_samples(FRAME * 2) == FRAME * 2);
for (int i = 0; i < FRAME; i++) CHECK(data[i] == 8192 && data[FRAME + i] == -16384);
for (int i = 0; i < FRAME * 2; i++) data[i] /= 4;
CHECK(write_samples(FRAME * 2) == FRAME * 2);
fill(1, 1);
effects_frame(0);
for (int i = 0; i < FRAME; i++) CHECK(mixes[0].buf[0][i] == -0.125f && mixes[0].buf[1][i] == 0.0625f);
CHECK(call(AUX_COUNT, (uintptr_t)&aux_object, 0, 0) == FRAME * 4); /* (the room, not what waits) */
effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0 && mixes[0].buf[1][0] == 0); /* (a return is played once: a late worker is silence) */
enable(0);
CHECK(!call(AUX_ENABLED, (uintptr_t)&aux_object, 0, 0));
CHECK(!call(AUX_REMOVABLE, (uintptr_t)&aux_object, 0, 0));
commit();
CHECK(call(AUX_REMOVABLE, (uintptr_t)&aux_object, 0, 0));
CHECK(read_samples(FRAME * 2) == 0);
fill(0.25f, -0.5f);
effects_frame(0);
CHECK(mixes[0].buf[0][0] == -0.5f && mixes[0].buf[1][0] == 0.25f); /* (disabled, a crossed map: each input once) */
enable(1); commit();
for (int frame = 1; frame <= 12; frame++) { fill((float)frame, -(float)frame); effects_frame(0); }
CHECK(read_samples(FRAME * 4) == FRAME * 4); /* (the send ring holds two frames: the rest were not queued in part) */
CHECK(data[0] == 32768 && data[FRAME] == -32768 && data[FRAME * 2] == 65536 && data[FRAME * 3] == -65536);
fill(0.125f, -0.25f); effects_frame(0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == 4096 && data[FRAME] == -8192);
CHECK(read_samples(-1) == 0 && write_samples(-1) == 0);
for (int i = 0; i < FRAME * 4; i++) data[i] = i + 1;
CHECK(write_samples(FRAME * 5) == FRAME * 4); /* (a bounded write) */
CHECK(write_samples(1) == 0);
mapping(1); commit(); /* (the same map again keeps what waits) */
fill(0, 0); effects_frame(0);
CHECK(mixes[0].buf[1][0] == 1.0f / 32768.0f);
mapping(0); commit(); /* (another map: the old layout's samples go) */
fill(1, 2); effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0 && mixes[0].buf[1][0] == 0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == 32768 && data[FRAME] == 65536);
fill(NAN, INFINITY); effects_frame(0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == 0 && data[FRAME] == 0);
fill(1e30f, -1e30f); effects_frame(0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == INT32_MAX && data[FRAME] == INT32_MIN);
/* removed: the mixer leaves the game's buffers alone at once, and the same guest object made again before the
update is the new effect, which the queued release does not take */
memset(&c, 0, sizeof c); c.x[1] = (uintptr_t)&aux_object;
AUX_REMOVE(&c);
CHECK(call(AUX_COUNT, (uintptr_t)&aux_object, 0, 0) == 0);
memset(send_storage, 0x5a, sizeof send_storage);
memset(return_storage, 0x5a, sizeof return_storage);
fill(0.5f, 0.5f); effects_frame(0);
CHECK(send_storage[32] == 0x5a5a5a5a && return_storage[32] == 0x5a5a5a5a);
add(); mapping(0); commit();
fill(0.5f, -0.5f); effects_frame(0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == 16384);
CHECK(send_storage[32 + FRAME * 4] == 0x5a5a5a5a && return_storage[32 + FRAME * 4] == 0x5a5a5a5a);
/* uneven reads cross the ring's end without losing the channels' order */
setup(); commit();
fill(1, -1); effects_frame(0);
CHECK(read_samples(100) == 100);
fill(2, -2); effects_frame(0);
CHECK(read_samples(600) == 600);
CHECK(data[139] == 32768 && data[140] == -32768 && data[380] == 65536);
fill(3, -3); effects_frame(0);
CHECK(read_samples(740) == 740);
CHECK(data[19] == 65536 && data[20] == -65536 && data[260] == 98304 && data[500] == -98304);
/* a worker may return one frame in several calls: a part of a frame is never played */
for (int i = 0; i < FRAME * 2; i++) data[i] = 4096;
CHECK(write_samples(100) == 100);
fill(1, 1); effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0);
CHECK(write_samples(FRAME * 2 - 100) == FRAME * 2 - 100);
effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0.125f && mixes[0].buf[1][FRAME - 1] == 0.125f);
/* the order the effects were added in, across a reverb and an Aux: a reverb with no wet part and half the dry */
setup(); commit();
Reverb *rv = &reverbs[0];
rv->used = rv->enabled = 1; rv->mix = 0; rv->n = 2; rv->in[1] = rv->out[1] = 1;
rv->room = -10000; rv->refl = -10000; rv->reverb = -10000; rv->dry = 0.5f; rv->seq = ++fx_seq;
rv->decay_ns = 1000000000ll; rv->hf_ratio = 1.0f; rv->hf_ref = 5000; rv->density = 100; rv->diffusion = 100;
for (int i = 0; i < FRAME * 2; i++) data[i] = 8192;
CHECK(write_samples(FRAME * 2) == FRAME * 2);
fill(1, 1); effects_frame(0);
CHECK(fabsf(mixes[0].buf[0][0] - 0.125f) < 0.0001f); /* (the Aux first, then the reverb) */
CHECK(read_samples(FRAME * 2) == FRAME * 2 && data[0] == 32768);
rv->seq = 0;
fill(1, 1); effects_frame(0);
CHECK(read_samples(FRAME * 2) == FRAME * 2 && abs(data[0] - 16384) < 8); /* (the reverb first, then the Aux) */
/* its mix released: it runs on none, and is still the game's to remove */
setup(); commit();
{ const Cmd k = {.op = OP_MIX_RELEASE, .idx = 0}; submit(&k); commit(); }
CHECK(auxes[0].used && auxes[0].mix == -1);
mixes[0].used = 1; mixes[0].buffers = 2;
fill(0.25f, 0.25f); effects_frame(0);
CHECK(mixes[0].buf[0][0] == 0.25f && read_samples(FRAME * 2) == 0);
memset(&c, 0, sizeof c); c.x[1] = (uintptr_t)&aux_object;
AUX_REMOVE(&c); commit();
CHECK(!auxes[0].used);
free(cmds);
puts("PASS: Aux sizing, PCM round trip, channel maps, update ordering, under- and overflow, reset, removal and slot reuse");
return 0;
}

View File

@@ -28,7 +28,9 @@ static void au_unlock(void) { CHECK(--lock_depth == 0); }
/* the voice's source: one authored sample a frame (render_voice's resampler at 1.0 hands them through a frame late) */
static float tone[4096];
static int tone_pos;
static int silent_voice = -1; /* (this voice plays silence) */
static int next_source_frame(Voice *v) {
if (v - voices == silent_voice) { v->cur[0] = 0; return 1; }
v->cur[0] = tone[tone_pos++ % 4096];
return 1;
}
@@ -274,11 +276,57 @@ static float splitter_level(int filter_on) {
}
return level;
}
/* Two voices through one splitter destination with its low pass on: the filter's history is each voice's own. The
first plays a steady 1.0, the second silence: with one history in the splitter the second voice's samples came out of
the first one's filter state, and the first one's level was taken down by the second's zeros */
static void splitter_voices(void) {
reset();
Splitter *s = &splitters[0];
s->used = 1; s->channels = 1; s->dests = 1; s->dest_mix[0] = 1;
s->vol[0][0][0] = s->ramp[0][0][0] = 1.0f;
put_handle(SPLIT, K_SPLITTER, 0);
float_packet(1, (const float[]){0.1f, 0, 0, 0.9f, 0});
Ctx c = call(SPLIT, 0, MIX1, 0, PACKET, 0, 0);
imp__ZN2nn5audio32SetSplitterBiquadFilterParameterEPNS0_12SplitterTypeEiPNS0_10SubMixTypeEiRKNS0_22TBiquadFilterParameterIfEE(&c);
commit();
for (int k = 0; k < 2; k++) {
Voice *v = &voices[k];
v->used = 1; v->channels = 1; v->rate = RATE; v->pitch = 1; v->volume = v->ramp_volume = 1;
v->state = PLAY_STARTED; v->dest_kind = DEST_SPLITTER; v->dest = 0;
}
for (int i = 0; i < 4096; i++) tone[i] = 1.0f;
tone_pos = 0;
silent_voice = 1;
float first = 0;
for (int frame = 0; frame < 10; frame++) {
memset(mixes[1].buf, 0, sizeof mixes[1].buf);
render_voice(&voices[0]);
first = mixes[1].buf[0][FRAME - 1];
memset(mixes[1].buf, 0, sizeof mixes[1].buf);
render_voice(&voices[1]);
for (int i = 0; i < FRAME; i++) CHECK(mixes[1].buf[0][i] == 0.0f); /* (silence in, silence out) */
}
silent_voice = -1;
CHECK(fabsf(first - 1.0f) < 0.001f); /* (a steady 1.0 through y = 0.1 x + 0.9 y' settles at 1.0, filtered or not) */
/* the filter turned off and on again starts over in the voices: nothing of the level it had settled at */
float_packet(0, (const float[]){0.1f, 0, 0, 0.9f, 0});
c = call(SPLIT, 0, MIX1, 0, PACKET, 0, 0);
imp__ZN2nn5audio32SetSplitterBiquadFilterParameterEPNS0_12SplitterTypeEiPNS0_10SubMixTypeEiRKNS0_22TBiquadFilterParameterIfEE(&c);
float_packet(1, (const float[]){0.1f, 0, 0, 0.9f, 0});
c = call(SPLIT, 0, MIX1, 0, PACKET, 0, 0);
imp__ZN2nn5audio32SetSplitterBiquadFilterParameterEPNS0_12SplitterTypeEiPNS0_10SubMixTypeEiRKNS0_22TBiquadFilterParameterIfEE(&c);
commit();
memset(mixes[1].buf, 0, sizeof mixes[1].buf);
render_voice(&voices[0]);
if (effects) CHECK(fabsf(mixes[1].buf[0][0] - 0.1f) < 0.001f);
else CHECK(fabsf(mixes[1].buf[0][0] - 1.0f) < 0.001f);
}
static void splitter(void) {
const float plain = splitter_level(0), filtered = splitter_level(1);
CHECK(fabsf(plain - 1.0f) < 0.0001f);
if (!effects) CHECK(filtered == plain);
else CHECK(fabsf(filtered - 0.1f / 1.9f) < 0.001f);
splitter_voices();
}
int main(void) {

View File

@@ -0,0 +1,84 @@
/* Actual endpoint module with synthetic WinMM metadata. Never opens or records an audio device. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
#include <mmddk.h>
#include <mmdeviceapi.h>
#include <propsys.h>
#include <objbase.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <wchar.h>
/* (the options file beside the executable: hos_paths.h hos_game_path_a, the folder test_audio_output_devices.py runs it in) */
static unsigned synthetic_count = 80;
static int reordered;
static UINT WINAPI fake_count(void) { return synthetic_count; }
static MMRESULT WINAPI fake_caps(UINT_PTR index, LPWAVEOUTCAPSW caps, UINT size) {
(void)index; assert(size == sizeof *caps); memset(caps, 0, size);
wcscpy(caps->szPname, L"Mic \x03b1"); /* Duplicate Unicode labels, distinct endpoint IDs. */
return MMSYSERR_NOERROR;
}
static MMRESULT WINAPI fake_message(HWAVEOUT device, UINT message, DWORD_PTR value, DWORD_PTR bytes) {
unsigned index = (unsigned)(uintptr_t)device;
if (index >= synthetic_count) return MMSYSERR_BADDEVICEID;
if (reordered && (index == 0 || index == 79)) index = 79 - index;
WCHAR id[80]; swprintf(id, 80, L"endpoint-%u", index);
ULONG length = (ULONG)((wcslen(id) + 1) * sizeof(WCHAR));
if (message == DRV_QUERYFUNCTIONINSTANCEIDSIZE) *(ULONG *)value = length;
else { assert(message == DRV_QUERYFUNCTIONINSTANCEID && bytes >= length); memcpy((void *)value, id, length); }
return MMSYSERR_NOERROR;
}
static HRESULT WINAPI fake_create(REFCLSID clsid, LPUNKNOWN outer, DWORD context, REFIID iid, LPVOID *object) {
(void)clsid; (void)outer; (void)context; (void)iid; *object = NULL; return E_NOINTERFACE;
}
#define waveOutGetNumDevs fake_count
#define waveOutGetDevCapsW fake_caps
#define waveOutMessage fake_message
#define CoCreateInstance fake_create
#include "../host/audio_output_devices.c"
static const char *options_path(void) { /* (triforce_options.ini beside this executable, as the module reads it) */
static char path[MAX_PATH];
const DWORD n = GetModuleFileNameA(NULL, path, MAX_PATH);
char *slash = n ? strrchr(path, 92) : NULL;
assert(slash);
strcpy(slash + 1, "triforce_options.ini");
return path;
}
int main(void) {
FILE *settings = fopen(options_path(), "w"); assert(settings);
fputs("audio_output=2\nmicrophone=1\naudio_output_device_id=endpoint-23\n", settings); fclose(settings);
char id[HOS_OUTPUT_ID_CAP] = {0}, name[HOS_OUTPUT_NAME_CAP]; unsigned generation = 0;
hos_audio_output_preference(id, sizeof id, &generation);
assert(!strcmp(id, "endpoint-23"));
assert(hos_audio_output_count() == 80);
assert(hos_audio_output_info(79, id, sizeof id, name, sizeof name));
assert(!strcmp(id, "endpoint-79") && !strcmp(name, "Mic \xce\xb1"));
assert(!hos_audio_output_info(80, id, sizeof id, name, sizeof name));
char short_id[4] = "old";
assert(!hos_audio_output_info(79, short_id, sizeof short_id, name, sizeof name) && !strcmp(short_id, "old"));
char short_name[6];
assert(hos_audio_output_info(1, id, sizeof id, short_name, sizeof short_name));
assert(!strcmp(short_name, "Mic ")); /* A cut UTF-8 lead byte is removed. */
hos_audio_output_select("endpoint-79");
hos_audio_output_preference(id, sizeof id, &generation);
assert(!strcmp(id, "endpoint-79") && hos_audio_output_resolve(id) == 79);
reordered = 1;
assert(hos_audio_output_resolve(id) == 0); /* Save identity, not a driver index. */
hos_audio_output_select("bad\nnew_setting=1");
hos_audio_output_preference(id, sizeof id, &generation);
assert(!strcmp(id, "endpoint-79"));
synthetic_count = 0;
assert(hos_audio_output_count() == 0 && hos_audio_output_resolve(id) == -1);
synthetic_count = 80;
assert(hos_audio_output_count() == 80 && hos_audio_output_resolve(id) == 0);
hos_audio_output_report(HOS_OUTPUT_FALLBACK | HOS_OUTPUT_UNAVAILABLE);
assert(hos_audio_output_state() == (HOS_OUTPUT_FALLBACK | HOS_OUTPUT_UNAVAILABLE));
hos_audio_output_select(""); hos_audio_output_preference(id, sizeof id, &generation);
assert(!*id);
synthetic_count = 0; hos_audio_output_count();
puts("PASS: endpoint metadata, 80 devices, Unicode/duplicate names, stable IDs, preference mailbox and reconnect");
return 0;
}

View File

@@ -4,6 +4,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../host/audio_output_devices.h"
typedef void *HWAVEOUT;
typedef char *LPSTR;
@@ -32,7 +33,20 @@ static int queued[10];
static WAVEHDR *known[10];
static char last_log[512];
static const char *test_getenv(const char *name) { (void)name; return NULL; }
static const char *device_override;
static char requested_output[HOS_OUTPUT_ID_CAP];
static unsigned requested_generation = 1;
static int named_device = 1, route_state;
static int fail_named_open;
static const char *test_getenv(const char *name) { return !strcmp(name, "HOS_AUDIO_DEVICE") ? device_override : NULL; }
void hos_audio_output_preference(char *id, int capacity, unsigned *generation) {
if (*generation != requested_generation) {
CHECK(audio_output_copy_id(id, (size_t)capacity, requested_output));
*generation = requested_generation;
}
}
int hos_audio_output_resolve(const char *id) { return !strcmp(id, "named-endpoint") ? named_device : -1; }
void hos_audio_output_report(int state) { route_state = state; }
static void hos_log(const char *format, ...) {
va_list args;
va_start(args, format);
@@ -54,9 +68,10 @@ static MMRESULT test_open(HWAVEOUT *out, unsigned device, const WAVEFORMATEX *f,
CHECK(f->nBlockAlign == 2 * f->nChannels && f->nAvgBytesPerSec == 48000 * f->nBlockAlign);
last_channels = f->nChannels;
open_calls++;
if (fail_named_open && device == (unsigned)named_device) return 7;
if (opens_fail) return 6; /* (MMSYSERR_NODRIVER: the audio service down) */
if (fail_open || (fail_open6 && f->nChannels == 6)) return 7; /* (MMSYSERR_NOMEM; a device without 5.1: 32) */
*out = (void *)(uintptr_t)1;
*out = (void *)(uintptr_t)(device == WAVE_MAPPER ? 1 : device + 2);
return 0;
}
static MMRESULT test_prepare(HWAVEOUT out, WAVEHDR *h, unsigned size) {
@@ -74,7 +89,7 @@ static MMRESULT test_write(HWAVEOUT out, WAVEHDR *h, unsigned size) {
write_calls++;
if (gone_write_at && write_calls == gone_write_at) return 6; /* (MMSYSERR_NODRIVER) */
if (!(h->dwFlags & WHDR_PREPARED)) return 34; /* WAVERR_UNPREPARED: no completion follows. */
if (fail_write && write_calls == 1) return 7; /* MMSYSERR_NOMEM: no buffer was queued. */
if (fail_write && (fail_write < 0 || write_calls == 1)) return 7; /* MMSYSERR_NOMEM: no buffer was queued. */
queued[i] = 1;
h->dwFlags = (h->dwFlags & ~WHDR_DONE) | WHDR_INQUEUE;
accepted++;
@@ -131,6 +146,18 @@ static void frames(int count, int complete) {
if (complete) complete_all();
}
}
/* one frame mixed for `channels`, 7777 past its end: what a copy with another count would take */
static void mixed_frame(int channels) {
int16_t pcm[FRAME * 6];
for (int i = 0; i < FRAME * 6; i++) pcm[i] = (int16_t)(i < FRAME * channels ? 100 + i : 7777);
output_frame(pcm);
}
static int blocks_hold(int16_t value) {
for (int b = 0; b < NBLOCKS; b++)
for (int i = 0; i < FRAME * 2 * 6; i++)
if (blocks[b][i] == value) return 1;
return 0;
}
int main(int argc, char **argv) {
CHECK(argc == 2);
scenario = argv[1];
@@ -139,16 +166,205 @@ int main(int argc, char **argv) {
fail_unprepare = !strcmp(scenario, "unprepare");
fail_open = !strcmp(scenario, "open");
if (!strcmp(scenario, "bounded")) fail_prepare = -1;
if (!strcmp(scenario, "surround") || !strcmp(scenario, "fallback")) speakers = 6;
fail_open6 = !strcmp(scenario, "fallback");
if (!strcmp(scenario, "surround") || !strcmp(scenario, "fallback") || !strcmp(scenario, "upmix") ||
!strcmp(scenario, "downmix") || !strcmp(scenario, "retry"))
speakers = 6;
fail_open6 = !strcmp(scenario, "fallback") || !strcmp(scenario, "upmix");
opens_fail = !strcmp(scenario, "retry") || !strcmp(scenario, "same-layout-retry");
output_open();
if (fail_open6) {
if (!strcmp(scenario, "named-stall-budget") || !strcmp(scenario, "named-backoff")) {
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
uint64_t previous_wait = 0;
for (int attempt = 0; attempt < 10; attempt++) {
CHECK(out_named_active && wout);
frames(NBLOCKS * 2, 0); /* Open succeeds, but no queued block ever completes. */
now_ms += 1;
frames(1, 0);
now_ms += 1501;
frames(1, 0);
printf("OBSERVE %s: named stall %d, named=%d fallback=%d reopens=%d\n",
scenario, attempt + 1, out_named_active, !!(route_state & HOS_OUTPUT_FALLBACK), out_reopens);
fflush(stdout);
CHECK(wout && !out_named_active && (route_state & HOS_OUTPUT_FALLBACK));
const uint64_t delay = out_named_retry_at - now_ms;
if (!strcmp(scenario, "named-backoff")) {
CHECK(delay >= previous_wait);
CHECK(attempt == 0 || delay > previous_wait || delay == 60000);
previous_wait = delay;
}
const int before = accepted;
frames(4, 1);
CHECK(accepted == before + 2); /* Fallback still plays after more than six named stalls. */
now_ms = out_named_retry_at;
output_route_update();
}
} else if (!strcmp(scenario, "named-open-failure")) {
fail_named_open = 1;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(wout && !out_named_active && (route_state & HOS_OUTPUT_FALLBACK));
frames(4, 1);
for (int attempt = 0; attempt < 8; attempt++) {
complete_all();
if (fill_frames) frames(1, 1);
frames(3, 0); /* A queued fallback block plus a partially mixed one. */
const int closes = close_calls, resets = reset_calls, fill = fill_frames, calls = open_calls;
int queued_before[10]; memcpy(queued_before, queued, sizeof queued);
HWAVEOUT fallback = wout;
now_ms = out_named_retry_at;
output_route_update();
CHECK(open_calls > calls); /* Actually attempted the resolvable named endpoint. */
CHECK(wout == fallback && close_calls == closes && reset_calls == resets && fill_frames == fill);
CHECK(!memcmp(queued_before, queued, sizeof queued));
frames(3, 1);
}
fail_named_open = 0;
speakers = 6;
now_ms = out_named_retry_at;
output_route_update(); /* A successful probe switches layout before the next mix. */
CHECK(out_named_active && out_channels == 6 && !route_state && fill_frames == 0);
mixed_frame(out_channels);
CHECK(fill_frames == 1 && !blocks_hold(7777));
} else if (!strcmp(scenario, "named-retry-stereo")) {
fail_named_open = 1, speakers = 6;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(!out_named_active && out_channels == 6);
fail_named_open = 0, fail_open6 = 1;
now_ms = out_named_retry_at;
output_route_update();
CHECK(out_named_active && out_channels == 2 && last_channels == 2 && last_device == (unsigned)named_device);
mixed_frame(out_channels);
CHECK(fill_frames == 1 && !blocks_hold(7777));
} else if (!strcmp(scenario, "named-write-failure")) {
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(out_named_active);
out_named_retry_wait = 60000;
fail_write = -1;
frames(6200, 1);
CHECK(accepted == 0 && unprepare_calls > 3000);
CHECK(out_named_retry_wait == 60000); /* Reusing a never-queued header is not consumed audio. */
} else if (!strcmp(scenario, "named-healthy-reset")) {
fail_named_open = 1;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(out_named_retry_wait > 3000);
/* Even a long-lived healthy fallback must retain the named endpoint's backoff. */
frames(6200, 1);
CHECK(out_named_retry_wait > 3000);
fail_named_open = 0;
now_ms = out_named_retry_at;
output_route_update();
CHECK(out_named_active && out_named_retry_wait > 3000);
now_ms += 60000;
frames(NBLOCKS * 2, 0); /* Elapsed time and queued writes are not proof of consumption. */
CHECK(out_named_retry_wait > 3000);
complete_all();
frames(6200, 1); /* More than 30 seconds of completed 10 ms blocks. */
CHECK(out_named_retry_wait == 3000);
} else if (!strcmp(scenario, "selection")) {
CHECK(last_device == WAVE_MAPPER);
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(last_device == 1 && out_named_active && !route_state && close_calls == 1);
requested_output[0] = 0, requested_generation++;
output_route_update();
CHECK(last_device == WAVE_MAPPER && !out_named_active && close_calls == 2);
} else if (!strcmp(scenario, "named-missing")) {
named_device = -1;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(last_device == WAVE_MAPPER && (route_state & HOS_OUTPUT_FALLBACK));
const int calls = open_calls;
named_device = 73; /* The endpoint returns at a new index, beyond the former microphone-size limits. */
output_route_update();
CHECK(open_calls == calls);
now_ms += 3001;
output_route_update();
CHECK(last_device == 73 && out_named_active && !route_state);
} else if (!strcmp(scenario, "named-override")) {
device_override = "7";
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(last_device == 7 && (route_state & HOS_OUTPUT_OVERRIDE) && !out_named_active);
} else if (!strcmp(scenario, "named-format")) {
speakers = 6, fail_open6 = 1;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(last_device == 1 && last_channels == 2 && out_named_active);
CHECK(out_channels == 2 && !(route_state & HOS_OUTPUT_FALLBACK));
} else if (!strcmp(scenario, "layout-reopen")) {
/* This PCM was mixed for stereo. Reopening as surround must drop it before the ring copy. */
speakers = 6, default_key++, now_ms += 1001;
mixed_frame(2);
CHECK(out_channels == 6 && fill_frames == 0 && accepted == 0 && !blocks_hold(7777));
frames(2, 1);
CHECK(fill_frames == 0 && accepted == 1 && hdr[0].dwBufferLength == FRAME * 2 * 6 * 2);
output_close();
out_retry = 1, out_retry_at = now_ms, speakers = 2, now_ms += 1001;
mixed_frame(6);
CHECK(out_channels == 2 && fill_frames == 0 && accepted == 1);
frames(2, 1);
CHECK(accepted == 2 && hdr[0].dwBufferLength == FRAME * 2 * 2 * 2);
} else if (!strcmp(scenario, "named-default-change")) {
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
int calls = open_calls;
default_key++, now_ms += 2000;
frames(2, 1);
CHECK(last_device == 1 && open_calls == calls);
} else if (!strcmp(scenario, "pre-mix")) {
/* Same order as renderer_main: route first, then construct PCM using the selected sink's channels. */
speakers = 6;
strcpy(requested_output, "named-endpoint"), requested_generation++;
output_route_update();
CHECK(out_channels == 6 && out_named_active && fill_frames == 0);
mixed_frame(out_channels);
CHECK(fill_frames == 1 && !blocks_hold(7777));
frames(1, 1);
CHECK(accepted == 1 && hdr[0].dwBufferLength == FRAME * 2 * 6 * 2);
CHECK(blocks[0][FRAME * 6 - 1] == (int16_t)(100 + FRAME * 6 - 1));
} else if (fail_open6) {
CHECK(open_calls == 4 && last_channels == 2 && last_device == WAVE_MAPPER); /* (5.1 on all three, then stereo) */
CHECK(out_channels == 2 && hdr[0].dwBufferLength == FRAME * 2 * 2 * 2);
CHECK(strstr(last_log, "default device") && strstr(last_log, "stereo"));
logs = 0;
frames(40, 1);
CHECK(accepted == 20 && !logs);
if (!strcmp(scenario, "upmix")) {
frames(10, 1);
fail_open6 = 0; /* the new default takes 5.1 */
default_key = 12;
now_ms += 1000;
const int before = accepted;
mixed_frame(2); /* mixed in stereo before the move */
CHECK(close_calls == 1 && open_calls == 5 && out_channels == 6);
CHECK(fill_block == 0 && fill_frames == 0 && !blocks_hold(7777)); /* nothing of it queued */
frames(2, 1);
CHECK(accepted == before + 1 && blocks[0][FRAME * 6 - 1] == (int16_t)(FRAME * 6 - 1));
CHECK(blocks[0][FRAME * 6] == 31);
} else {
frames(40, 1);
CHECK(accepted == 20 && !logs);
}
} else if (opens_fail) {
const int attempts = !strcmp(scenario, "same-layout-retry") ? 3 : 6;
CHECK(open_calls == attempts && !wout && out_channels == 2);
mixed_frame(2);
CHECK(open_calls == attempts); /* not again within the second */
opens_fail = 0; /* a device plugged in, and it takes the requested layout */
now_ms += 1000;
mixed_frame(2);
CHECK(wout && open_calls == attempts + 1 && !write_calls && !blocks_hold(7777));
if (!strcmp(scenario, "same-layout-retry")) {
CHECK(out_channels == 2 && fill_frames == 1);
frames(1, 1);
} else {
CHECK(out_channels == 6 && fill_frames == 0);
frames(2, 1);
}
CHECK(accepted == 1);
CHECK(blocks[0][FRAME * out_channels] == (!strcmp(scenario, "same-layout-retry") ? 0 : 31));
} else if (fail_open) {
CHECK(open_calls == 3); /* (the default, then both devices; HOS_AUDIO_DEVICE unset) */
CHECK(!wout);
@@ -164,6 +380,19 @@ int main(int argc, char **argv) {
CHECK(accepted == 20 && prepare_calls == 20 && write_calls == 20 && !logs);
CHECK(blocks[9][0] == 38 * 31 && blocks[9][FRAME * 6] == 39 * 31);
CHECK(blocks[9][FRAME * 6 - 1] == (int16_t)(38 * 31 + FRAME * 6 - 1));
} else if (!strcmp(scenario, "downmix")) {
CHECK(out_channels == 6);
frames(10, 1);
fail_open6 = 1; /* the new default takes stereo only */
default_key = 12;
now_ms += 1000;
const int before = accepted;
mixed_frame(6);
CHECK(close_calls == 1 && out_channels == 2 && hdr[0].dwBufferLength == FRAME * 2 * 2 * 2);
CHECK(fill_block == 0 && fill_frames == 0); /* the 5.1 frame not queued as two stereo ones */
frames(2, 1);
CHECK(accepted == before + 1 && blocks[0][FRAME * 2 - 1] == (int16_t)(FRAME * 2 - 1));
CHECK(blocks[0][FRAME * 2] == 31);
} else if (!strcmp(scenario, "lost")) {
gone_write_at = 25; /* a Bluetooth headset off: its 25th block, "no driver" */
frames(60, 1);
@@ -204,6 +433,7 @@ int main(int argc, char **argv) {
now_ms += 600;
frames(1, 1);
CHECK(close_calls == 1 && open_calls == 2 && last_device == WAVE_MAPPER && out_default_key == 12);
CHECK(fill_frames == 1); /* stereo again: the frame mixed before the move kept */
now_ms += 2000;
frames(2, 1);
CHECK(open_calls == 2); /* the same default: not opened again */

View File

@@ -9,6 +9,8 @@ typedef struct { uint64_t x[32]; } Ctx;
static _Alignas(8) uint8_t guest[4096];
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); exit(1); } } while (0)
static void *guest_ptr(uint64_t address) { CHECK(address < sizeof guest); return guest + address; }
/* (host/hos.h's, over this fixture's guest: NULL unless all n bytes lie in it) */
static void *hos_guest_range(uint64_t a, uint64_t n) { return a < sizeof guest && n <= sizeof guest - a ? guest + a : NULL; }
#define GP(a) guest_ptr(a)
#define G64(a) (*(uint64_t *)GP(a))
#define G32(a) (*(uint32_t *)GP(a))

96
tests/cmpflags_test.c Normal file
View File

@@ -0,0 +1,96 @@
/* tests/test_cmpflags.py's driver: each guest word as the lift translates it now (nx2/cmpflags.py: a subtraction's V as N xor
(a < b, signed)) against the same word as before, from one Ctx, the whole Ctx compared after (every register, N, Z, C, V).
cmpflags_test sweep every pair of the edge values below in Xn and Xm (the words read x1 and x2), under each
of the 16 NZCV values (CCMP and CCMN read them), the other registers random
cmpflags_test random <n> <seed> n random states per word (registers: random, edges, near each other)
Exit 0: no mismatch, and V came out both 0 and 1 for every subtraction. 1: a mismatch. */
#include "a64.h"
#include <stdio.h>
#include <stdlib.h>
#include "cmpflags_lifted.h"
static uint64_t rs;
static uint64_t rnd(void) { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }
static const uint64_t EDGE[] = {
0, 1, 2, 3, 0xFFFFFFFFFFFFFFFFull, 0xFFFFFFFFFFFFFFFEull,
0x7FFFFFFFFFFFFFFFull, 0x8000000000000000ull, 0x8000000000000001ull, 0x7FFFFFFFFFFFFFFEull,
0x000000007FFFFFFFull, 0x0000000080000000ull, 0x0000000080000001ull, 0x000000007FFFFFFEull, 0x00000000FFFFFFFFull,
0x00000000FFFFFFFEull, 0x0000000100000000ull, 0xFFFFFFFF80000000ull, 0xFFFFFFFF7FFFFFFFull, 0xFFFFFFFF00000000ull,
5, 4, 6, 7, 4095, 4096, 4094, 0x1000, 0xFFF, 0x1001,
0x00000000000000FFull, 0x0000000000000100ull, 0xFFFFFFFFFFFFFF80ull, 0x0000000000000080ull, 0x0000000000007FFFull,
0x0000000000008000ull, 0x3FFFFFFFFFFFFFFFull, 0xC000000000000000ull, 0x40000000ull, 0xC0000000ull,
};
enum { NEDGE = sizeof EDGE / sizeof EDGE[0] };
static uint64_t checks, mismatches, v0[64], v1[64];
static void check(int k, const Ctx *start) {
static Ctx a, b;
memcpy(&a, start, sizeof a);
memcpy(&b, start, sizeof b);
CASES[k].old(&a);
CASES[k].now(&b);
checks++;
if (a.v) v1[k]++; else v0[k]++;
if (memcmp(&a, &b, sizeof a) != 0 && mismatches++ < 12)
printf("MISMATCH %s: x1 %#llx x2 %#llx nzcv %d%d%d%d -> before nzcv %d%d%d%d x3 %#llx, now nzcv %d%d%d%d x3 %#llx\n",
CASES[k].name, (unsigned long long)start->x[1], (unsigned long long)start->x[2], start->n, start->z, start->c,
start->v, a.n, a.z, a.c, a.v, (unsigned long long)a.x[3], b.n, b.z, b.c, b.v, (unsigned long long)b.x[3]);
}
static void random_regs(Ctx *c) {
for (int r = 0; r < 32; r++) c->x[r] = rnd();
}
static uint64_t operand(void) {
switch (rnd() % 4) {
case 0: return EDGE[rnd() % NEDGE];
case 1: return EDGE[rnd() % NEDGE] + (rnd() % 5) - 2;
case 2: return (uint64_t)(int64_t)(int32_t)rnd();
default: return rnd();
}
}
int main(int argc, char **argv) {
if (argc < 2) return 2;
static Ctx start;
const int ncases = (int)(sizeof CASES / sizeof CASES[0]);
if (!strcmp(argv[1], "sweep")) {
rs = 11;
for (int k = 0; k < ncases; k++)
for (int i = 0; i < NEDGE; i++)
for (int j = 0; j < NEDGE; j++)
for (int f = 0; f < 16; f++) {
memset(&start, 0, sizeof start);
random_regs(&start);
start.x[1] = EDGE[i], start.x[2] = EDGE[j];
start.n = f >> 3 & 1, start.z = f >> 2 & 1, start.c = f >> 1 & 1, start.v = f & 1;
check(k, &start);
}
} else if (!strcmp(argv[1], "random")) {
const uint64_t n = argc > 2 ? strtoull(argv[2], 0, 10) : 1000000;
rs = argc > 3 ? strtoull(argv[3], 0, 10) : 1;
for (int k = 0; k < ncases; k++)
for (uint64_t i = 0; i < n; i++) {
memset(&start, 0, sizeof start);
random_regs(&start);
start.x[1] = operand(), start.x[2] = operand();
if (rnd() % 4 == 0) start.x[2] = start.x[1] + (rnd() % 3) - 1; /* (equal or one apart) */
const unsigned f = (unsigned)rnd();
start.n = f & 1, start.z = f >> 1 & 1, start.c = f >> 2 & 1, start.v = f >> 3 & 1;
check(k, &start);
}
} else {
return 2;
}
printf("cmpflags %s: %llu checks over %d guest words, %llu mismatches\n", argv[1], (unsigned long long)checks, ncases,
(unsigned long long)mismatches);
if (mismatches) return 1;
for (int k = 0; k < ncases; k++)
if (CASES[k].sub && (!v0[k] || !v1[k])) {
printf("%s: V came out only %d: the cases do not reach both\n", CASES[k].name, v1[k] ? 1 : 0);
return 4;
}
return 0;
}

221
tests/compute_gate_test.cpp Normal file
View File

@@ -0,0 +1,221 @@
// compute_gate (gpu/vk/compute_gate.h): how many of the driver's compute compiles run at once. The budget the memory gives,
// the rule for one more by the compiles' weights, and the gate itself under threads: one always let through, one more only
// while its weight fits and the memory is there, never more than an asked limit, a stop that ends a wait without a turn.
// No game, no GPU.
#include "../gpu/vk/compute_gate.h"
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
using compute_gate::budget_for;
using compute_gate::kFreeMB;
using compute_gate::kMost;
using compute_gate::kPinnedMB;
using compute_gate::kReserveMB;
using compute_gate::kUnknownMB;
using compute_gate::may_start;
namespace {
int failures = 0;
void expect(bool ok, const char* what) {
if (!ok) std::printf("FAIL: %s\n", what), failures++;
}
void rules() {
expect(compute_gate::weight(true, 0) == kPinnedMB && compute_gate::weight(false, 0) == kFreeMB && kPinnedMB > kFreeMB,
"a compile held to 32 lanes weighs more");
expect(compute_gate::weight(true, 2190) == compute_gate::kHeavyMB && compute_gate::weight(true, 1892) == kPinnedMB &&
compute_gate::weight(false, 12329) == kFreeMB && compute_gate::kHeavyMB > kPinnedMB,
"a pinned compile of 2,000 phis or more weighs the most; at the driver's lanes the phis do not count");
expect(compute_gate::weight(true, 58, true) == compute_gate::kMeshMB && compute_gate::kMeshMB > kPinnedMB &&
compute_gate::kHeavyMB > compute_gate::kMeshMB && compute_gate::weight(true, 80000, true) == compute_gate::kHeavyMB &&
compute_gate::weight(false, 58, true) == kFreeMB && compute_gate::weight(true, 58) == kPinnedMB,
"a pinned mesh fallback stage weighs more than an ordinary pinned compile, whatever its phis");
expect(budget_for(0) == 0 && budget_for(kReserveMB) == 0 && budget_for(kUnknownMB) == 0, "no budget: one at a time");
expect(budget_for(kReserveMB + 100) == 100, "the budget: what is past the reserve");
const uint64_t plenty = uint64_t(1) << 40, budget = 16 * 1024;
// (no gate)
expect(may_start(99, 0, kPinnedMB, 0, false, 0, 0), "no limit and no memory rule: no gate");
// (none running: always, whatever the memory)
expect(may_start(0, 0, kPinnedMB, 0, true, 0, 0) && may_start(0, 0, kPinnedMB, 1, false, 0, 0), "the first one always starts");
// (an asked limit: the limit alone)
expect(!may_start(4, 0, kFreeMB, 4, false, 0, plenty) && may_start(3, 0, kFreeMB, 4, false, 0, 0), "an asked limit alone");
// (by memory: the weights in the budget, and the weight available now)
expect(may_start(1, kPinnedMB, kFreeMB, 0, true, budget, plenty), "one more that fits");
expect(!may_start(1, budget - kFreeMB + 1, kFreeMB, 0, true, budget, plenty), "not one more past the budget");
expect(!may_start(1, kFreeMB, kFreeMB, 0, true, budget, kReserveMB + kFreeMB - 1), "not one more without the memory now");
expect(may_start(1, kFreeMB, kFreeMB, 0, true, budget, kReserveMB + kFreeMB), "one more with exactly its memory");
expect(!may_start(1, kFreeMB, kFreeMB, 0, true, budget, kUnknownMB), "memory unknown now: no more than one");
expect(!may_start(kMost, 0, 0, 0, true, plenty, plenty), "never more than kMost");
expect(!may_start(1, kFreeMB, kFreeMB, 0, true, 0, plenty), "no budget: one at a time");
// (the PC this was measured on: about 16 GB past the reserve: 8 held to 32 lanes, or kMost others)
expect(may_start(7, 7 * kPinnedMB, kPinnedMB, 0, true, budget, plenty) &&
!may_start(8, 8 * kPinnedMB, kPinnedMB, 0, true, budget, plenty) &&
may_start(kMost - 1, (kMost - 1) * kFreeMB, kFreeMB, 0, true, budget, plenty),
"16 GB past the reserve: 8 held to 32 lanes, or 16 others");
// (the freed memory handed back: only where there is a gate, and only after a long compile)
expect(!compute_gate::trims(false, 60000), "no gate: nothing is handed back, as before");
expect(!compute_gate::trims(true, compute_gate::kTrimAfterMs - 1), "a short compile hands nothing back");
expect(compute_gate::trims(true, compute_gate::kTrimAfterMs) && compute_gate::trims(true, 600000), "a long one does");
// (RADV, an integrated GPU: a Radeon 760M with 12 GB killed for memory while its first start compiled the mesh
// fallback's stages on 12 threads. By the phis alone, at twice what was measured on discrete cards, as the Intel weights
// are: the 80,000-phi stages took 2.9 GB, those up to 29,400 under 700 MB)
using compute_gate::weight_radv;
expect(weight_radv(79947) == compute_gate::kRadvBigMB && weight_radv(compute_gate::kRadvBigPhis) == compute_gate::kRadvBigMB &&
compute_gate::kRadvBigMB >= 2 * 2900,
"RADV: a stage of 80,000 phis weighs less than twice its measured 2.9 GB");
expect(weight_radv(29372) == compute_gate::kRadvMidMB && weight_radv(compute_gate::kRadvBigPhis - 1) == compute_gate::kRadvMidMB &&
compute_gate::kRadvMidMB >= 2 * 700,
"RADV: a stage of up to 29,400 phis weighs less than twice its measured 700 MB");
expect(weight_radv(0) == compute_gate::kRadvMB && weight_radv(compute_gate::kRadvMidPhis - 1) == compute_gate::kRadvMB &&
compute_gate::kRadvMB >= 2 * 200 && compute_gate::kRadvMB < compute_gate::kRadvMidMB &&
compute_gate::kRadvMidMB < compute_gate::kRadvBigMB,
"RADV: a small stage weighs the least, and not under twice 200 MB");
// (the 760M's PC at its first start, say 7 GB available: 3 GB past the reserve. The large stages run alone, the small ones
// side by side, up to what fits; with plenty of memory, as many as before)
{
const uint64_t avail = 7 * 1024, b = budget_for(avail);
expect(!may_start(1, compute_gate::kRadvMB, compute_gate::kRadvBigMB, 0, true, b, avail) &&
may_start(0, 0, compute_gate::kRadvBigMB, 0, true, b, avail),
"RADV, 7 GB available: a stage of 80,000 phis starts beside another");
expect(may_start(1, compute_gate::kRadvMidMB, compute_gate::kRadvMidMB, 0, true, b, avail) &&
!may_start(2, 2 * compute_gate::kRadvMidMB, compute_gate::kRadvMidMB, 0, true, b, avail),
"RADV, 7 GB available: three stages of 10,000 phis or more at once");
expect(may_start(5, 5 * compute_gate::kRadvMB, compute_gate::kRadvMB, 0, true, b, avail) &&
!may_start(6, 6 * compute_gate::kRadvMB, compute_gate::kRadvMB, 0, true, b, avail),
"RADV, 7 GB available: not 6 small stages at once, or more");
expect(!may_start(3, 3 * compute_gate::kRadvMB, compute_gate::kRadvMB, 0, true, b, kReserveMB + compute_gate::kRadvMB - 1),
"RADV: one more starts with the memory gone meanwhile");
const uint64_t lots = 32 * 1024;
expect(may_start(kMost - 1, (kMost - 1) * compute_gate::kRadvMB, compute_gate::kRadvMB, 0, true, budget_for(lots), lots),
"RADV, 32 GB available: fewer small stages at once than kMost");
}
// (where RADV's gate is on by default: an integrated GPU on a PC with under 13 GB of RAM, as the 12 GB that was killed. The Steam Deck
// (16 GB, about 14.5 GB the system's) and 16 GB APUs keep main's rule: nobody has run the gate there)
{
using compute_gate::radv_by_memory;
expect(radv_by_memory(true, 11 * 1024) && radv_by_memory(true, 7 * 1024), "RADV, integrated, 12 or 8 GB: gated");
expect(!radv_by_memory(true, 14848), "RADV, the Steam Deck (about 14.5 GB of RAM to the system): not gated, as on main");
expect(!radv_by_memory(true, 15 * 1024) && !radv_by_memory(true, 32 * 1024), "RADV, integrated, 16 GB or more: not gated");
expect(!radv_by_memory(false, 8 * 1024), "RADV, a discrete card: not gated, whatever the RAM");
expect(!radv_by_memory(true, 0), "RADV, integrated, the RAM not known: not gated, as on main");
}
// (a cgroup's limit: what memory.max leaves past memory.current. None set: no bound from it)
{
using compute_gate::cgroup_room_mb;
expect(cgroup_room_mb("max\n", 1ull << 30) == compute_gate::kUnknownMB, "cgroup: no limit (max): no bound");
expect(cgroup_room_mb("", 0) == compute_gate::kUnknownMB && cgroup_room_mb(nullptr, 0) == compute_gate::kUnknownMB &&
cgroup_room_mb("junk", 0) == compute_gate::kUnknownMB,
"cgroup: nothing read, or not a number: no bound");
expect(cgroup_room_mb("17179869184\n", 12ull << 30) == 4096, "cgroup: a 16 GB limit with 12 GB in use leaves 4 GB");
expect(cgroup_room_mb("8589934592\n", 9ull << 30) == 0, "cgroup: past its limit leaves nothing");
expect(budget_for(std::min<uint64_t>(30 * 1024, cgroup_room_mb("17179869184", 12ull << 30))) == 0,
"cgroup: a host with 30 GB free in a slice with 4 GB left compiles one at a time");
}
}
/// `threads` threads each take `each` turns of weight_mb at a gate; avail_mb is what the memory reads. The most that ran at once
int most_running(unsigned limit, bool by_memory, uint64_t budget_mb, uint64_t weight_mb, uint64_t avail_mb, unsigned threads,
int each, uint64_t* waits = nullptr) {
compute_gate::Gate gate;
gate.set(limit, by_memory, budget_mb);
std::atomic<int> running{0}, most{0}, turns{0};
std::vector<std::thread> pool;
for (unsigned t = 0; t < threads; t++)
pool.emplace_back([&] {
for (int i = 0; i < each; i++) {
if (!gate.enter(weight_mb, [&] { return avail_mb; }, [] { return false; })) continue;
const int now = ++running;
int seen = most.load();
while (now > seen && !most.compare_exchange_weak(seen, now)) {}
std::this_thread::sleep_for(std::chrono::microseconds(300));
--running;
turns++;
gate.leave(weight_mb);
}
});
for (std::thread& t : pool) t.join();
expect(turns.load() == (int)threads * each, "every compile got its turn: none is left out");
expect(running.load() == 0, "nothing is left running");
unsigned gate_most = 0;
uint64_t gate_waits = 0;
gate.seen(&gate_most, &gate_waits);
expect((int)gate_most == most.load(), "the gate's own count of the most at once is what ran");
if (waits) *waits = gate_waits;
return most.load();
}
void gate() {
const uint64_t plenty = uint64_t(1) << 30, none = 0;
uint64_t waits = 0;
expect(most_running(0, false, 0, kPinnedMB, none, 8, 200) > 1, "no gate: they run together, as before");
expect(most_running(1, false, 0, kFreeMB, plenty, 8, 200, &waits) == 1 && waits > 0, "an asked 1: one at a time");
{
const int most = most_running(3, false, 0, kFreeMB, none, 8, 200);
expect(most <= 3 && most >= 2, "an asked 3: up to three, whatever the memory");
}
{
const int most = most_running(0, true, 3 * kPinnedMB, kPinnedMB, plenty, 8, 200);
expect(most <= 3 && most >= 2, "a budget of three pinned compiles: up to three of them");
}
{
const int most = most_running(0, true, 3 * kPinnedMB, kFreeMB, plenty, 20, 100);
expect(most > 3 && most <= (int)kMost, "the same budget: more of the light ones, never past kMost");
}
// (the budget allows several, but there is not a compile's worth of memory available now: one at a time, and still every one)
expect(most_running(0, true, 16 * 1024, kPinnedMB, none, 8, 100) == 1, "within the budget without the memory: one at a time");
expect(most_running(0, true, 16 * 1024, kPinnedMB, kReserveMB + kPinnedMB - 1, 8, 100) == 1, "one MB short: one at a time");
}
void stopped() {
// (one holds the only turn; the one waiting behind it is told to stop: it gets no turn, and does not hang)
compute_gate::Gate gate;
gate.set(1, false);
expect(gate.enter(kFreeMB, [] { return uint64_t(0); }, [] { return false; }), "the first turn");
std::atomic<bool> stop{false}, returned{false}, got{true};
std::thread waiter([&] {
got = gate.enter(kFreeMB, [] { return uint64_t(0); }, [&] { return stop.load(); });
returned = true;
});
std::this_thread::sleep_for(std::chrono::milliseconds(100));
expect(!returned.load(), "the second waits while the first runs");
stop = true;
waiter.join();
expect(returned.load() && !got.load(), "a stop ends the wait with no turn taken");
gate.leave(kFreeMB);
stop = false;
expect(gate.enter(kFreeMB, [] { return uint64_t(0); }, [] { return true; }), "a free gate gives a turn even when stopped");
gate.leave(kFreeMB);
}
void memory_returns() {
// (the second waits for memory, not for a turn: it starts when the memory is back, without any leave())
compute_gate::Gate gate;
gate.set(0, true, 16 * 1024);
std::atomic<uint64_t> avail{0};
expect(gate.enter(kPinnedMB, [&] { return avail.load(); }, [] { return false; }), "the first turn");
std::atomic<bool> entered{false};
std::thread waiter([&] { entered = gate.enter(kPinnedMB, [&] { return avail.load(); }, [] { return false; }); });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
expect(!entered.load(), "no second compile while the memory is short");
avail = kReserveMB + kPinnedMB;
waiter.join();
expect(entered.load(), "the second starts once the memory is available again");
gate.leave(kPinnedMB);
gate.leave(kPinnedMB);
}
} // namespace
int main() {
rules();
gate();
stopped();
memory_returns();
if (failures) return std::printf("%d checks failed\n", failures), 1;
std::printf("compute_gate: ok\n");
return 0;
}

1172
tests/control_test.c Normal file

File diff suppressed because it is too large Load Diff

135
tests/crash_record_test.c Normal file
View File

@@ -0,0 +1,135 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
(Triforce) tests/test_crash_record.py's fixture: host/hos_crash_record.c as it is (included whole, for its statics), with
host/mkw_glue.c's record_exception and hos_crash_record_fatal cut in at RECORD_EXCEPTION by the test. The game, its
threads and its guest memory are stand-ins. One mode a run: argv[1] the game folder, argv[2] the mode. */
#define _GNU_SOURCE
#define _CRT_SECURE_NO_WARNINGS
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hos_crash_record.c"
void hos_log(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
}
const char *hos_version(void) { return "fixture-v1"; }
typedef struct Ctx { uint64_t x[32]; } Ctx;
typedef struct HosThread { char name[64]; } HosThread;
static HosThread guest_thread = {"fixture-thread"};
static Ctx guest_context;
static unsigned char guest_memory[1024];
#define A64_MEM guest_memory
#define HOS_GUEST_SPACE sizeof guest_memory
static Ctx *hos_ctx(void) { return &guest_context; }
static HosThread *hos_self(void) { return &guest_thread; }
static const char *hos_thread_name(HosThread *t) { return t->name; }
/* RECORD_EXCEPTION */
static void authored_context(HosCrashContext *c) {
memset(c, 0, sizeof *c);
c->reason = "unhandled exception";
c->thread = guest_thread.name;
c->code = 0xc0000005u;
c->pc = (uintptr_t)authored_context;
c->sp = (uintptr_t)c;
c->guest_base = (uintptr_t)guest_memory;
c->guest_size = sizeof guest_memory;
c->fault_address = c->guest_base + 64;
c->guest_registers = guest_context.x;
}
#ifdef _WIN32
static LONG WINAPI filter(EXCEPTION_POINTERS *info) {
record_exception(info);
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
static void quit_now(int code) { /* (no atexit: a process ended from outside, or by the game's own ExitProcess) */
#ifdef _WIN32
TerminateProcess(GetCurrentProcess(), (UINT)code);
#else
_exit(code);
#endif
}
int main(int argc, char **argv) {
assert(argc >= 3);
#ifdef _WIN32
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#endif
const char *mode = argv[2];
char log[PATH_CAP];
assert(join(log, sizeof log, argv[1], "triforce_log.txt"));
hos_crash_record_start(argv[1], "fixture-v1", log);
printf("run_id: %s\n", hos_report_run_id());
fflush(stdout);
hos_crash_record_log_notes();
if (!strcmp(mode, "read-only")) { assert(!ready); return 0; }
assert(ready);
for (unsigned i = 0; i < 32; ++i) guest_context.x[i] = 0x1000 + i;
guest_context.x[29] = 64, guest_context.x[30] = 0x80001234;
const uint64_t frames[] = {80, 0x80005678, 0, 0x80009abc};
memcpy(guest_memory + 64, frames, sizeof frames);
{ char stamp[17]; timestamp(0, stamp); assert(!strcmp(stamp, "19700101T000000Z")); }
assert(hos_crash_record_marker(argv[1], session.pid, session.run_id) == (
#ifdef _WIN32
2 /* (Windows: the live owner's lock) */
#else
1
#endif
));
if (!strcmp(mode, "clean")) { hos_crash_clean_end(); hos_crash_clean_end(); return 0; }
if (!strcmp(mode, "return")) return 0; /* (atexit) */
if (!strcmp(mode, "killed")) quit_now(3);
if (!strcmp(mode, "quit-killed")) { hos_crash_quit_asked(); hos_crash_quit_asked(); quit_now(3); }
if (!strcmp(mode, "fatal")) { hos_crash_record_fatal(guest_context.x, "hos_fatal"); quit_now(3); }
if (!strcmp(mode, "device-lost")) {
hos_crash_record_fatal(NULL, "device lost");
hos_crash_record_fatal(NULL, "Vulkan fatal"); /* (a second fatal line never replaces the first record) */
quit_now(3);
}
if (!strcmp(mode, "label")) {
char out[160];
hos_crash_redact(out, sizeof out, "a\tb\x01" "c\xc3\xa9", 6);
printf("label: %s\n", out);
hos_crash_clean_end();
return 0;
}
#ifdef _WIN32
if (!strcmp(mode, "crash")) {
SetUnhandledExceptionFilter(filter);
static volatile uintptr_t address = 0x40;
*(volatile int *)address = 1;
return 91;
}
#endif
HosCrashContext c;
authored_context(&c);
if (!strcmp(mode, "privacy")) {
const char *home = getenv(
#ifdef _WIN32
"USERPROFILE"
#else
"HOME"
#endif
);
snprintf(guest_thread.name, sizeof guest_thread.name, "%s/t", home ? home : "");
}
if (!strcmp(mode, "bounds")) {
struct { char bytes[8]; char guard; } small = {{0}, 'X'};
Text out = {small.bytes, sizeof small.bytes, 0, 0};
format_record(&out, &session, &c, epoch_now(), NULL);
assert(out.full && small.guard == 'X');
}
assert(hos_crash_record_write(&c) == 1);
assert(hos_crash_record_write(&c) == 0); /* (reentry or a second fault: the first record stands) */
hos_crash_clean_end(); /* (no effect once a record was claimed) */
return 0;
}

202
tests/cxx_escape_test.cpp Normal file
View File

@@ -0,0 +1,202 @@
// A C++ exception that leaves the renderer (gpu/vk/cxx_escape.h, renderer_guard.h), with the real headers and hooks
// of its own: the log printed, out of memory printed and exit 4, the FATAL line printed and exit 3 (in the game neither returns).
// The functions are the real MkwVkRenderer table's members behind guard_renderer, called as the host calls them; the threads are
// real ones. No game, window or GPU. One case a process: tests/test_cxx_escape.py runs each and reads what it printed.
#include <atomic>
#include <chrono>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <new>
#include <stdexcept>
#include <string>
#include <system_error>
#include <thread>
#include <vector>
#if defined(__GLIBC__) || __has_include(<gnu/libc-version.h>)
#include <pthread.h>
#define HAVE_DEFAULT_STACK 1 // (pthread_setattr_default_np: a thread that cannot be started, on demand)
#endif
#ifndef _Static_assert // (gpu/render/rx_nvn.h is C: clang, the build's compiler, takes its asserts in C++ too; g++ does not)
#define _Static_assert static_assert
#endif
#include "gpu/vk/renderer_guard.h"
using namespace mkwvk;
static void fail(const char* why) {
std::printf("FAIL %s\n", why);
std::fflush(stdout);
std::_Exit(1);
}
#define CHECK(x) \
do { \
if (!(x)) fail(#x); \
} while (0)
static std::atomic<int> logs{0};
static void hook_log(const char* line) {
logs++;
std::printf("LOG %s\n", line);
std::fflush(stdout);
}
[[noreturn]] static void hook_oom(const char* what) {
std::printf("OOM %s\n", what);
std::fflush(stdout);
std::_Exit(4);
}
[[noreturn]] static void hook_fatal(const char* why) {
std::printf("FATAL %s\n", why);
std::fflush(stdout);
std::_Exit(3);
}
[[noreturn]] static void wait_for_the_thread() { // (a thread's escape ends the process; this one waits for it)
std::this_thread::sleep_for(std::chrono::seconds(20));
fail("the thread's exception did not stop the process");
std::_Exit(1);
}
// (the table's functions as the renderer gives them: each does what the case asks)
static int option_calls = 0;
static int option(int id) {
option_calls++;
if (id == 1) throw std::bad_alloc();
if (id == 2) {
std::vector<int> v;
v.reserve(SIZE_MAX / 2); // (a size past any PC's: std::length_error)
}
if (id == 3) return std::vector<int>{1, 2, 3}.at(7);
if (id == 4) throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again), "thread constructor failed");
if (id == 5) throw std::system_error(std::make_error_code(std::errc::permission_denied), "a lock");
return id * 3;
}
static void submit(const uint64_t* handles, int n) {
if (n == 99) throw std::bad_alloc();
if (n == 98) throw std::bad_array_new_length();
(void)handles;
}
#ifdef HAVE_DEFAULT_STACK
static void no_threads() { // (every thread from here asks for a stack no PC has: pthread_create says EAGAIN, as at the commit limit)
pthread_attr_t a;
pthread_attr_init(&a);
CHECK(pthread_attr_setstacksize(&a, (size_t)1 << 47) == 0); // (128 TB: past the address space)
CHECK(pthread_setattr_default_np(&a) == 0);
pthread_attr_destroy(&a);
bool refused = false;
try {
std::thread([] {}).join();
} catch (const std::system_error&) {
refused = true;
}
if (!refused) { // (this system gave it anyway: nothing to see here)
std::printf("SKIP no thread is refused here\n");
std::exit(0);
}
}
#endif
int main(int argc, char** argv) {
if (argc < 2) fail("no case");
const std::string c = argv[1];
cxx_escape::g_hooks = {hook_log, hook_oom, hook_fatal};
MkwVkRenderer t{};
t.option = option;
t.nvn_submit = submit;
guard_renderer(t);
if (c == "pass") { // (a call that throws nothing: its arguments and result through, nothing said; a null left null)
CHECK(t.option != option && t.nvn_submit != submit);
CHECK(t.option(7) == 21 && option_calls == 1);
const uint64_t h[2] = {1, 2};
t.nvn_submit(h, 2);
CHECK(!t.nvn_present && !t.start && !t.screen_point);
guard_renderer(t); // (again: not wrapped twice)
CHECK(t.option(8) == 24 && option_calls == 2);
CHECK(logs == 0);
std::printf("PASS\n");
return 0;
}
if (c == "entry-bad-alloc") t.option(1);
if (c == "entry-no-notice") { // (the game's hooks: no out-of-memory notice, the FATAL line says it)
cxx_escape::g_hooks.out_of_memory = nullptr;
t.option(1);
}
if (c == "entry-length") t.option(2);
if (c == "entry-range") t.option(3);
if (c == "entry-system-memory") t.option(4);
if (c == "entry-system-other") t.option(5);
if (c == "entry-submit") {
const uint64_t h[1] = {1};
t.nvn_submit(h, 99);
}
if (c == "entry-array-length") t.nvn_submit(nullptr, 98);
if (c == "thread") { // (the replay thread's body: its exception said and stopped on, from that thread)
cxx_escape::spawn_needed("replay", [] { (void)std::vector<int>{1}.at(4); });
wait_for_the_thread();
}
if (c == "thread-memory") {
cxx_escape::spawn_needed("presenter", [](int n) { if (n == 3) throw std::bad_alloc(); }, 3);
wait_for_the_thread();
}
if (c == "fork-join") { // (every part made once, the helpers' starts run on them)
std::atomic<int> parts[6] = {};
static std::atomic<int> starts{0};
cxx_escape::fork_join("texture gather", 6, [&](unsigned i) { parts[i]++; }, [] { starts++; });
for (auto& p : parts) CHECK(p == 1);
CHECK(starts == 5);
cxx_escape::fork_join("texture gather", 1, [&](unsigned i) { parts[i]++; });
CHECK(parts[0] == 2);
std::printf("PASS\n");
return 0;
}
if (c == "fork-join-throws") { // (a helper's exception: said and stopped on)
cxx_escape::fork_join("texture unswizzle", 4, [](unsigned i) {
if (i == 2) throw std::out_of_range("part 2");
std::this_thread::sleep_for(std::chrono::milliseconds(200));
});
fail("fork_join returned after a helper threw");
}
if (c == "fork-join-caller-throws") { // (part(0)'s exception comes out once the helpers are joined, as it would have)
std::atomic<int> done{0};
try {
cxx_escape::fork_join("texture check", 4, [&](unsigned i) {
if (i == 0) throw std::runtime_error("part 0");
std::this_thread::sleep_for(std::chrono::milliseconds(100));
done++;
});
} catch (const std::runtime_error& e) {
CHECK(!std::strcmp(e.what(), "part 0"));
CHECK(done == 3);
std::printf("PASS\n");
return 0;
}
fail("part(0)'s exception did not come out");
}
#ifdef HAVE_DEFAULT_STACK
if (c == "fork-join-no-threads") { // (no helper can be started: the caller makes every part, said once in the log)
no_threads();
std::atomic<int> parts[4] = {};
cxx_escape::fork_join("texture gather", 4, [&](unsigned i) { parts[i]++; });
for (auto& p : parts) CHECK(p == 1);
CHECK(logs == 1);
std::printf("PASS\n");
return 0;
}
if (c == "spawn-no-threads") { // (spawn: false and said; spawn_needed: out of memory)
no_threads();
CHECK(!cxx_escape::spawn("upscaler probe", [] {}));
CHECK(logs == 1);
cxx_escape::spawn_needed("replay", [] {});
fail("spawn_needed returned without its thread");
}
#else
if (c == "fork-join-no-threads" || c == "spawn-no-threads") {
std::printf("SKIP no pthread_setattr_default_np here\n");
return 0;
}
#endif
fail(("the case came back: " + c).c_str());
}

View File

@@ -25,6 +25,10 @@ static uint8_t *at(uint64_t a, size_t n) {
return mem + (a - MEM_BASE);
}
#define A64_PTR(a) at((a), 1)
/* (host/hos.h's, over the stand-in's memory: NULL unless all n bytes lie in it) */
static void *hos_guest_range(uint64_t a, uint64_t n) {
return a >= MEM_BASE && n <= MEM_SIZE && a - MEM_BASE <= MEM_SIZE - n ? mem + (a - MEM_BASE) : NULL;
}
static uint8_t recomp_load8(Ctx *c, uint64_t a) { (void)c, loads++; return *at(a, 1); }
static uint32_t recomp_load32(Ctx *c, uint64_t a) { (void)c, loads++; uint32_t v; memcpy(&v, at(a, 4), 4); return v; }
static uint64_t recomp_load64(Ctx *c, uint64_t a) { (void)c, loads++; uint64_t v; memcpy(&v, at(a, 8), 8); return v; }

View File

@@ -28,6 +28,9 @@ static std::string mode;
static unsigned loads, inits, windows, threads, offscreen, signals, sleeps, flushes, waited, prepares;
static std::vector<std::string> logs;
void hos_discord_start() {} // Inert optional IPC startup; the fixture exercises display startup only.
// (host/hos_crash_dialog.c, host/hos_crash_record.c: the game itself, never a crash window's helper; no record here)
int hos_crash_helper_main(int, char**) { return -1; }
void hos_crash_clean_end() {}
static void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
@@ -101,6 +104,7 @@ static void WaitForSingleObject(HANDLE h, unsigned timeout) {
++waited;
}
static void load_hookshot_env() {}
#include "prepare_args.h" // ((Triforce, 11-24) main takes a supervised preparation's arguments for no image: host/prepare_args.h
#include "display_startup_actual.inc"

View File

@@ -141,7 +141,15 @@ static void write(Recording& r,size_t bytes,unsigned seed) {
int main(int argc,char**argv) {
require(argc==3,"fixture arguments");std::string mode=argv[1];coherent=std::string(argv[2])=="coherent";
dev.props.limits.minUniformBufferOffsetAlignment=256;dev.props.limits.minStorageBufferOffsetAlignment=64;
// (first-stream-failure: the slot's first stream cannot be made, as when host-visible memory runs out at a recording's start)
fail_buffer=mode=="first-stream-failure";
Recording a=recording(0);draw_begin_recording(0,a.cmd,1);
fail_buffer=false;
if(mode=="first-stream-failure") {
require(res[0].streams.empty() && !res[0].stream && res[0].si==0,"the slot has no stream");
submit_recording(a);require(!flushed && a.submitted,"a recording without a stream submits with nothing to flush");
std::puts("PASS: a recording whose first stream could not be made");return 0;
}
if(mode=="empty") { submit_recording(a);require(!flushed,"empty recording must not flush old bytes");return 0; }
write(a,701,1);
if(mode=="grow" || mode=="reuse") {

View File

@@ -20,11 +20,20 @@ constexpr VkBufferUsageFlags VK_BUFFER_USAGE_STORAGE_BUFFER_BIT = 1;
constexpr VkBufferUsageFlags VK_BUFFER_USAGE_TRANSFER_DST_BIT = 2;
constexpr VkBufferUsageFlags VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT = 4;
constexpr VkBufferUsageFlags VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT = 8;
constexpr VkBufferUsageFlags VK_BUFFER_USAGE_TRANSFER_SRC_BIT = 16;
constexpr int VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO = 1;
struct VkBufferDeviceAddressInfo { int sType; VkBuffer buffer = 0; };
struct { int device = 1; } dev;
namespace Shader::Backend::SPIRV {
constexpr uint64_t MESH_FALLBACK_CAPACITY = 5, MESH_FALLBACK_HEADER_WORDS = 8, MESH_FALLBACK_RECORD_WORDS = 16;
// (mma_layout.h mesh_fallback_global_attributes: the records buffer then holds the attribute regions' pool past the records)
constexpr uint64_t MESH_FALLBACK_POOL_OFFSET = 128, MESH_FALLBACK_POOL_BYTES = 64;
constexpr uint64_t MESH_FALLBACK_RECORDS_LIMIT = 1024; // (the largest records buffer made: these all fit)
inline bool mesh_fallback_global_attributes = false;
// (mma_layout.h mesh_fallback_shared_warp: its counters past the records, or past the pool; the pool's own wait counts there too)
constexpr uint64_t WARP_COUNTER_BYTES = 16;
inline bool mesh_fallback_shared_warp = false;
inline bool MeshFallbackCounters() { return mesh_fallback_shared_warp || mesh_fallback_global_attributes; }
}
struct Program {
uint32_t fallback_vertices_per_workgroup = 3;
@@ -39,13 +48,15 @@ static Allocation poison;
static std::unordered_map<VkBuffer, VmaAllocation> live;
static unsigned create_calls, destroy_calls, address_calls;
static unsigned fail_create, zero_address;
static VkBufferUsageFlags records_usage; // (the first buffer made: the records)
static void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
static bool create_buffer(uint64_t size, VkBufferUsageFlags, bool,
static bool create_buffer(uint64_t size, VkBufferUsageFlags usage, bool,
VkBuffer& buffer, VmaAllocation& allocation, void**) {
require(size != 0, "fixture received a zero allocation size");
++create_calls;
if (create_calls == 1) records_usage = usage;
if (create_calls == fail_create) {
// An output written on failure must never be treated as a confirmed allocation.
buffer = 0xffff;
@@ -147,6 +158,24 @@ static void run(const std::string& name) {
success_reuse(false);
} else if (name == "task_success") {
success_reuse(true);
} else if (name == "pool_records") {
// (the attribute regions' pool: the records buffer reaches its end, then the counters its wait counts in; the payload as
// without it)
Shader::Backend::SPIRV::mesh_fallback_global_attributes = true;
require(fallback_buffers_of(p, out) && out && out->records_address, "initialization with the pool failed");
require(out->records_bytes == 128 + 64 + 16, "the records buffer does not hold the pool, and its counters, past the records");
require(out->payload_bytes == 44, "the pool changed the payload buffer");
require(records_usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT, "the pool's counters cannot be copied out of the records");
} else if (name == "warp_counters" || name == "warp_counters_pool") {
// (the shared warp's counters: right past the records' regular end, with the pool or without, and the buffer a copy's source)
Shader::Backend::SPIRV::mesh_fallback_shared_warp = true;
Shader::Backend::SPIRV::mesh_fallback_global_attributes = name == "warp_counters_pool";
require(fallback_buffers_of(p, out) && out && out->records_address, "initialization with the shared warp failed");
require(out->records_bytes == (name == "warp_counters_pool" ? 128 + 64 : 96) + 16,
"the records buffer has no room for the shared warp's counters");
require(!out->warp_counters_cleared, "a new records buffer's counters count as cleared");
require(records_usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT, "the counters cannot be copied out of the records");
require(out->payload_bytes == 44, "the shared warp changed the payload buffer");
} else if (name == "invalid_program") {
p.fallback_record_words = 0;
require(!fallback_buffers_of(p, out), "invalid program was accepted");

188
tests/fastfp_fma_test.c Normal file
View File

@@ -0,0 +1,188 @@
/* tests/test_fastfp_fma.py's driver: each of the fast float regions' ops alone inside the regions' MXCSR window
(a64_ff_begin / a64_ff_end) against the exact body the lifted code falls back to, value and FPSR. A run the window
sends to its exact copy (a64_ff_end returning 0) is a fallback, always sound; a kept result must be Arm's bit for bit.
Built at -march=x86-64-v3 only (without FMA3 the multiply-add is the exact helper itself).
fastfp_fma_test <op> <n> <seed> n random cases, plus the edge list, for one op:
fma a64_ff_fma32_fma32 against recomp_fpe_fma32
mul a64_ff_mul32_fma32 (FMUL: the addend is a zero of the product's sign) against recomp_fpe_fma32
div, add, sub a64_ff_div32_div32 / add32_add32 / sub32_sub32 against recomp_fpe_div32 / add32 / sub32
vmul, vadd, vsub a64_ff_vmul32 / vadd32 / vsub32 on 4 lanes, then 2, against the scalar exact body lane by lane
Exit 0: no mismatch, and both kept and fallen-back cases seen. 1: a mismatch. 3: the CPU has no FMA3/AVX2. */
#include "a64.h"
#include <stdio.h>
#include <stdlib.h>
#include <immintrin.h>
#include <cpuid.h>
#include "a64_fastfp.h"
#if RECOMP_FPX_HOST != 2 || !defined(__FMA__)
#error "build at -march=x86-64-v3 (FMA3)"
#endif
static uint64_t rs;
static uint64_t rnd(void) { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; }
static uint32_t r32(void) { return (uint32_t)(rnd() >> 16); }
static uint32_t rbelow(uint32_t n) { return (uint32_t)(((rnd() >> 32) * n) >> 32); }
static uint32_t mkf(uint32_t s, int e, uint32_t f) { return (s << 31) | ((uint32_t)e << 23) | (f & 0x7fffff); }
static float F(uint32_t x) { float f; memcpy(&f, &x, 4); return f; }
static uint32_t B(float f) { uint32_t x; memcpy(&x, &f, 4); return x; }
static uint32_t sparse(void) { /* fractions with few bits: exact products, ties, cancellations */
switch (rbelow(4)) { case 0: return 0; case 1: return (uint32_t)1 << rbelow(23); case 2: return r32() & 0x7ff000; default: return r32(); }
}
static uint32_t operand(void) {
const uint32_t s = r32() & 1;
switch (rbelow(14)) {
case 0: return s << 31; /* zero */
case 1: return mkf(s, 0, r32() | 1); /* subnormal */
case 2: return mkf(s, 1 + rbelow(3), sparse()); /* smallest normals */
case 3: return mkf(s, 254 - rbelow(3), sparse()); /* largest normals */
case 4: return mkf(s, 255, 0); /* inf */
case 5: return mkf(s, 255, (r32() | 1) & 0x7fffff); /* NaN, quiet or signalling */
case 6: return mkf(s, 255, 0x400000 | r32()); /* quiet NaN */
case 7: case 8: return mkf(s, 120 + rbelow(15), sparse()); /* near 1 */
default: return mkf(s, 1 + rbelow(254), r32()); /* any normal */
}
}
enum { FMA, MUL, DIV, ADD, SUB, VMUL, VADD, VSUB };
static int op;
/* a product (or quotient) near the bottom of the normal range (rounding to and across 2^-126), or near the overflow edge */
static void edge_pair(uint32_t *a, uint32_t *b) {
if (op == DIV && rbelow(2)) { /* a in [2^-126, 2^-124), b in [1, 4): quotients from 2^-128 up, many rounding to 2^-126 */
*a = mkf(r32() & 1, 1 + rbelow(2), rbelow(2) ? (0x7fffff - rbelow(64)) : r32());
*b = mkf(r32() & 1, 127 + rbelow(2), rbelow(2) ? rbelow(64) : r32());
return;
}
if (op == ADD || op == SUB || op == VADD || op == VSUB) { /* sums near 2^-126: near-cancellations of small normals */
*a = mkf(r32() & 1, 1 + rbelow(3), r32());
*b = (*a ^ (op == SUB || op == VSUB ? 0 : 0x80000000u)) + (uint32_t)((int)rbelow(65) - 32);
return;
}
if (rbelow(4) == 0) { /* a in [0.5, 1), b in [2^-126, 2^-124): products from 2^-127 up, many rounding to 2^-126 */
*a = mkf(r32() & 1, 126, rbelow(2) ? (0x7fffff - rbelow(64)) : r32());
*b = mkf(r32() & 1, 1 + rbelow(2), rbelow(2) ? (0x7fffff - rbelow(64)) : r32());
return;
}
const int target = rbelow(8) == 0 ? 255 - (int)rbelow(3) : (int)rbelow(60) - 30;
int ea = 1 + (int)rbelow(253), eb = target - ea + 127;
if (eb < 1 || eb > 254) { eb = 1 + (int)rbelow(254); ea = target - eb + 127; }
if (ea < 1) ea = 1;
if (ea > 254) ea = 254;
*a = mkf(r32() & 1, ea, rbelow(2) ? sparse() : r32());
*b = mkf(r32() & 1, eb, rbelow(2) ? sparse() : r32());
}
static uint32_t addend(uint32_t a, uint32_t b) {
const double p = (double)F(a) * (double)F(b);
switch (rbelow(9)) {
case 0: return operand();
case 1: return B((float)-p); /* near (often exact) cancellation */
case 2: return B((float)-p) + (uint32_t)((int)rbelow(9) - 4); /* a few ulps off */
case 3: return r32() & 0x80000000u; /* a zero */
case 4: return mkf(r32() & 1, 0, r32()); /* subnormal */
case 5: return mkf(r32() & 1, 1 + rbelow(3), r32()); /* near the smallest normal */
default: return mkf(r32() & 1, 1 + rbelow(254), r32());
}
}
static uint64_t checks, kept, fell, mismatches;
static int report_left = 20;
static const char *const NAMES[] = {"fma", "mul", "div", "add", "sub", "vmul", "vadd", "vsub"};
static uint64_t exact(Ctx *c, int o, uint32_t a, uint32_t b, uint32_t z) {
switch (o) {
case FMA: return recomp_fpe_fma32(c, a, b, z);
case MUL: case VMUL: return recomp_fpe_fma32(c, a, b, (a ^ b) & 0x80000000u); /* (FMUL as the lifter passes it) */
case DIV: return recomp_fpe_div32(c, a, b);
case ADD: case VADD: return recomp_fpe_add32(c, a, b);
default: return recomp_fpe_sub32(c, a, b);
}
}
/* one case: scalar ops on (a, b, z); vector ops on lanes (a, b), (b, a), (z, a), (a, z), 4 lanes or 2 */
static void check(uint64_t cr, uint64_t sr, uint32_t a, uint32_t b, uint32_t z, int k) {
Ctx ref, got;
uint64_t r[2] = {0, 0}, v[2] = {0, 0};
memset(&ref, 0, sizeof ref);
ref.fpcr = cr; ref.fpsr = sr;
got = ref;
const unsigned m = a64_ff_begin(&got);
if (op >= VMUL) {
const uint32_t n4[4] = {a, b, z, a}, m4[4] = {b, a, a, z};
uint64_t n[2], mm[2];
uint32_t e[4] = {0, 0, 0, 0};
memcpy(n, n4, 16); memcpy(mm, m4, 16);
if (op == VMUL) a64_ff_vmul32(&got, v, n, mm, k);
else if (op == VADD) a64_ff_vadd32(&got, v, n, mm, k);
else a64_ff_vsub32(&got, v, n, mm, k);
for (int j = 0; j < k; j++) e[j] = (uint32_t)exact(&ref, op, n4[j], m4[j], 0);
memcpy(r, e, 16);
} else {
const uint32_t zz = op == MUL ? (a ^ b) & 0x80000000u : z;
r[0] = exact(&ref, op, a, b, zz);
v[0] = op == FMA ? a64_ff_fma32_fma32(&got, a, b, zz) : op == MUL ? a64_ff_mul32_fma32(&got, a, b, zz)
: op == DIV ? a64_ff_div32_div32(&got, a, b) : op == ADD ? a64_ff_add32_add32(&got, a, b)
: a64_ff_sub32_sub32(&got, a, b);
}
const int ok = a64_ff_end(&got, m);
checks++;
if (!ok) { fell++; return; }
kept++;
if (memcmp(r, v, 16) || got.fpsr != ref.fpsr) {
mismatches++;
if (report_left-- > 0)
printf("MISMATCH %s a=%08x b=%08x z=%08x k=%d fpcr=%llx fpsr=%llx: exact %08llx %08llx/%llx fast %08llx %08llx/%llx\n",
NAMES[op], a, b, z, k, (unsigned long long)cr, (unsigned long long)sr, (unsigned long long)r[0],
(unsigned long long)r[1], (unsigned long long)ref.fpsr, (unsigned long long)v[0],
(unsigned long long)v[1], (unsigned long long)got.fpsr);
}
}
static void states(uint32_t a, uint32_t b, uint32_t z) { /* FZ off/on, the flags IXC only or all set (vector: 4 lanes, 2) */
const int vec = op >= VMUL;
for (int fz = 0; fz < 2; fz++)
for (int k = vec ? 4 : 1; k >= (vec ? 2 : 1); k -= 2) {
check(fz ? 1u << 24 : 0, 0x10, a, b, z, k);
check(fz ? 1u << 24 : 0, 0x9f, a, b, z, k);
}
}
int main(int argc, char **argv) {
unsigned eax, ebx, ecx, edx;
if (!__get_cpuid(1, &eax, &ebx, &ecx, &edx) || !(ecx >> 12 & 1) || !__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx) ||
!(ebx >> 5 & 1)) {
printf("this CPU has no FMA/AVX2 (x86-64-v3)\n");
return 3;
}
op = -1;
for (int i = 0; argc == 4 && i < 8; i++) if (!strcmp(argv[1], NAMES[i])) op = i;
if (op < 0) {
fprintf(stderr, "usage: fma|mul|div|add|sub|vmul|vadd|vsub <n> <seed>\n");
return 2;
}
/* the cases the window must send to the exact copy, and plain ones it must keep */
static const uint32_t E[][3] = {
{0x00000000u, 0x7f800000u, 0x7fc00001u}, /* 0 * inf + qNaN: Arm's default NaN and IOC */
{0x7f800000u, 0x80000000u, 0xffc00002u},
{0x3f000001u, 0x00fffffeu, 0x00000000u}, /* (1 - 2^-46) * 2^-126: rounds up to 2^-126, tiny before rounding */
{0xbf000001u, 0x00fffffeu, 0x80000000u},
{0x17800000u, 0x97800000u, 0x00800000u}, /* 2^-126 - 2^-160 */
{0x3f800000u, 0x3f800000u, 0x00000123u}, /* a subnormal addend */
{0x00000123u, 0x3f800000u, 0x3f800000u}, /* a subnormal operand */
{0x3fc00000u, 0x40000000u, 0xc0400000u}, /* 1.5 * 2 - 3: an exact cancellation (+0) */
{0x3f800001u, 0x3f800001u, 0xbf800000u}, /* inexact */
{0x7f000000u, 0x7f000000u, 0x00000000u}, /* overflow */
{0x7fc00003u, 0x3f800000u, 0x3f800000u}, /* quiet NaN operands */
{0x3f800000u, 0x7fc00004u, 0x7fc00005u},
{0x003ed3cdu, 0x7ffb5d55u, 0x00000000u}, /* a subnormal and a quiet NaN: Arm flushes it under FZ and sets IDC */
{0x00ffffffu, 0x40000001u, 0x00000000u}, /* quotients and sums at the bottom of the normal range */
{0x00800001u, 0x00000001u, 0x00000000u},
};
for (unsigned i = 0; i < sizeof E / sizeof E[0]; i++) states(E[i][0], E[i][1], E[i][2]);
rs = strtoull(argv[3], 0, 0) * 0x9E3779B97F4A7C15ULL + 1;
const uint64_t n = strtoull(argv[2], 0, 0);
for (uint64_t i = 0; i < n; i++) {
uint32_t a, b;
if (rbelow(2)) edge_pair(&a, &b); else { a = operand(); b = operand(); }
states(a, b, addend(a, b));
}
printf("%s: %llu checks, %llu kept, %llu sent to the exact copy, %llu mismatches\n", argv[1],
(unsigned long long)checks, (unsigned long long)kept, (unsigned long long)fell, (unsigned long long)mismatches);
return mismatches ? 1 : (kept && fell) ? 0 : 4;
}

478
tests/fsr4_models_test.cpp Normal file
View File

@@ -0,0 +1,478 @@
// Synthetic PE images for gpu/vk/fsr4_models.h's scanner: the four FSR 4 provider classes, their Complete Object
// Locators, vtables and static registry, laid out as AMD's 4.1.2 Vulkan DLL has them. No AMD DLL, no GPU, no game.
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include "fsr4_models.h"
using namespace mkwvk::fsr4_models;
#ifdef FSR4_MODELS_TEST
static int fail_protect = -1, protect_calls = 0;
static std::vector<void*> protected_slots;
bool fsr4_test_protect(void* slot, bool writable, uintptr_t* protection) {
if (writable) {
if (protect_calls++ == fail_protect) return false;
protected_slots.push_back(slot);
*protection = 1;
} else {
if (protected_slots.empty() || protected_slots.back() != slot || *protection != 1) std::abort();
protected_slots.pop_back();
}
return true;
}
#endif
namespace {
constexpr uint32_t kPe = 0x80;
constexpr uint32_t kOpt = kPe + 24;
constexpr uint32_t kSections = kOpt + 0xF0;
constexpr uint32_t kText = 0x1000;
constexpr uint32_t kRdata = 0x2000;
constexpr uint32_t kData = 0x3000;
constexpr uint32_t kSize = 0x4000;
constexpr uint32_t kCodeFlags = 0x60000020; // CODE | EXECUTE | READ
constexpr uint32_t kReadFlags = 0x40000040; // INITIALIZED_DATA | READ
constexpr uint32_t kWriteFlags = 0xC0000040; // INITIALIZED_DATA | READ | WRITE
struct Image {
std::vector<uint8_t> bytes = std::vector<uint8_t>(kSize);
uintptr_t base() const { return reinterpret_cast<uintptr_t>(bytes.data()); }
uint64_t va(uint32_t rva) const { return base() + rva; }
void u16(uint32_t at, uint16_t v) { std::memcpy(bytes.data() + at, &v, 2); }
void u32(uint32_t at, uint32_t v) { std::memcpy(bytes.data() + at, &v, 4); }
void u64(uint32_t at, uint64_t v) { std::memcpy(bytes.data() + at, &v, 8); }
void str(uint32_t at, const char* s) { std::memcpy(bytes.data() + at, s, std::strlen(s) + 1); }
static uint32_t align(uint32_t at, uint32_t n) { return (at + n - 1) & ~(n - 1); }
};
struct ModelInfo {
Model model;
const char* name;
const char* class_name;
};
const ModelInfo kModels[] = {
{MODEL_FP8, "FP8", ".?AVffxProvider_FSR4@@"},
{MODEL_INT8, "INT8", ".?AVffxProvider_FSR4_Int8@@"},
{MODEL_INT8_NAVI2, "INT8 Navi 2", ".?AVffxProvider_FSR4_Int8_Navi2@@"},
{MODEL_LITE, "INT8 Lite", ".?AVffxProvider_FSR4Lite_Int8@@"},
};
struct Fixture {
bool models[4] = {true, true, true, true};
bool unknown = false;
bool bad_shared = false;
bool is_supported_yes[4] = {false, false, true, false}; // (the RX 6600 case: only Navi 2 says yes)
};
void headers(Image& im) {
im.u16(0, 0x5A4D);
im.u32(0x3C, kPe);
im.u32(kPe, 0x00004550);
im.u16(kPe + 4, 0x8664); // AMD64
im.u16(kPe + 6, 3);
im.u16(kPe + 20, 0xF0); // SizeOfOptionalHeader (PE32+)
im.u16(kOpt, 0x20B);
im.u32(kOpt + 0x38, kSize);
const uint32_t sec = kSections;
im.str(sec, ".text");
im.u32(sec + 8, 0x1000);
im.u32(sec + 12, kText);
im.u32(sec + 16, 0x1000);
im.u32(sec + 36, kCodeFlags);
im.str(sec + 40, ".rdata");
im.u32(sec + 48, 0x1000);
im.u32(sec + 52, kRdata);
im.u32(sec + 56, 0x1000);
im.u32(sec + 76, kReadFlags);
im.str(sec + 80, ".data");
im.u32(sec + 88, 0x1000);
im.u32(sec + 92, kData);
im.u32(sec + 96, 0x1000);
im.u32(sec + 116, kWriteFlags);
// A ret at every address a vtable names; the scanner only checks that they are in .text.
for (uint32_t rva = kText + 0x100; rva < kText + 0x300; rva += 0x10) im.bytes[rva] = 0xC3;
}
struct Built {
Image image;
uint32_t vtable_rva[5] = {};
uint32_t instance_rva[5] = {};
int count = 0;
};
Built build(const Fixture& f) {
Built b;
Image& im = b.image;
headers(im);
// (the Windows patch test calls the providers' IsSupported: x64 code returning true/false)
for (int i = 0; i < 4; i++) {
const uint32_t at = kText + 0x200 + (uint32_t)i * 0x10;
if (f.is_supported_yes[i]) {
const uint8_t yes[] = {0xB8, 1, 0, 0, 0, 0xC3}; // mov eax, 1; ret
std::memcpy(im.bytes.data() + at, yes, sizeof yes);
} else {
const uint8_t no[] = {0x31, 0xC0, 0xC3}; // xor eax, eax; ret
std::memcpy(im.bytes.data() + at, no, sizeof no);
}
}
uint32_t td_cursor = Image::align(kData + 0x100, 8);
uint32_t col_cursor = Image::align(kRdata + 0x100, 8);
uint32_t vt_cursor = Image::align(col_cursor + 5 * 24, 8);
uint32_t obj_cursor = Image::align(td_cursor + 5 * 128, 8);
uint32_t reg_cursor = Image::align(obj_cursor + 5 * 0x20, 8);
const uint32_t shared[8] = {kText + 0x100, kText + 0x110, 0, kText + 0x130,
kText + 0x140, kText + 0x150, kText + 0x160, kText + 0x170};
for (int i = 0; i < 4; i++) {
if (!f.models[i]) continue;
const int n = b.count;
const uint32_t td_rva = td_cursor;
im.u64(td_rva, im.va(kRdata));
im.u64(td_rva + 8, 0);
im.str(td_rva + 16, kModels[i].class_name);
td_cursor = Image::align(td_rva + 16 + (uint32_t)std::strlen(kModels[i].class_name) + 1, 8);
const uint32_t col_rva = col_cursor;
im.u32(col_rva, 1);
im.u32(col_rva + 4, 0);
im.u32(col_rva + 8, 0);
im.u32(col_rva + 12, td_rva);
im.u32(col_rva + 16, 0);
im.u32(col_rva + 20, col_rva);
col_cursor += 24;
const uint32_t slot_rva = vt_cursor;
const uint32_t vtable_rva = slot_rva + 8;
im.u64(slot_rva, im.va(col_rva));
for (int e = 0; e < 8; e++) {
uint64_t addr = 0;
if (e == 2) addr = im.va(kText + 0x200 + (uint32_t)n * 0x10);
else if (e == 1 && f.bad_shared && n == 1) addr = im.va(kText + 0x120);
else addr = im.va(shared[e]);
im.u64(vtable_rva + e * 8, addr);
}
vt_cursor = vtable_rva + 8 * 8;
b.vtable_rva[n] = vtable_rva;
const uint32_t obj_rva = obj_cursor;
im.u64(obj_rva, im.va(vtable_rva));
b.instance_rva[n] = obj_rva;
obj_cursor += 0x20;
b.count++;
}
if (f.unknown) {
const int n = b.count;
const char* name = ".?AVffxProvider_FSR4_Future@@";
const uint32_t td_rva = td_cursor;
im.u64(td_rva, im.va(kRdata));
im.u64(td_rva + 8, 0);
im.str(td_rva + 16, name);
td_cursor = Image::align(td_rva + 16 + (uint32_t)std::strlen(name) + 1, 8);
const uint32_t col_rva = col_cursor;
im.u32(col_rva, 1);
im.u32(col_rva + 4, 0);
im.u32(col_rva + 8, 0);
im.u32(col_rva + 12, td_rva);
im.u32(col_rva + 16, 0);
im.u32(col_rva + 20, col_rva);
col_cursor += 24;
const uint32_t slot_rva = vt_cursor;
const uint32_t vtable_rva = slot_rva + 8;
im.u64(slot_rva, im.va(col_rva));
for (int e = 0; e < 8; e++) {
uint64_t addr = 0;
if (e == 2) addr = im.va(kText + 0x200 + (uint32_t)n * 0x10);
else addr = im.va(shared[e]);
im.u64(vtable_rva + e * 8, addr);
}
vt_cursor = vtable_rva + 8 * 8;
b.vtable_rva[n] = vtable_rva;
const uint32_t obj_rva = obj_cursor;
im.u64(obj_rva, im.va(vtable_rva));
b.instance_rva[n] = obj_rva;
obj_cursor += 0x20;
b.count++;
}
for (int i = 0; i < b.count; i++) im.u64(reg_cursor + i * 8, im.va(b.instance_rva[i]));
return b;
}
int failures = 0;
void check(bool ok, const char* what) {
if (!ok) {
std::printf("FAIL: %s\n", what);
failures++;
}
}
void test_four() {
std::printf("case: four providers\n");
const Built b = build(Fixture{});
const ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 4, "four providers found");
check(r.shape_ok, "four providers have the 4.1.2 shape");
check(r.lite_present, "Lite is present");
check(r.registry_found, "provider registry found");
if (r.providers.size() != 4) return;
for (int i = 0; i < 4; i++) {
check(r.providers[i].model == kModels[i].model, "provider order is FP8, INT8, Navi 2, Lite");
check(std::strcmp(r.providers[i].class_name, kModels[i].class_name) == 0, "provider class name");
check((uintptr_t)r.providers[i].vtable == b.image.va(b.vtable_rva[i]), "provider vtable address");
check((uintptr_t)r.providers[i].is_supported == b.image.va(kText + 0x200 + (uint32_t)i * 0x10),
"provider IsSupported address");
check(r.providers[i].instance == (void*)b.image.va(b.instance_rva[i]), "provider instance from the registry");
}
}
void test_no_lite() {
std::printf("case: no Lite\n");
Fixture f;
f.models[3] = false;
const Built b = build(f);
const ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 3, "three providers found");
check(r.shape_ok, "three providers have the 4.1.2 shape");
check(!r.lite_present, "Lite is not present");
check(r.registry_found, "three-provider registry found");
}
void test_one_provider() {
std::printf("case: one provider\n");
Fixture f;
f.models[0] = f.models[1] = f.models[2] = false; // Lite only
const Built b = build(f);
const ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 1, "one provider found");
check(!r.shape_ok, "one provider is not a patchable shape");
check(r.lite_present, "the one provider is Lite");
check(!r.registry_found, "one provider is not a registry");
}
void test_bad_shape() {
std::printf("case: shifted shared entry\n");
Fixture f;
f.bad_shared = true;
const Built b = build(f);
const ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 4, "the providers are still listed");
check(!r.shape_ok, "a shifted shared vtable entry is rejected");
}
void test_unknown() {
std::printf("case: unknown provider\n");
Fixture f;
f.unknown = true;
const Built b = build(f);
const ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 5, "the unknown provider is listed");
check(r.shape_ok, "the unknown provider shares the 4.1.2 shape");
check(r.providers.size() == 5 && r.providers[4].model == MODEL_UNKNOWN, "the unknown provider is last");
check(r.providers.size() == 5 && std::strcmp(r.providers[4].class_name, ".?AVffxProvider_FSR4_Future@@") == 0,
"the unknown class name is kept");
check(r.registry_found, "the five-provider registry is found");
}
void test_not_pe() {
std::printf("case: not a PE image\n");
uint8_t junk[64] = {};
const ScanResult r = scan_image(junk, sizeof junk);
check(r.providers.empty(), "no providers in junk");
check(r.reason && *r.reason, "the rejection says why");
}
bool yes(void*, void*) { return true; }
bool no(void*, void*) { return false; }
const char* const kSdk24 = "4a7e895af6e0b615d40a84d59eb8c2b1054ad91cdd0c739567940270d51bdab7";
void test_known_library() {
std::printf("case: the known library and SHA-256\n");
check(sha256_hex("", 0) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "SHA-256 of nothing");
check(sha256_hex("abc", 3) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "SHA-256 of abc");
const std::string two_blocks(1000, 'a'); // (crosses block boundaries and the padding's second block)
check(sha256_hex(two_blocks.data(), two_blocks.size()) == "41edece42d63e8d9bf515a9ba6932e1c20cbc9f5a5d134645adb5db1b9737ea3",
"SHA-256 of 1000 a");
check(sha256_file("no such file here").empty(), "a file that cannot be read has no SHA-256");
check(known_library(kSdk24) != nullptr, "FSR SDK 2.4's upscaler library is known");
std::string upper = kSdk24;
for (char& c : upper) c = (char)std::toupper((unsigned char)c);
check(known_library(upper.c_str()) == known_library(kSdk24), "the SHA-256 in upper case names the same library");
std::string other = kSdk24;
other[63] = other[63] == '0' ? '1' : '0';
check(!known_library(other.c_str()), "another SHA-256 names no library");
check(!known_library(nullptr) && !known_library("") && !known_library("4a7e895a"), "a short or missing SHA-256 names none");
const KnownModule none = load_known("no such folder here");
check(!none.library && !none.scan.base, "no library is loaded from a folder without the file");
}
/// The fixture's instance i, with its vtable's IsSupported a function of this program (the image's own code is not
/// executable memory here)
void set_answer(ScanResult& r, int i, bool (*answer)(void*, void*)) {
r.providers[i].vtable[2] = reinterpret_cast<void*>(answer);
r.providers[i].is_supported = answer;
}
bool ask(const Built& b, const ScanResult& r, int i) {
void* instance = (void*)b.image.va(b.instance_rva[i]);
return reinterpret_cast<bool (*)(void*, void*)>(r.providers[i].vtable[2])(instance, nullptr);
}
void test_patch() {
std::printf("case: the hook, only for a known library\n");
check(scan_loaded_modules().empty(), "live discovery stays disabled");
const Built b = build(Fixture{});
ScanResult r = scan_image(b.image.bytes.data(), b.image.bytes.size());
check(r.providers.size() == 4 && r.shape_ok && r.lite_present, "patch fixture scans");
for (int i = 0; i < 4; i++) set_answer(r, i, i == 2 ? yes : no); // (the RX 6600 case: only Navi 2 says yes)
const KnownLibrary* known = known_library(kSdk24);
const KnownLibrary made_up{kSdk24, "a copy of the table's row"};
check(!install(b.image.base(), r, nullptr), "the shared shape alone is not a known library");
check(!install(b.image.base(), r, &made_up), "a library the caller made up is not a known one");
check(!install(0, r, known), "no module, no hook");
ScanResult bad = r;
bad.shape_ok = false;
check(!install(b.image.base(), bad, known), "a shape that is not understood is not hooked");
ScanResult moved = r;
moved.providers[1].is_supported = yes; // (its slot holds `no`: the vtable changed under the scan)
check(!install(b.image.base(), moved, known), "a slot that no longer holds what the scan read is not hooked");
check(!hook_installed() && !has_model(MODEL_LITE), "every refusal leaves Lite unavailable");
for (int i = 0; i < 4; i++)
check(r.providers[i].vtable[2] == reinterpret_cast<void*>(i == 2 ? yes : no), "every refusal leaves every slot unchanged");
#ifdef FSR4_MODELS_TEST
for (int failure = 0; failure < 4; failure++) {
fail_protect = failure;
protect_calls = 0;
check(!install(b.image.base(), r, known), "a protection failure refuses the whole install");
check(protected_slots.empty(), "all acquired protections restored in reverse order");
check(!hook_installed() && !has_model(MODEL_LITE), "no model exposed after a protection failure");
for (int i = 0; i < 4; i++)
check(r.providers[i].vtable[2] == reinterpret_cast<void*>(i == 2 ? yes : no), "protection failure leaves every slot unchanged");
}
fail_protect = -1;
protect_calls = 0;
#endif
check(install(b.image.base(), r, known), "the known library's providers are hooked");
check(hook_installed() && has_model(MODEL_LITE) && has_model(MODEL_FP8), "the hooked models are known");
for (int i = 0; i < 4; i++) {
check(r.providers[i].vtable[2] != reinterpret_cast<void*>(i == 2 ? yes : no), "IsSupported is the delegating answer");
for (int e = 0; e < 8; e++)
if (e != 2)
check((uintptr_t)r.providers[i].vtable[e] != (uintptr_t)r.providers[i].vtable[2], "only entry 2 is written");
}
check(!install(b.image.base(), r, known), "a second install is refused");
set_model(SELECT_AUTO);
check(!ask(b, r, 0) && !ask(b, r, 1) && ask(b, r, 2) && !ask(b, r, 3), "Auto: each provider's own answer");
check(native_model() == MODEL_INT8_NAVI2, "the first yes of an Auto walk is AMD's pick");
set_model(SELECT_LITE);
check(!ask(b, r, 0) && !ask(b, r, 1) && !ask(b, r, 2) && ask(b, r, 3), "Lite: yes for the Lite provider alone");
release();
check(!ask(b, r, 0) && !ask(b, r, 1) && ask(b, r, 2) && !ask(b, r, 3), "after release: AMD's own answers with Lite selected");
check(!hook_installed() && !has_model(MODEL_LITE), "after release no model counts as hooked");
check(!known_module_is_loaders(KnownModule{}), "a module that was never loaded is not the loader's");
set_model(SELECT_AUTO);
}
void test_selection() {
std::printf("case: selection and env\n");
set_model(SELECT_LITE);
check(selected_model() == SELECT_LITE, "set_model/selected_model Lite");
set_model(SELECT_AUTO);
check(selected_model() == SELECT_AUTO, "set_model/selected_model Auto");
record_native_model(MODEL_LITE);
check(native_model() == MODEL_INT8_NAVI2, "the first native model is kept (the hook's Auto walk recorded Navi 2)");
check(parse_model_env(nullptr) == -1, "unset env");
check(parse_model_env("") == -1, "empty env");
check(parse_model_env("auto") == SELECT_AUTO, "auto");
check(parse_model_env("lite") == SELECT_LITE, "lite");
check(parse_model_env("0") == SELECT_AUTO, "0");
check(parse_model_env("1") == SELECT_LITE, "1");
check(parse_model_env("LITE") == -1, "invalid env");
}
void test_native_model() {
std::printf("case: native model\n");
ScanResult r;
Provider p;
p.model = MODEL_FP8;
p.is_supported = no;
p.instance = (void*)1;
r.providers.push_back(p);
p.model = MODEL_INT8;
p.is_supported = yes;
p.instance = (void*)1;
r.providers.push_back(p);
p.model = MODEL_INT8_NAVI2;
p.is_supported = no;
p.instance = (void*)1;
r.providers.push_back(p);
bool supported[MODEL_COUNT] = {};
check(native_model(r, nullptr, supported) == MODEL_UNKNOWN, "unverified instances are not called");
check(!supported[MODEL_INT8] && !supported[MODEL_FP8] && !supported[MODEL_INT8_NAVI2], "no private answers are inferred");
p.model = MODEL_LITE;
p.is_supported = yes;
p.instance = nullptr;
r.providers.push_back(p);
check(native_model(r, nullptr) == MODEL_UNKNOWN, "unverified providers are not asked");
}
void test_failed_create() {
void* handle = nullptr;
int creates = 0, destroys = 0;
const auto create = [&](void** out) {
*out = (void*)1;
return creates++ == 0 ? 1 : 0;
};
const auto destroy = [&](void** out) { destroys++; *out = nullptr; };
check(create_attempt(handle, 0, create, destroy) == 1 && !handle && destroys == 1,
"failed creation destroys its returned handle");
check(create_attempt(handle, 0, create, destroy) == 0 && handle && destroys == 1,
"retry retains the successful handle");
destroy(&handle);
}
} // namespace
int main() {
test_four();
test_no_lite();
test_one_provider();
test_bad_shape();
test_unknown();
test_not_pe();
test_known_library();
test_patch();
test_selection();
test_native_model();
test_failed_create();
check(std::strcmp(model_name(MODEL_LITE), "INT8 Lite") == 0, "model_name(Lite)");
check(std::strcmp(model_class_name(MODEL_FP8), ".?AVffxProvider_FSR4@@") == 0, "model_class_name(FP8)");
std::printf("fsr4_models_test: %d failure(s)\n", failures);
return failures ? 1 : 0;
}

View File

@@ -0,0 +1,19 @@
// AMD FSR 4's network layers in miniature, for tests/test_fsr4_tune.py: constant weight tables read at loop-dependent
// places (one copied in once, one copied in at every iteration as FSR 4's own layers do), a writable and a read-only
// byte-address buffer, counted loops three deep, each with its counter alone (the sum kept in memory, as FSR 4's layers
// keep theirs in arrays). Built in this folder with:
// dxc -spirv -T cs_6_0 -E fsr4_model_test_pass7 -fspv-target-env=vulkan1.3 -Fo layer.spv layer.hlsl
RWByteAddressBuffer ScratchBuffer : register(u0);
ByteAddressBuffer InitializerBuffer : register(t1);
static const uint W[8] = { 0x0A0B0C0Du, 3u, 0xFFFFFFF0u, 77u, 5u, 0x12345678u, 9u, 1u };
[numthreads(64, 1, 1)]
void fsr4_model_test_pass7(uint3 id : SV_DispatchThreadID) {
const uint o = id.x * 4;
[unroll] for (uint i = 0; i < 4; i++)
[unroll] for (uint j = 0; j < 2; j++)
for (uint k = 0; k < 3; k++) {
const uint V[4] = { 11u, 22u, 33u, 44u };
ScratchBuffer.Store(o, ScratchBuffer.Load(o) + W[i * 2 + j] * ScratchBuffer.Load((id.x + k + 64) * 4) +
InitializerBuffer.Load(k * 4) + V[(k + i) & 3]);
}
}

BIN
tests/fsr4_tune/layer.spv Normal file

Binary file not shown.

View File

@@ -0,0 +1,11 @@
// A table the shader writes into itself (tests/test_fsr4_tune.py): it must stay where it is. Built in this folder with:
// dxc -spirv -T cs_6_0 -E fsr4_model_test_pass3 -fspv-target-env=vulkan1.3 -Fo written.spv written.hlsl
RWByteAddressBuffer ScratchBuffer : register(u0);
[numthreads(64, 1, 1)]
void fsr4_model_test_pass3(uint3 id : SV_DispatchThreadID) {
uint t[4] = { 1u, 2u, 3u, 4u };
t[ScratchBuffer.Load(0) & 3] = ScratchBuffer.Load(4);
uint acc = 0;
for (uint i = 0; i < 4; i++) acc += t[(i + id.x) & 3];
ScratchBuffer.Store(id.x * 4, acc);
}

BIN
tests/fsr4_tune/written.spv Normal file

Binary file not shown.

View File

@@ -12,6 +12,7 @@
#include <spirv/unified1/spirv.hpp>
#include "shader_recompiler/backend/spirv/emit_spirv.h"
#include "shader_recompiler/backend/spirv/mma_layout.h"
#include "shader_recompiler/exception.h"
#include "shader_recompiler/environment.h"
#include "shader_recompiler/frontend/ir/ir_emitter.h"
@@ -800,6 +801,123 @@ static void check_vertex_load_controls(bool inline_128, const char* name) {
std::printf("PASS: %s\n", name);
}
// (mma_layout.h global_table_loop, RX_VK_GM_LOOP=1) a global load whose only storage buffer is a table of 16 entries, searched in
// the loop: CI validates the module, the return inside the loop's body with it
static void check_table_loop() {
ObjectPool<IR::Inst> inst_pool;
IR::Block block{inst_pool};
IR::Program program;
program.stage = Stage::Compute;
program.workgroup_size = {1, 1, 1};
program.blocks.push_back(&block);
program.post_order_blocks.push_back(&block);
IR::AbstractSyntaxNode node{};
node.type = IR::AbstractSyntaxNode::Type::Block;
node.data.block = &block;
program.syntax_list.push_back(node);
program.syntax_list.push_back({.type = IR::AbstractSyntaxNode::Type::Return});
IR::IREmitter ir{block};
(void)ir.LoadGlobal32(ir.Imm64(u64{0x0000000100001000}));
ir.Epilogue();
TestEnvironment env;
Optimization::CollectShaderInfoPass(env, program);
program.info.constant_buffer_descriptors.push_back({0, 1});
program.info.storage_buffers_descriptors.push_back({0, 0x40, 16, false});
program.info.used_constant_buffer_types |= IR::Type::U32 | IR::Type::U32x2;
Profile profile{};
profile.supported_spirv = 0x00010600;
profile.support_int64 = true;
profile.support_descriptor_aliasing = true;
profile.min_ssbo_alignment = 16;
Shader::Backend::SPIRV::global_table_loop = true;
const auto module = inspect(save_module("ssbo-table-loop", EmitSPIRV(profile, program)));
Shader::Backend::SPIRV::global_table_loop = false;
bool loop = false;
for (const auto& inst : module.instructions)
if (inst.op == spv::Op::OpLoopMerge && inst.words[2] == spv::LoopControlDontUnrollMask) loop = true;
if (!loop) fail("the storage buffer table was not searched in a DontUnroll loop");
std::printf("PASS: storage buffer table searched in a loop\n");
}
// (mma_layout.h graphics_table_loads, RX_VK_GP_TABLE) a stage's global loads through the guest page table: 0 searches the bound
// storage buffer, 1 reads the table alone (no search left in the load helpers), 2 keeps the search and records a load the two read
// otherwise in the miss buffer (c0+0xff0). In every stage that takes it, each OpSelectionMerge right before its branch: the check's
// condition once came between them and RADV crashed compiling those modules. Native task and mesh stages too, whose load helpers
// are inlined at every load: there the table's address comes in the push block, the member at GUEST_PAGES_PUSH_OFFSET. CI
// validates every module written
static void check_table_loads(Stage stage, int mode, const char* name) {
ObjectPool<IR::Inst> inst_pool;
IR::Block block{inst_pool};
IR::Program program;
program.stage = stage;
program.workgroup_size = {1, 1, 1};
program.output_vertices = stage == Stage::Mesh ? 1 : 0;
program.mesh.max_vertices = stage == Stage::Mesh ? 1 : 0;
program.mesh.max_primitives = stage == Stage::Mesh ? 1 : 0;
program.mesh.payload_words = stage == Stage::Mesh || stage == Stage::Task ? 1 : 0;
program.blocks.push_back(&block);
program.post_order_blocks.push_back(&block);
IR::AbstractSyntaxNode node{};
node.type = IR::AbstractSyntaxNode::Type::Block;
node.data.block = &block;
program.syntax_list.push_back(node);
program.syntax_list.push_back({.type = IR::AbstractSyntaxNode::Type::Return});
IR::IREmitter ir{block};
(void)ir.LoadGlobal32(ir.Imm64(u64{0x0000001000001000}));
(void)ir.LoadGlobal128(ir.Imm64(u64{0x0000001000001010}));
ir.Epilogue();
TestEnvironment env{stage};
Optimization::CollectShaderInfoPass(env, program);
program.info.constant_buffer_descriptors.push_back({0, 1});
program.info.storage_buffers_descriptors.push_back({0, 0x40, 1, false});
if (mode == 2) program.info.storage_buffers_descriptors.push_back({0, 0xff0, 1, true}); // (translate_program.cpp's)
program.info.used_constant_buffer_types |= IR::Type::U32 | IR::Type::U32x2;
Profile profile{};
profile.supported_spirv = 0x00010600;
profile.support_int64 = true;
profile.unified_descriptor_binding = true;
profile.support_descriptor_aliasing = true;
profile.min_ssbo_alignment = 16;
RuntimeInfo runtime_info{};
Backend::Bindings bindings{};
Shader::Backend::SPIRV::graphics_table_loads = mode;
const auto module = inspect(save_module(name, EmitSPIRV(profile, runtime_info, program, bindings)));
Shader::Backend::SPIRV::graphics_table_loads = 0;
// (the load helpers: the functions the entry point calls, by what each holds)
std::map<u32, std::pair<bool, bool>> holds; // (function: a buffer search (OpArrayLength), a table read (OpConvertUToPtr))
std::vector<u32> called;
bool record = false;
bool pages_member = false; // (a push block member at GUEST_PAGES_PUSH_OFFSET: the table's address)
u32 current = 0;
for (size_t i = 0; i < module.instructions.size(); i++) {
const auto& inst = module.instructions[i];
if (inst.op == spv::Op::OpMemberDecorate && inst.words.size() >= 4 && inst.words[2] == spv::DecorationOffset &&
inst.words[3] == Shader::Backend::SPIRV::GUEST_PAGES_PUSH_OFFSET)
pages_member = true;
if (inst.op == spv::Op::OpFunction) current = inst.words[1];
if (inst.op == spv::Op::OpFunctionEnd) current = 0;
if (inst.op == spv::Op::OpArrayLength && current) holds[current].first = true;
if (inst.op == spv::Op::OpConvertUToPtr && current) holds[current].second = true;
if (inst.op == spv::Op::OpAtomicIAdd && current) record = true;
if (inst.op == spv::Op::OpFunctionCall) called.push_back(inst.words[2]);
if (inst.op == spv::Op::OpSelectionMerge &&
(i + 1 >= module.instructions.size() || (module.instructions[i + 1].op != spv::Op::OpBranchConditional &&
module.instructions[i + 1].op != spv::Op::OpSwitch)))
fail("an OpSelectionMerge is not right before its branch");
}
if (called.size() != 2) fail("the two global loads are not two helper calls");
for (const u32 f : called) {
const auto [search, table] = holds[f];
if (mode == 1 && (search || !table)) fail("RX_VK_GP_TABLE=1: a load helper still searches, or does not read the table");
if (mode != 1 && !search) fail("a load helper no longer searches the bound storage buffer");
if (mode == 2 && !table) fail("RX_VK_GP_TABLE=2: a load helper does not read the table to compare");
}
if (mode == 2 && !record) fail("RX_VK_GP_TABLE=2: no load that differs is recorded");
if (mode != 0 && !pages_member) fail("the push block has no member for the page table's address");
std::printf("PASS: %s\n", name);
}
int main(int argc, char** argv) {
if (argc == 3 && std::string(argv[1]) == "--cas-loops") {
output_dir = argv[2];
@@ -841,4 +959,10 @@ int main(int argc, char** argv) {
check_unsupported_profile();
check_vertex_load_controls(false, "vertex-global-load-default");
check_vertex_load_controls(true, "vertex-global-load-inline128");
check_table_loop();
for (const auto& [stage, label] : {std::pair{Stage::VertexB, "vertex"}, std::pair{Stage::Fragment, "fragment"},
std::pair{Stage::Compute, "compute"}, std::pair{Stage::Task, "task"},
std::pair{Stage::Mesh, "mesh"}})
for (int mode = 0; mode <= 2; mode++)
check_table_loads(stage, mode, (std::string("table-loads-") + label + "-" + std::to_string(mode)).c_str());
}

58
tests/hold_gpu_test.cpp Normal file
View File

@@ -0,0 +1,58 @@
// (tests/test_hold_gpu.py) gpu/vk/hold_gpu.h: what the order's watch thread does with queues stopped past hold_ms
#include "../gpu/vk/hold_gpu.h"
#include <cstdio>
using mkwvk::hold_gpu::Choice;
using mkwvk::hold_gpu::choose;
// (hold_ms 50, the bound 1000: the renderer's defaults)
constexpr double kHold = 50, kMost = 1000;
// not past hold_ms yet: nothing, whoever waits and whatever the switch
static_assert(choose(true, false, 10, 10, kHold, kMost) == Choice::Wait);
static_assert(choose(true, true, 50, 50, kHold, kMost) == Choice::Wait);
static_assert(choose(false, true, 49, 49, kHold, kMost) == Choice::Wait);
// past it with nobody waiting for the GPU: made to go, as before
static_assert(choose(true, false, 51, 51, kHold, kMost) == Choice::Force);
// a thread of the game's waits for the GPU: held on, however long since the queues stopped, up to the bound
static_assert(choose(true, true, 51, 0, kHold, kMost) == Choice::Hold);
static_assert(choose(true, true, 120, 0, kHold, kMost) == Choice::Hold);
static_assert(choose(true, true, 999, 0, kHold, kMost) == Choice::Hold);
// its wait over: hold_ms more for the signal it makes after it, then made to go
static_assert(choose(true, false, 120, 1, kHold, kMost) == Choice::Hold);
static_assert(choose(true, false, 160, 50, kHold, kMost) == Choice::Hold);
static_assert(choose(true, false, 161, 51, kHold, kMost) == Choice::Force);
// the bound: a wait that does not end cannot hold them for good
static_assert(choose(true, true, 1000, 0, kHold, kMost) == Choice::Force);
static_assert(choose(true, false, 1500, 10, kHold, kMost) == Choice::Force);
// the switch off: made to go at hold_ms whoever waits, as before
static_assert(choose(false, true, 51, 0, kHold, kMost) == Choice::Force);
static_assert(choose(false, false, 120, 1, kHold, kMost) == Choice::Force);
// a bound set at hold_ms itself (RX_VK_HOLD_GPU_MS at its least): never held
static_assert(choose(true, true, 51, 0, kHold, kHold) == Choice::Force);
int main() {
// (a stall as it was measured: the queues stop at 0, the game waits for the GPU from 0 to 100 ms, signals 2 ms later;
// the watch looks every millisecond. They must be held throughout, and never made to go)
int forced = 0, held = 0;
for (int t = 0; t <= 102; t++) {
const bool gpu_wait = t <= 100;
const double since = gpu_wait ? 0 : t - 100;
const Choice c = choose(true, gpu_wait, t, since, kHold, kMost);
forced += c == Choice::Force, held += c == Choice::Hold;
}
if (forced != 0 || held != 52) {
std::fprintf(stderr, "FAIL: a 100 ms GPU wait: %d looks held, %d made to go (52 and 0 wanted)\n", held, forced);
return 1;
}
// (the same with the rule off: made to go from the 51st millisecond on)
forced = 0;
for (int t = 0; t <= 102; t++) forced += choose(false, t <= 100, t, t <= 100 ? 0 : t - 100, kHold, kMost) == Choice::Force;
if (forced != 52) {
std::fprintf(stderr, "FAIL: the rule off: %d looks made to go (52 wanted)\n", forced);
return 1;
}
std::puts("PASS: stopped queues are held on while a thread of the game's waits for the GPU, hold_ms after it, and to the bound");
return 0;
}

233
tests/image_arrays_ir.cpp Normal file
View File

@@ -0,0 +1,233 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Descriptor arrays of image buffers, storage images and texture buffers through the real texture pass and SPIR-V back end:
// synthetic compute programs, no game or GPU (nx2/test_image_arrays.py builds, runs and validates them).
//
// A handle read from a constant buffer at a dynamic offset (base + element * 8) is a descriptor array: the texture pass
// sizes it by the words left after the base (DynamicDescriptorCount) and indexes it with the element. The bases here
// leave room for 2 or 3 descriptors. The same programs with the handle at a constant offset are single descriptors.
// Image buffers and storage images are read and written, or added to atomically; texture buffers and textures fetched.
//
// image_arrays_ir <output folder>
// writes <case>.spv for each case and prints one line a case:
// <case> <words> texbuf:<counts> imgbuf:<counts> tex:<counts> img:<counts> (Shader::Info's descriptors, in order)
// <case> refused: <what the translation threw>
#include <array>
#include <cstdio>
#include <exception>
#include <filesystem>
#include <fstream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "shader_recompiler/backend/spirv/emit_spirv.h"
#include "shader_recompiler/backend/spirv/mma_layout.h"
#include "shader_recompiler/environment.h"
#include "shader_recompiler/frontend/ir/ir_emitter.h"
#include "shader_recompiler/host_translate_info.h"
#include "shader_recompiler/ir_opt/passes.h"
#include "shader_recompiler/object_pool.h"
using namespace Shader;
struct TestEnvironment final : Environment {
TestEnvironment() { stage = Stage::Compute; }
u64 ReadInstruction(u32) override { return 0; }
u32 ReadCbufValue(u32, u32) override { return 1; }
TextureType ReadTextureType(u32) override { return TextureType::Color2D; }
TexturePixelFormat ReadTexturePixelFormat(u32) override { return {}; }
bool IsTexturePixelFormatInteger(u32) override { return false; }
u32 ReadViewportTransformState() override { return 1; }
u32 TextureBoundBuffer() const override { return 0; }
u32 LocalMemorySize() const override { return 0; }
u32 SharedMemorySize() const override { return 0; }
std::array<u32, 3> WorkgroupSize() const override { return {64, 1, 1}; }
bool HasHLEMacroState() const override { return false; }
std::optional<ReplaceConstant> GetReplaceConstBuffer(u32, u32) override { return std::nullopt; }
void Dump(u64, u64) override {}
};
enum class Kind { TextureBuffer, ImageBuffer, Texture, Image, ImageBufferAtomic, ImageAtomic };
struct Array {
Kind kind;
u32 count; // (1: a handle at a constant offset, a single descriptor)
};
struct Case {
std::string name;
std::vector<Array> arrays;
bool nonuniform; // (the device indexes every kind of descriptor array nonuniformly: NonUniform decorations)
bool fetch_bounds; // (Shader::Backend::SPIRV::fetch_bounds and fetch_bounds_buffers: texel fetches bounded by the size)
};
// The texture pass's limit with no device limits (HostTranslateInfo::DEFAULT_DESCRIPTOR_LIMIT) reads 16 bytes a
// descriptor: a base 8 * count bytes before that end leaves room for count descriptors of 8 bytes
constexpr u32 kCbufEnd = 16 * HostTranslateInfo::DEFAULT_DESCRIPTOR_LIMIT;
IR::U32 Handle(IR::IREmitter& ir, u32 cbuf, u32 count, const IR::U32& element) {
if (count == 1) {
return ir.GetCbuf(ir.Imm32(cbuf), ir.Imm32(0x40));
}
const IR::U32 offset{ir.IAdd(ir.Imm32(kCbufEnd - 8 * count), IR::U32{ir.ShiftLeftLogical(element, ir.Imm32(3))})};
return ir.GetCbuf(ir.Imm32(cbuf), offset);
}
IR::Value AsU32x4(IR::IREmitter& ir, const IR::Value& color) {
std::array<IR::U32, 4> parts;
for (size_t i = 0; i < parts.size(); ++i) {
parts[i] = ir.BitCast<IR::U32, IR::F32>(IR::F32{ir.CompositeExtract(color, i)});
}
return ir.CompositeConstruct(parts[0], parts[1], parts[2], parts[3]);
}
std::vector<u32> Emit(const Case& c, Info& info_out) {
ObjectPool<IR::Inst> inst_pool;
IR::Block block{inst_pool};
IR::Program program;
program.stage = Stage::Compute;
program.workgroup_size = {64, 1, 1};
program.blocks.push_back(&block);
program.post_order_blocks.push_back(&block);
IR::AbstractSyntaxNode node{};
node.type = IR::AbstractSyntaxNode::Type::Block;
node.data.block = &block;
program.syntax_list.push_back(node);
IR::AbstractSyntaxNode ret{};
ret.type = IR::AbstractSyntaxNode::Type::Return;
program.syntax_list.push_back(ret);
IR::IREmitter ir{block};
const IR::U32 lane{ir.LocalInvocationIdX()}; // (each invocation its own element: nonuniform)
const IR::U32 next{ir.IAdd(lane, ir.Imm32(1))};
IR::TextureInstInfo out{}; // (where sampled reads are stored: a single image buffer bound at c0[0x100])
out.type.Assign(TextureType::Buffer);
out.image_format.Assign(ImageFormat::R32_UINT);
u32 cbuf{2};
for (const Array& array : c.arrays) {
const IR::U32 handle{Handle(ir, cbuf++, array.count, lane)};
IR::TextureInstInfo info{};
info.image_format.Assign(ImageFormat::R32_UINT);
switch (array.kind) {
case Kind::ImageBuffer: {
info.type.Assign(TextureType::Buffer);
const IR::Value texel{ir.ImageRead(handle, lane, info)};
ir.ImageWrite(handle, next, texel, info);
break;
}
case Kind::Image: {
info.type.Assign(TextureType::Color2D);
const IR::Value texel{ir.ImageRead(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), info)};
ir.ImageWrite(handle, ir.CompositeConstruct(next, ir.Imm32(1)), texel, info);
break;
}
case Kind::TextureBuffer: {
info.type.Assign(TextureType::Buffer);
const IR::Value texel{ir.ImageFetch(handle, lane, {}, {}, {}, info)};
ir.ImageWrite(ir.Imm32(0x100), lane, AsU32x4(ir, texel), out);
break;
}
case Kind::Texture: {
info.type.Assign(TextureType::Color2D);
const IR::Value texel{
ir.ImageFetch(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), {}, ir.Imm32(0), {}, info)};
ir.ImageWrite(ir.Imm32(0x100), next, AsU32x4(ir, texel), out);
break;
}
case Kind::ImageBufferAtomic: {
info.type.Assign(TextureType::Buffer);
const IR::U32 old{ir.ImageAtomicIAdd(handle, lane, ir.Imm32(1), info)};
ir.ImageWrite(ir.Imm32(0x100), lane, ir.CompositeConstruct(old, old, old, old), out);
break;
}
case Kind::ImageAtomic: {
info.type.Assign(TextureType::Color2D);
const IR::U32 old{ir.ImageAtomicIAdd(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), ir.Imm32(1), info)};
ir.ImageWrite(ir.Imm32(0x100), lane, ir.CompositeConstruct(old, old, old, old), out);
break;
}
}
}
ir.Epilogue();
TestEnvironment env;
HostTranslateInfo host_info{};
host_info.support_snorm_render_buffer = true;
host_info.ApplyDescriptorLimitPolicy(); // (as TranslateProgram: no device limits, the defaults)
Optimization::TexturePass(env, program, host_info);
Optimization::DeadCodeEliminationPass(program);
Optimization::CollectShaderInfoPass(env, program);
info_out = program.info;
Profile profile{};
profile.supported_spirv = 0x00010600;
profile.support_int64 = true;
profile.support_sampled_image_array_nonuniform_indexing = c.nonuniform;
profile.support_storage_image_array_nonuniform_indexing = c.nonuniform;
profile.support_uniform_texel_buffer_array_nonuniform_indexing = c.nonuniform;
profile.support_storage_texel_buffer_array_nonuniform_indexing = c.nonuniform;
Backend::SPIRV::fetch_bounds = c.fetch_bounds;
Backend::SPIRV::fetch_bounds_buffers = c.fetch_bounds;
return Backend::SPIRV::EmitSPIRV(profile, program);
}
template <typename Descriptors>
std::string Counts(const Descriptors& descriptors) {
std::string text;
for (const auto& desc : descriptors) {
text += (text.empty() ? "" : ",") + std::to_string(desc.count);
}
return text;
}
int main(int argc, char** argv) {
if (argc != 2) {
std::fprintf(stderr, "usage: image_arrays_ir <output folder>\n");
return 2;
}
const std::filesystem::path folder{argv[1]};
std::filesystem::create_directories(folder);
const std::array<std::pair<const char*, std::vector<Array>>, 12> programs{{
{"imgbuf-1", {{Kind::ImageBuffer, 1}}},
{"img-1", {{Kind::Image, 1}}},
{"texbuf-1", {{Kind::TextureBuffer, 1}}},
{"imgbuf-atomic-1", {{Kind::ImageBufferAtomic, 1}}},
{"img-atomic-1", {{Kind::ImageAtomic, 1}}},
{"mixed-1", {{Kind::TextureBuffer, 1}, {Kind::ImageBuffer, 1}, {Kind::Texture, 1}, {Kind::Image, 1}}},
{"imgbuf-2", {{Kind::ImageBuffer, 2}}},
{"img-3", {{Kind::Image, 3}}},
{"texbuf-2", {{Kind::TextureBuffer, 2}}},
{"imgbuf-atomic-2", {{Kind::ImageBufferAtomic, 2}}},
{"img-atomic-3", {{Kind::ImageAtomic, 3}}},
{"mixed", {{Kind::TextureBuffer, 2}, {Kind::ImageBuffer, 2}, {Kind::Texture, 2}, {Kind::Image, 3}}},
}};
std::vector<Case> cases;
for (const auto& [name, arrays] : programs) {
cases.push_back({name, arrays, false, false});
cases.push_back({std::string{name} + "-nonuniform", arrays, true, false});
if (std::string_view{name}.starts_with("texbuf") || std::string_view{name}.starts_with("mixed")) {
cases.push_back({std::string{name} + "-bounds", arrays, false, true});
}
}
for (const Case& c : cases) {
Info info;
std::vector<u32> words;
try {
words = Emit(c, info);
} catch (const std::exception& e) {
std::printf("%s refused: %s\n", c.name.c_str(), e.what());
continue;
}
std::ofstream file(folder / (c.name + ".spv"), std::ios::binary);
file.write(reinterpret_cast<const char*>(words.data()), static_cast<std::streamsize>(words.size() * 4));
if (!file) {
std::fprintf(stderr, "%s: not written\n", c.name.c_str());
return 3;
}
std::printf("%s %zu texbuf:%s imgbuf:%s tex:%s img:%s\n", c.name.c_str(), words.size(),
Counts(info.texture_buffer_descriptors).c_str(), Counts(info.image_buffer_descriptors).c_str(),
Counts(info.texture_descriptors).c_str(), Counts(info.image_descriptors).c_str());
}
return 0;
}

View File

@@ -31,11 +31,23 @@ LONG64 InterlockedCompareExchange64(volatile LONG64 *p, LONG64 value, LONG64 exp
}
static int64_t now_ns = 10000000000LL, sampling;
static int key_bind[HOS_KEY_N][2], pad_raw_now; /* (the keys-only controls after the Switch's buttons) */
/* ((Triforce) 11-24: the ocarina's note layer's words, which host/nn_hid.c keeps beside its bindings: no note wait here
(hos_oc_wait stays 0) and no note row bound, so nothing is consumed and the game's word is the buttons' own) */
static int pad_bind[HOS_KEY_N][2]; /* (Input 1 and Input 2) */
static uint64_t pad_after_menu;
static uint64_t oc_consumed_pads __attribute__((unused)); /* (read by bound_pad_buttons, a stand-in here) */
static long oc_consumed_keys[256];
static int oc_live;
volatile uint64_t hos_oc_note_bits;
volatile int hos_oc_wait, hos_oc_last_kind;
volatile unsigned hos_oc_beat;
static unsigned char *memory;
static char last_log[256];
volatile int64_t hos_hid_last_read;
volatile int hos_nvn_sync_log_on;
static void *at(uint64_t address) { CHECK(address <= 512 - 8); return memory + address; }
/* (host/hos.h's, over this fixture's 512 bytes: NULL unless all n bytes lie in them) */
static void *hos_guest_range(uint64_t a, uint64_t n) { return a <= 512 && n <= 512 - a ? memory + a : NULL; }
#define GP(a) at(a)
#define G32(a) (*(uint32_t *)at(a))
#define G64(a) (*(uint64_t *)at(a))
@@ -48,6 +60,15 @@ static int walk_row, walk_scale, walk_held;
button held, and the game's Back tapped for it) */
static int options_open, options_front, right_held;
static char tapped[64];
/* (the "held-input" case: the keys and the pad hold only what the case holds, the Z key (ZL's here) and the pad's buttons) */
static int quiet, z_held;
/* (the "menu-side-buttons" case: whether one of the game's menus has the mouse, and Mouse 4, A's here, is held) */
static int game_menu_mouse, side_held;
/* ((Triforce) 11-24, the "deck-mouse" case: the Steam Deck's built-in controls give the input, host/pad_sdl.c's answer;
the mouse captured, its left button, Y's here, held, and its motion as the right stick) */
static int deck_builtin, mouse_captured, left_held;
static int32_t mouse_motion;
static uint64_t pad_held;
int rx_option(int id, int otherwise) {
if (id == HOS_OPT_WALK_KEY) return walk_row;
if (id == 1 && options_open) return 1;
@@ -67,25 +88,37 @@ LONG_PTR GetWindowLongPtrA(HWND window, int index) { (void)window; (void)index;
int GetClassNameA(HWND window, char *text, int size) { (void)window; return snprintf(text, (size_t)size, "fixture"); }
short GetAsyncKeyState(int key) {
key_queries++;
if (quiet) return (z_held && key == 'Z') || (side_held && key == VK_XBUTTON1) || (left_held && key == VK_LBUTTON) ? (short)-32768 : 0;
return key == 'P' || key == 'D' || (walk_held && key == VK_CAPITAL) || (right_held && key == VK_RBUTTON) ? (short)-32768 : 0;
}
int hos_sdl_pads(uint64_t *buttons, int32_t stick[4]) {
bootstrap_polls++; *buttons = 1ULL << B_Y; stick[0] = -31000; return 1;
}
int hos_sdl_pads_deck_builtin(void) { return deck_builtin; } /* (host/pad_sdl.c's: the "deck-mouse" case) */
/* (the pads' inputs still held after the Insert menu: none here, pad_raw_now staying 0, so the bindings are never asked) */
static uint64_t pad_raw_game;
static uint64_t bound_pad_buttons(uint64_t raw) { (void)raw; CHECK(!"no pad input was held after the menu"); return 0; }
void pads_read(uint64_t *buttons, int32_t stick[4]) {
/* The physical backend boundary is a spy; actual routing merges its result with the script below. */
if (quiet) { pad_merges++; *buttons |= pad_held; return; }
pad_merges++; *buttons |= 1ULL << B_B; stick[0] = -12000; stick[2] = 8000;
}
void binds_load(void) {
key_bind[B_X][0] = 'P';
key_bind[B_X][0] = 'P', key_bind[B_ZL][0] = 'Z';
key_bind[B_A][1] = VK_XBUTTON1; /* (Mouse 4 on A, for the "menu-side-buttons" case; held in no other) */
key_bind[B_Y][1] = VK_LBUTTON; /* (the mouse's left button on Y, as out of the box, for the "deck-mouse" case) */
/* (the left stick's and the camera's keys are bindings too: the defaults, WASD and the arrows) */
key_bind[HOS_KEY_MOVE_UP][0] = 'W', key_bind[HOS_KEY_MOVE_DOWN][0] = 'S', key_bind[HOS_KEY_MOVE_LEFT][0] = 'A';
key_bind[HOS_KEY_MOVE_RIGHT][0] = 'D', key_bind[HOS_KEY_CAM_UP][0] = VK_UP, key_bind[HOS_KEY_CAM_DOWN][0] = VK_DOWN;
key_bind[HOS_KEY_CAM_LEFT][0] = VK_LEFT, key_bind[HOS_KEY_CAM_RIGHT][0] = VK_RIGHT;
pad_bind[HOS_KEY_TOGGLE_HUD][0] = pad_bind[HOS_KEY_TOGGLE_HUD][1] = -1; /* ((Triforce) Toggle HUD unbound, as out of the box) */
}
/* ((Triforce) host/hos_wide_ui.c's: Toggle HUD is unbound here, so never pressed) */
void hos_gameplay_hud_toggle(void) { CHECK(!"Toggle HUD pressed with nothing bound to it"); }
/* the native mouse look (no camera found: the motion goes to mouse_stick) and the mouse's sensitivity, which
read_input calls */
int hos_mouse_native(void) { return -1; }
int hos_mouse_in_game_menu(void) { return game_menu_mouse; } /* (host/display.c's) */
void hos_mouse_native_free(int free) { (void)free; }
/* ((Triforce, 11-22) whether the right stick turns the camera, told after every read: behind another window too, where the
pads alone turned it, and the native mouse put the angles back each frame) */
@@ -93,10 +126,13 @@ static int native_held = -1;
void hos_mouse_native_stick(int held) { native_held = held; }
static void mouse_setup(void) {}
static void mouse_sens_keys(void) {}
int mouse_stick(int32_t *x, int32_t *y, int held) { (void)x; (void)y; (void)held; mouse_queries++; return 0; }
int mouse_stick(int32_t *x, int32_t *y, int held) { (void)y; (void)held; mouse_queries++; *x = mouse_motion; return mouse_captured; }
/* (the options tabs inside the game's own Options screen, which read_input looks at: never open here, so the Back it
would tap for the game is never asked for) */
int hos_binding(int set, int button, int slot) { (void)set; (void)button; (void)slot; return -1; }
void hos_prompts_live(void) {} /* ((Triforce) host/prompts.c: the button prompts follow the controls) */
volatile int hos_prompts_row = -1; /* (host/prompts.c: "!prompts" in the live input) */
void hos_bind(int set, int button, int slot, int code) { (void)set, (void)button, (void)slot, (void)code; } /* ("!bind") */
int hos_oot_options_front(void) { return options_front; }
/* (the sprint button, which takes its press out of the buttons while Link plays: off here; and the pipeline crawl's
lines of a live script, which no case writes) */
@@ -107,6 +143,12 @@ void rx_request_frame_dump(void) { commands++; }
void rx_set_screenshot_ms(int64_t ms) { (void)ms; commands++; }
void rx_request_rdoc_capture(int frames) { (void)frames; commands++; }
void rx_flash_dark_arm(void) { commands++; }
/* ((Triforce) host/input_movie.c: no recording and no playback here: every read is the player's, and each one is offered
to the recording once) */
#include "../host/input_movie.h"
static int movie_begins, movie_ends;
int hos_input_movie_begin(MoviePad *given) { (void)given; movie_begins++; return 0; }
void hos_input_movie_end(const MoviePad *p) { (void)p; movie_ends++; CHECK(movie_ends == movie_begins); }
#include "input_actual.inc"
@@ -279,6 +321,80 @@ int main(int argc, char **argv) {
free(memory);
return 0;
}
if (!strcmp(name, "menu-side-buttons")) {
/* While one of the game's menus has the mouse (the capture gone to it), a side button bound to A is still A, as
a key is: it confirmed nothing in the text box's choices. Free in play (no menu, no capture) it is no control;
one held as the menu takes the mouse counts only after it was let go. Through the real read_input */
const uint64_t a = 1ULL << B_A;
front = quiet = 1;
packet(0, 0, 0, 0);
side_held = 1; packet(0, 0, 0, 0); /* the mouse free in play: no control */
game_menu_mouse = 1; packet(0, 0, 0, 0); /* held as the menu opens: not until let go */
side_held = 0; packet(0, 0, 0, 0);
side_held = 1; packet(a, 0, 0, 0); /* pressed in the menu: A */
packet(a, 0, 0, 0);
side_held = 0; packet(0, 0, 0, 0);
game_menu_mouse = 0; side_held = 1; packet(0, 0, 0, 0); /* the menu closed, the mouse free again: no control */
side_held = 0; packet(0, 0, 0, 0);
printf("PASS: the mouse's side buttons stay their controls' while one of the game's menus has the mouse %s" "%c", name, 10);
free(memory);
return 0;
}
if (!strcmp(name, "deck-mouse")) {
/* The Steam Deck's built-in controls show the system a mouse as well as the pad (in Steam's Desktop layout R2 is
a left click, L2 a right one, and the right stick moves it), so a control bound to a mouse button fired twice,
once from the pad and once from that click. While those controls give the input the mouse's buttons are no
control's and its motion steers nothing; it is still taken in, and one of the game's menus keeps its side
buttons. Any other pad, and a PC without a Steam Deck's controls, as before. Through the real read_input */
const uint64_t a = 1ULL << B_A, y = 1ULL << B_Y;
front = quiet = mouse_captured = 1;
packet(0, 0, 0, 0);
left_held = 1; packet(y, 0, 0, 0); /* an ordinary pad: the left button is Y, as its binding says */
mouse_motion = 20000; packet(y, 0, 0, 20000); /* and the mouse's motion is the camera's */
pad_held = a; deck_builtin = 1;
int before = mouse_queries;
packet(a, 0, 0, 0); /* the Deck's own controls: the click is not Y, the motion not the camera's */
CHECK(mouse_queries > before); /* (the pointer still taken in) */
left_held = 0; packet(a, 0, 0, 0); /* let go and pressed again while they give the input: still nothing */
left_held = 1; packet(a, 0, 0, 0);
pad_held = 0; deck_builtin = 0;
packet(0, 0, 0, 20000); /* the controls go, the button held through: let go first */
left_held = 0; packet(0, 0, 0, 20000);
left_held = 1; packet(y, 0, 0, 20000);
left_held = 0; mouse_motion = 0; packet(0, 0, 0, 0);
deck_builtin = 1; mouse_captured = 0; game_menu_mouse = 1; /* one of the game's menus has the mouse: */
packet(0, 0, 0, 0);
side_held = 1; packet(a, 0, 0, 0); /* its side button is still A's there, the Deck's controls or not */
side_held = 0; packet(0, 0, 0, 0);
deck_builtin = 0; game_menu_mouse = 0;
printf("PASS: a Steam Deck's built-in controls give their actions once, not again through the mouse they also show %s" "%c", name, 10);
free(memory);
return 0;
}
if (!strcmp(name, "held-input")) {
/* The player's input hides the game menus' cursor until the mouse moves (host/display.c gm_cursor_shown), so an
input counts when it goes down, not at every read while it stays down: the ocarina's song sheet is open while ZL
is held, and a ZL held on a pad or the Z key counted at every read, so the cursor the mouse had just shown was
hidden again before the menu used it and its hover failed. Through the real read_input */
const uint64_t zl = 1ULL << B_ZL, l = 1ULL << B_L;
front = quiet = 1;
packet(0, 0, 0, 0); CHECK(player_stamps == 0);
z_held = 1; packet(zl, 0, 0, 0); CHECK(player_stamps == 1); /* a key goes down: the player's input */
for (int i = 0; i < 5; i++) packet(zl, 0, 0, 0);
CHECK(player_stamps == 1); /* held: not at every read */
z_held = 0; packet(0, 0, 0, 0); CHECK(player_stamps == 1); /* let go: not an input */
z_held = 1; packet(zl, 0, 0, 0); CHECK(player_stamps == 2); /* down again: one more */
z_held = 0; packet(0, 0, 0, 0);
pad_held = zl; packet(zl, 0, 0, 0); CHECK(player_stamps == 3); /* a pad's button the same */
for (int i = 0; i < 5; i++) packet(zl, 0, 0, 0);
CHECK(player_stamps == 3);
pad_held = zl | l; packet(zl | l, 0, 0, 0); CHECK(player_stamps == 4); /* a second one, the first held */
pad_held = l; packet(l, 0, 0, 0); CHECK(player_stamps == 4);
pad_held = 0; packet(0, 0, 0, 0); CHECK(player_stamps == 4);
printf("PASS: an input held down is the player's input when it goes down, not at every read %s\n", name);
free(memory);
return 0;
}
front = !strcmp(name, "foreground") || !strcmp(name, "exclusive-foreground");
menu_background = !strcmp(name, "pads-menu") || !strcmp(name, "pads-off");
const int exclusive = !strncmp(name, "exclusive-", 10);

View File

@@ -12,7 +12,7 @@
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
using namespace std::chrono_literals;
struct HosThread { int vc_held = 0, releases = 0, takes = 0; bool returning_caller = false; };
struct HosThread { int vc_held = 0, vc_escaped = 0, releases = 0, takes = 0; bool returning_caller = false; };
static thread_local HosThread* cur;
static thread_local bool callback_active;
static std::mutex lease_mu, renderer_mu;

View File

@@ -0,0 +1,76 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// gpu/vk/load_default.h alone (tests/test_load_default.py)
#include "../gpu/vk/load_default.h"
#include <cstdlib>
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "CHECK failed line %d: %s\n", __LINE__, #c); std::exit(1); } } while (0)
int main(int argc, char** argv) {
CHECK(argc == 2);
using load_default::choose;
// the switch always wins, whatever the GPU and the marker
for (int mesh = 0; mesh < 2; mesh++)
for (int marker = 0; marker < 2; marker++) {
CHECK(choose("create", mesh, marker).create);
CHECK(!choose("start", mesh, marker).create);
// (Triforce) without it, or with anything else, start: how the game has always loaded its programs
CHECK(!choose(nullptr, mesh, marker).create && !choose("", mesh, marker).create && !choose("1", mesh, marker).create);
CHECK(std::strstr(choose(nullptr, mesh, marker).why, "Triforce's default"));
}
// auto: create with no marker, with mesh shaders or through the compute fallback (only the reason differs)
CHECK(choose("auto", true, false).create);
CHECK(choose("auto", false, false).create && std::strstr(choose("auto", false, false).why, "compute fallback"));
CHECK(!choose("auto", true, true).create);
CHECK(!choose("auto", false, true).create);
CHECK(std::strstr(choose("auto", true, true).why, "triforce_load_start.txt"));
// without the shader preparation start loads nothing before the title: the marker is left aside there
CHECK(choose("auto", true, true, false).create && choose("auto", false, true, false).create);
CHECK(std::strstr(choose("auto", true, true, false).why, "RX_VK_PRECOMPILE=0"));
CHECK(!choose(nullptr, true, false, false).create && !choose("start", true, false, false).create);
// the safety net: only waits over kLongMs count; a healthy session's few milliseconds each never add up
using load_default::counts;
using load_default::waits_verdict;
using load_default::Waits;
CHECK(!counts(2.0) && !counts(7.0) && !counts(20.0) && counts(20.1) && counts(261));
// one bad moment (261 ms, 322 in the session) is fine; over kStrikeMs a strike, the marker only the second session running
CHECK(waits_verdict(322, false) == Waits::kFine && waits_verdict(500, false) == Waits::kFine);
CHECK(waits_verdict(500.1, false) == Waits::kStrike && waits_verdict(500.1, true) == Waits::kStart);
// the PC where loads at create do not work: 2.5-4.7 s of waits, the marker at once
CHECK(waits_verdict(2556.6, false) == Waits::kStart && waits_verdict(4733, false) == Waits::kStart);
CHECK(waits_verdict(2000, false) == Waits::kStrike && waits_verdict(2000.1, false) == Waits::kStart);
{ // the strike: written, found once by the next start and taken away
const std::string marker = std::string(argv[1]) + "/triforce_load_start.txt";
CHECK(!load_default::strike_take(marker));
CHECK(load_default::strike_write(marker, 612) && load_default::marker_there(load_default::strike_path(marker)));
CHECK(load_default::strike_take(marker) && !load_default::strike_take(marker));
}
// its second part: listed pipelines in no cache, 0 where the caches held the preparation's work, thousands where they did not
CHECK(!load_default::caches_lacked(0) && !load_default::caches_lacked(39) && !load_default::caches_lacked(500));
CHECK(load_default::caches_lacked(501) && load_default::caches_lacked(4189));
// the marker: not there, written, there; its text says how to take it away
const std::string path = std::string(argv[1]) + "/triforce_load_start.txt";
CHECK(!load_default::marker_there(path));
CHECK(load_default::marker_write(path, 884.4, 2556.6) && load_default::marker_there(path));
char text[400]{};
FILE* f = std::fopen(path.c_str(), "rb");
CHECK(f && std::fread(text, 1, sizeof text - 1, f) > 0);
std::fclose(f);
CHECK(std::strstr(text, "2557 ms") && std::strstr(text, "884 ms") && std::strstr(text, "Delete this file"));
using load_default::Marker;
CHECK(load_default::marker_kind(path) == Marker::kWaits);
CHECK(load_default::marker_write_lacked(path, 4189) && load_default::marker_there(path));
CHECK(load_default::marker_kind(path) == Marker::kLacked);
// the lacked marker is not followed on a PC of 20 GB or less (start would not fit there); the waits' one is, on any RAM
CHECK(!load_default::marker_counts(Marker::kLacked, 16384) && !load_default::marker_counts(Marker::kLacked, 20480));
CHECK(load_default::marker_counts(Marker::kLacked, 20481) && load_default::marker_counts(Marker::kLacked, 0));
CHECK(load_default::marker_counts(Marker::kWaits, 16384) && !load_default::marker_counts(Marker::kNone, 65536));
{ // (a marker written by hand: the waits')
FILE* h = std::fopen(path.c_str(), "wb");
CHECK(h && std::fputs("x\n", h) >= 0 && std::fclose(h) == 0);
CHECK(load_default::marker_kind(path) == Marker::kWaits);
}
CHECK(load_default::marker_kind(std::string(argv[1]) + "/none.txt") == Marker::kNone);
CHECK(!load_default::marker_write(std::string(argv[1]) + "/no-such-folder/x.txt", 1, 1));
CHECK(std::remove(path.c_str()) == 0 && !load_default::marker_there(path));
std::printf("load_default: ok\n");
return 0;
}

View File

@@ -770,6 +770,8 @@ static void frames_and_events(void) {
#define FRAME 240
static float master = 1.0f;
static float master_volume(void) { return master; }
static float speaker_frame[FRAME]; /* ((Triforce) the controller speaker's frame, off here: host/pad_speaker.c) */
static int speaker_on;
static void render_tail(float out[6][FRAME], int16_t *pcm, const int nch) {
#include "render_tail.inc"
}

View File

@@ -1,6 +1,7 @@
// Authored allocator/address failures only; no Vulkan device, driver or game data.
// Null mapping and zero BDA are defensive injections, not conforming-driver outcomes.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <stdexcept>
@@ -28,12 +29,12 @@ static constexpr uint32_t sentinel = 0xcccccccc;
static void require(bool condition, const char* message) {
if (!condition) throw std::runtime_error(message);
}
static uint64_t ring_bytes();
static bool create_buffer(uint64_t size, VkBufferUsageFlags usage, bool host_visible,
VkBuffer& buffer, VmaAllocation& allocation, void** mapped) {
++creates;
require(creates == 1, "initialization allocated more than once");
require(size != 0 && size % 16 == 0 && size <= 4 * 1024 * 1024,
"unexpected allocation size");
require(size == ring_bytes(), "unexpected allocation size");
require(usage == (VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) && host_visible && mapped,
"changed production allocation flags");
@@ -66,6 +67,8 @@ static uint64_t vkGetBufferDeviceAddress(int device, const VkBufferDeviceAddress
#include "mesh_args_actual.inc"
static uint64_t ring_bytes() { return static_cast<uint64_t>(kMeshArgs) * 4 * sizeof(uint32_t); }
static void initialized_ring() {
require(storage.size() == static_cast<std::size_t>(kMeshArgs) * 4 + 2,
"allocation does not hold the actual ring");
@@ -118,6 +121,28 @@ int main(int argc, char** argv) {
require(creates == 1 && destroys == 0 && addresses == 1 &&
mesh_args_words[4] == 123 && mesh_args_words[7] == 456,
"reuse recreated, destroyed or reset the ring");
} else if (mode == "take_ranges") {
// Entries handed out stay in use until kMeshArgs / 2 more have been handed out: no range may reuse one
// sooner. A big draw right before the old modulus wrapped, then a one-entry draw, overlapped.
std::vector<uint64_t> taken_at(kMeshArgs, UINT64_MAX);
uint64_t handed = 1; // (the ring's counter starts at 1)
const auto take = [&](uint32_t n) {
const uint32_t at = mesh_args_take(n);
n = std::clamp<uint32_t>(n, 1, kMeshArgs / 2);
require(at >= 1 && (uint64_t)at + n <= kMeshArgs, "range outside the ring or on entry 0");
for (uint32_t i = 0; i < n; ++i) {
const uint64_t prior = taken_at[at + i];
require(prior == UINT64_MAX || handed + n - prior > kMeshArgs / 2,
"range reuses entries still in use");
taken_at[at + i] = handed;
}
handed += n;
};
constexpr uint32_t big = 4096;
while (handed < (uint64_t)kMeshArgs - big) take(1);
take(big);
for (uint32_t k = 0; k < 64; ++k) take(1 + k % 5);
for (uint32_t k = 0; k < 3 * kMeshArgs / big; ++k) take(k % 3 ? 1 + k % 97 : big);
} else {
throw std::runtime_error("unknown fixture case");
}

72
tests/module_ids_test.cpp Normal file
View File

@@ -0,0 +1,72 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// gpu/vk/module_ids.h alone: the side file of shader module identifiers (tests/test_module_ids.py)
#include "../gpu/vk/module_ids.h"
#include <cstdlib>
#define CHECK(c) do { if (!(c)) { std::fprintf(stderr, "CHECK failed line %d: %s\n", __LINE__, #c); std::exit(1); } } while (0)
int main(int argc, char** argv) {
CHECK(argc == 2);
const std::string path = std::string(argv[1]) + "/ids.bin";
const uint8_t driver[16] = {1, 2, 3}, other[16] = {9};
uint8_t a[32], b[20];
for (int i = 0; i < 32; i++) a[i] = (uint8_t)(i + 1);
for (int i = 0; i < 20; i++) b[i] = (uint8_t)(200 - i);
module_ids::Id got;
{
module_ids::Store s;
s.open(path, 77, driver); // (no file yet)
CHECK(s.size() == 0 && !s.pending() && s.flush());
CHECK(s.add(10, 1, a, 32) && s.add(10, 2, b, 20) && s.pending());
CHECK(!s.add(10, 1, b, 20)); // (known: the first stays)
CHECK(!s.add(11, 1, a, 0) && !s.add(11, 1, a, 33)); // (not an identifier)
CHECK(s.find(10, 1, &got) && got.n == 32 && !std::memcmp(got.bytes, a, 32));
CHECK(!s.find(10, 3, &got) && s.has(10, 2) && !s.has(11, 1));
CHECK(s.flush() && !s.pending());
CHECK(s.add(12, 0, b, 20) && s.flush()); // (appended to the file it began)
}
{
module_ids::Store s;
s.open(path, 77, driver);
CHECK(s.size() == 3 && !s.pending());
CHECK(s.find(10, 2, &got) && got.n == 20 && !std::memcmp(got.bytes, b, 20));
CHECK(s.find(12, 0, &got) && got.n == 20);
}
{ // another program cache, another driver: none of it is used, and the next flush begins the file again
module_ids::Store s;
s.open(path, 78, driver);
CHECK(s.size() == 0);
s.open(path, 77, other);
CHECK(s.size() == 0);
CHECK(s.add(20, 5, a, 32) && s.flush());
module_ids::Store t;
t.open(path, 77, other);
CHECK(t.size() == 1 && t.has(20, 5));
t.open(path, 77, driver);
CHECK(t.size() == 0);
}
{ // cut short in an entry, and an entry that is none: what read before it is kept
module_ids::Store s;
s.open(path, 77, other);
CHECK(s.add(21, 1, b, 20) && s.add(22, 1, b, 20) && s.flush());
FILE* f = std::fopen(path.c_str(), "rb");
CHECK(f);
std::vector<uint8_t> all(32 + 3 * 52);
CHECK(std::fread(all.data(), 1, all.size(), f) == all.size());
std::fclose(f);
f = std::fopen(path.c_str(), "wb");
CHECK(f && std::fwrite(all.data(), 1, all.size() - 10, f) == all.size() - 10);
std::fclose(f);
module_ids::Store t;
t.open(path, 77, other);
CHECK(t.size() == 2 && t.has(20, 5) && t.has(21, 1) && !t.has(22, 1));
const uint32_t big = 99;
std::memcpy(all.data() + 32 + 52 + 16, &big, 4); // (the second entry's size)
f = std::fopen(path.c_str(), "wb");
CHECK(f && std::fwrite(all.data(), 1, all.size(), f) == all.size());
std::fclose(f);
t.open(path, 77, other);
CHECK(t.size() == 1 && t.has(20, 5));
}
std::printf("module_ids: ok\n");
return 0;
}

View File

@@ -0,0 +1,270 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// The renderer's profile (make_profile, gpu/vk/vk_shader.cpp) on GPUs with and without nonuniform indexing of storage image,
// uniform texel buffer and storage texel buffer arrays, and synthetic compute programs with descriptor arrays of each kind
// through the real texture pass and SPIR-V back end: no game or GPU (tests/test_nonuniform_image_arrays.py cuts make_profile,
// storage_binding_align and translator_stamp's nonuniform word out of the tree into nonuniform_profile.inc, builds this and
// validates its modules).
//
// A handle read from a constant buffer at a dynamic offset (base + element * 8) is a descriptor array: the texture pass sizes it
// by the words left after the base (DynamicDescriptorCount) and indexes it with the element, here each invocation's own. The
// same programs with the handle at a constant offset are single descriptors.
//
// nonuniform_image_arrays_ir <output folder>
// writes <device>.<program>.spv for each GPU and program and prints one line each:
// <device>.<program> <words> (a module)
// <device>.<program> refused: <what> (what the translation threw)
// stamp <device> <words> (what translator_stamp's nonuniform word adds, in hex, comma separated; - for
// nothing; "missing" when the tree's translator_stamp has no such word)
#include <array>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <fstream>
#include <string>
#include <utility>
#include <vector>
#include "shader_recompiler/backend/spirv/emit_spirv.h"
#include "shader_recompiler/backend/spirv/mma_layout.h"
#include "shader_recompiler/environment.h"
#include "shader_recompiler/frontend/ir/ir_emitter.h"
#include "shader_recompiler/host_translate_info.h"
#include "shader_recompiler/ir_opt/passes.h"
#include "shader_recompiler/object_pool.h"
#include "shader_recompiler/profile.h"
// What make_profile and storage_binding_align read of the renderer (vk_internal.h's dev): a GPU with 32 lanes, no float add of
// its own, NVIDIA's gather, 16-byte storage buffer offsets, f16 shaders; the nonuniform indexing features set per device below
constexpr uint32_t VK_SHADER_STAGE_ALL = 0x7fffffff;
constexpr uint32_t VK_DRIVER_ID_AMD_PROPRIETARY = 1;
constexpr uint32_t VK_DRIVER_ID_MESA_RADV = 3; // (make_profile: RADV before Mesa 26.2.5 keeps NumWorkgroups live)
#define VK_MAKE_VERSION(major, minor, patch) ((((uint32_t)(major)) << 22U) | (((uint32_t)(minor)) << 12U) | ((uint32_t)(patch)))
using VkBool32 = uint32_t;
using VkShaderStageFlags = uint32_t;
constexpr VkBool32 VK_FALSE = 0;
constexpr uint32_t VK_SHADER_STAGE_VERTEX_BIT = 0x1, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 0x2,
VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 0x4, VK_SHADER_STAGE_GEOMETRY_BIT = 0x8,
VK_SHADER_STAGE_FRAGMENT_BIT = 0x10, VK_SHADER_STAGE_COMPUTE_BIT = 0x20, VK_SHADER_STAGE_TASK_BIT_EXT = 0x40,
VK_SHADER_STAGE_MESH_BIT_EXT = 0x80;
enum VkShaderFloatControlsIndependence { VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_32_BIT_ONLY = 0,
VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL = 1, VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE = 2 };
struct {
uint32_t subgroup_max = 32, driver_id = 0;
bool float_atomic_add = false;
struct {
bool shaderFloat16 = true;
VkBool32 shaderBufferInt64Atomics = 1;
bool shaderStorageImageArrayNonUniformIndexing = false, shaderUniformTexelBufferArrayNonUniformIndexing = false,
shaderStorageTexelBufferArrayNonUniformIndexing = false;
} vk12;
struct { struct { uint64_t minStorageBufferOffsetAlignment = 16; } limits; uint32_t driverVersion = 0; } props;
struct { bool gather_offset = false; } fixes;
struct {
VkShaderFloatControlsIndependence denormBehaviorIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL,
roundingModeIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL;
VkBool32 shaderSignedZeroInfNanPreserveFloat16 = 1, shaderSignedZeroInfNanPreserveFloat32 = 1,
shaderDenormPreserveFloat32 = 1, shaderDenormFlushToZeroFloat32 = 1;
} float_controls;
VkShaderStageFlags subgroup_stages = 0xff;
} dev;
#include "nonuniform_profile.inc" // (storage_binding_align, make_profile, profile(), stamp_section and STAMP_SECTION)
using namespace Shader;
struct TestEnvironment final : Environment {
TestEnvironment() { stage = Stage::Compute; }
u64 ReadInstruction(u32) override { return 0; }
u32 ReadCbufValue(u32, u32) override { return 1; }
TextureType ReadTextureType(u32) override { return TextureType::Color2D; }
TexturePixelFormat ReadTexturePixelFormat(u32) override { return {}; }
bool IsTexturePixelFormatInteger(u32) override { return false; }
u32 ReadViewportTransformState() override { return 1; }
u32 TextureBoundBuffer() const override { return 0; }
u32 LocalMemorySize() const override { return 0; }
u32 SharedMemorySize() const override { return 0; }
std::array<u32, 3> WorkgroupSize() const override { return {64, 1, 1}; }
bool HasHLEMacroState() const override { return false; }
std::optional<ReplaceConstant> GetReplaceConstBuffer(u32, u32) override { return std::nullopt; }
void Dump(u64, u64) override {}
};
enum class Kind { TextureBuffer, ImageBuffer, Texture, Image, ImageBufferAtomic, ImageAtomic };
struct Array {
Kind kind;
u32 count; // (1: a handle at a constant offset, a single descriptor)
};
// The GPUs: which of the three kinds of array they index nonuniformly (Vulkan 1.2's features of those names)
struct Device {
const char* name;
bool storage_image, uniform_texel_buffer, storage_texel_buffer;
};
// The texture pass's limit with no device limits (HostTranslateInfo::DEFAULT_DESCRIPTOR_LIMIT) reads 16 bytes a descriptor:
// a base 8 * count bytes before that end leaves room for count descriptors of 8 bytes
constexpr u32 kCbufEnd = 16 * HostTranslateInfo::DEFAULT_DESCRIPTOR_LIMIT;
IR::U32 Handle(IR::IREmitter& ir, u32 cbuf, u32 count, const IR::U32& element) {
if (count == 1) {
return ir.GetCbuf(ir.Imm32(cbuf), ir.Imm32(0x40));
}
const IR::U32 offset{ir.IAdd(ir.Imm32(kCbufEnd - 8 * count), IR::U32{ir.ShiftLeftLogical(element, ir.Imm32(3))})};
return ir.GetCbuf(ir.Imm32(cbuf), offset);
}
IR::Value AsU32x4(IR::IREmitter& ir, const IR::Value& color) {
std::array<IR::U32, 4> parts;
for (size_t i = 0; i < parts.size(); ++i) {
parts[i] = ir.BitCast<IR::U32, IR::F32>(IR::F32{ir.CompositeExtract(color, i)});
}
return ir.CompositeConstruct(parts[0], parts[1], parts[2], parts[3]);
}
std::vector<u32> Emit(const std::vector<Array>& arrays, const Profile& device_profile) {
ObjectPool<IR::Inst> inst_pool;
IR::Block block{inst_pool};
IR::Program program;
program.stage = Stage::Compute;
program.workgroup_size = {64, 1, 1};
program.blocks.push_back(&block);
program.post_order_blocks.push_back(&block);
IR::AbstractSyntaxNode node{};
node.type = IR::AbstractSyntaxNode::Type::Block;
node.data.block = &block;
program.syntax_list.push_back(node);
IR::AbstractSyntaxNode ret{};
ret.type = IR::AbstractSyntaxNode::Type::Return;
program.syntax_list.push_back(ret);
IR::IREmitter ir{block};
const IR::U32 lane{ir.LocalInvocationIdX()}; // (each invocation its own element: nonuniform)
const IR::U32 next{ir.IAdd(lane, ir.Imm32(1))};
IR::TextureInstInfo out{}; // (where sampled reads are stored: a single image buffer bound at c0[0x100])
out.type.Assign(TextureType::Buffer);
out.image_format.Assign(ImageFormat::R32_UINT);
u32 cbuf{2};
for (const Array& array : arrays) {
const IR::U32 handle{Handle(ir, cbuf++, array.count, lane)};
IR::TextureInstInfo info{};
info.image_format.Assign(ImageFormat::R32_UINT);
switch (array.kind) {
case Kind::ImageBuffer: {
info.type.Assign(TextureType::Buffer);
const IR::Value texel{ir.ImageRead(handle, lane, info)};
ir.ImageWrite(handle, next, texel, info);
break;
}
case Kind::Image: {
info.type.Assign(TextureType::Color2D);
const IR::Value texel{ir.ImageRead(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), info)};
ir.ImageWrite(handle, ir.CompositeConstruct(next, ir.Imm32(1)), texel, info);
break;
}
case Kind::TextureBuffer: {
info.type.Assign(TextureType::Buffer);
const IR::Value texel{ir.ImageFetch(handle, lane, {}, {}, {}, info)};
ir.ImageWrite(ir.Imm32(0x100), lane, AsU32x4(ir, texel), out);
break;
}
case Kind::Texture: {
info.type.Assign(TextureType::Color2D);
const IR::Value texel{
ir.ImageFetch(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), {}, ir.Imm32(0), {}, info)};
ir.ImageWrite(ir.Imm32(0x100), next, AsU32x4(ir, texel), out);
break;
}
case Kind::ImageBufferAtomic: {
info.type.Assign(TextureType::Buffer);
const IR::U32 old{ir.ImageAtomicIAdd(handle, lane, ir.Imm32(1), info)};
ir.ImageWrite(ir.Imm32(0x100), lane, ir.CompositeConstruct(old, old, old, old), out);
break;
}
case Kind::ImageAtomic: {
info.type.Assign(TextureType::Color2D);
const IR::U32 old{ir.ImageAtomicIAdd(handle, ir.CompositeConstruct(lane, ir.Imm32(0)), ir.Imm32(1), info)};
ir.ImageWrite(ir.Imm32(0x100), lane, ir.CompositeConstruct(old, old, old, old), out);
break;
}
}
}
ir.Epilogue();
TestEnvironment env;
HostTranslateInfo host_info{};
host_info.support_snorm_render_buffer = true;
host_info.ApplyDescriptorLimitPolicy(); // (as TranslateProgram: no device limits, the defaults)
Optimization::TexturePass(env, program, host_info);
Optimization::DeadCodeEliminationPass(program);
Optimization::CollectShaderInfoPass(env, program);
return Backend::SPIRV::EmitSPIRV(device_profile, program);
}
int main(int argc, char** argv) {
if (argc != 2) {
std::fprintf(stderr, "usage: nonuniform_image_arrays_ir <output folder>\n");
return 2;
}
const std::filesystem::path folder{argv[1]};
std::filesystem::create_directories(folder);
const std::array<Device, 5> devices{{
{"none", false, false, false},
{"storage-image", true, false, false},
{"uniform-texel-buffer", false, true, false},
{"storage-texel-buffer", false, false, true},
{"all", true, true, true},
}};
const std::array<std::pair<const char*, std::vector<Array>>, 13> programs{{
{"imgbuf-1", {{Kind::ImageBuffer, 1}}},
{"img-1", {{Kind::Image, 1}}},
{"texbuf-1", {{Kind::TextureBuffer, 1}}},
{"imgbuf-atomic-1", {{Kind::ImageBufferAtomic, 1}}},
{"img-atomic-1", {{Kind::ImageAtomic, 1}}},
{"mixed-1", {{Kind::TextureBuffer, 1}, {Kind::ImageBuffer, 1}, {Kind::Texture, 1}, {Kind::Image, 1}}},
{"tex-2", {{Kind::Texture, 2}}},
{"imgbuf-2", {{Kind::ImageBuffer, 2}}},
{"img-3", {{Kind::Image, 3}}},
{"texbuf-2", {{Kind::TextureBuffer, 2}}},
{"imgbuf-atomic-2", {{Kind::ImageBufferAtomic, 2}}},
{"img-atomic-3", {{Kind::ImageAtomic, 3}}},
{"mixed", {{Kind::TextureBuffer, 2}, {Kind::ImageBuffer, 2}, {Kind::Texture, 2}, {Kind::Image, 3}}},
}};
Backend::SPIRV::fetch_bounds = Backend::SPIRV::fetch_bounds_buffers = false; // (NVIDIA's: vk_vendor.h)
for (const Device& device : devices) {
dev.vk12.shaderStorageImageArrayNonUniformIndexing = device.storage_image;
dev.vk12.shaderUniformTexelBufferArrayNonUniformIndexing = device.uniform_texel_buffer;
dev.vk12.shaderStorageTexelBufferArrayNonUniformIndexing = device.storage_texel_buffer;
const Profile device_profile{make_profile()};
current_profile = &device_profile;
std::string words;
stamp_section([&words](const void* data, size_t bytes) {
for (size_t i = 0; i < bytes / 4; ++i) {
char hex[16];
std::snprintf(hex, sizeof hex, "%s%08x", words.empty() ? "" : ",", static_cast<const uint32_t*>(data)[i]);
words += hex;
}
});
std::printf("stamp %s %s\n", device.name, STAMP_SECTION ? (words.empty() ? "-" : words.c_str()) : "missing");
for (const auto& [name, arrays] : programs) {
const std::string id{std::string{device.name} + "." + name};
std::vector<u32> module;
try {
module = Emit(arrays, device_profile);
} catch (const std::exception& e) {
std::printf("%s refused: %s\n", id.c_str(), e.what());
continue;
}
std::ofstream file(folder / (id + ".spv"), std::ios::binary);
file.write(reinterpret_cast<const char*>(module.data()), static_cast<std::streamsize>(module.size() * 4));
if (!file) {
std::fprintf(stderr, "%s: not written\n", id.c_str());
return 3;
}
std::printf("%s %zu\n", id.c_str(), module.size());
}
}
return 0;
}

426
tests/pad_speaker_test.c Normal file
View File

@@ -0,0 +1,426 @@
/* host/pad_speaker.c itself against a made-up DualSense: SDL's endpoint calls and the pad's output report are stood in
for here, and the test plays the mixer, SDL's audio thread and the pads' poll in turn. */
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "../gpu/vk/vk_api.h" /* ((Triforce) HOS_OPT_PAD_SPEAKER_*: the menu's three packed numbers) */
#define CHECK(x) do { if (!(x)) { fprintf(stderr, "FAIL line %d: %s\n", __LINE__, #x); exit(1); } } while (0)
static int64_t now_ns;
int64_t hos_now_ns(void) { return now_ns; }
void hos_log(const char *fmt, ...) { (void)fmt; }
/* the Audio tab's Controller speaker rows: their values, or -1 (-1000 for the sync) for the player's usual choice here:
Navi, targeting, pick-ups, the interface, the Stone of Agony, the low-health alarm, fishing and bottles on the pad alone,
her flight, the ocarina, items and fairies on both, all sound to headphones. (Triforce: those are not the defaults, which
are all Off, "defaults" below; the cases here play a player who chose them.) no_renderer: rx_option's otherwise, as
before the renderer is up */
static int menu_volume = -1, menu_sync = -1000, menu_class[12] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
static int menu_headphones = -1, menu_headphone_volume = -1, no_renderer;
static const int chosen_class[12] = {1, 2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 1};
static int clamp_int(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
int rx_option(int id, int otherwise) {
/* (gpu/vk/vk_api.h's packed numbers, as gpu/vk/vk_replay.cpp packs the rows: the classes 323, the levels 324, the
headphones 325) */
if (no_renderer) return otherwise;
if (id == HOS_OPT_PAD_SPEAKER_CLASSES) {
int packed = 0;
for (int k = 0; k < 12; k++) packed |= clamp_int(menu_class[k] < 0 ? chosen_class[k] : menu_class[k], 0, 2) << (2 * k);
return packed;
}
if (id == HOS_OPT_PAD_SPEAKER_LEVELS)
return clamp_int(menu_volume < 0 ? 100 : menu_volume, 0, 200) | (clamp_int(menu_sync == -1000 ? 0 : menu_sync, -100, 150) + 100) << 8 |
clamp_int(menu_headphone_volume < 0 ? 80 : menu_headphone_volume, 0, 100) << 16;
CHECK(id == HOS_OPT_PAD_SPEAKER_HEADPHONES);
return menu_headphones < 0 ? 2 : menu_headphones;
}
static int pad_headphones = -1; /* (what the made-up pad's report says: -1 nothing) */
int hos_sdl_pad_headphones(void *pad) { (void)pad; return pad_headphones; }
static int endpoints = 1, endpoint_channels = 4, alive = 1, opened, closed, open_fails;
static void *unmatched_pad;
static const char *endpoint_name = "Speakers (DualSense Wireless Controller)";
static void (*pull)(void *user, uint8_t *out, int len);
static uint8_t report[64];
static int reports, report_size, reject_report;
static void *report_pad;
/* host/hos_sdl.c's playback devices: a sound card, then the pad's (when there) */
int hos_sdl_output_count(void) { return endpoints ? 2 : 1; }
int hos_sdl_output_info(int index, char *id, int id_capacity, char *name, int name_capacity) {
snprintf(id, (size_t)id_capacity, "%s", index == 0 ? "card" : "pad");
snprintf(name, (size_t)name_capacity, "%s", index == 0 ? "Speakers (some sound card)" : endpoint_name);
return index == 0 || (index == 1 && endpoints);
}
int hos_sdl_output_channels(int index) { return index == 0 ? 2 : endpoint_channels; }
int hos_sdl_output_resolve(const char *id) { return !strcmp(id, "pad") ? 9 : 7; }
int hos_sdl_pad_audio_endpoint(void *pad) { return pad && pad != unmatched_pad && endpoints && endpoint_channels >= 4 ? 9 : -1; }
void *hos_sdl_audio_open_device(unsigned device, int freq, int channels, int s16, int frames, void (*p)(void *user, uint8_t *out, int len), void *user) {
CHECK(device == 9 && freq == 48000 && channels == 4 && !s16 && !user && frames == (getenv("HOS_PAD_SPEAKER_LOW_LATENCY") ? 0 : 256));
if (open_fails) return NULL;
pull = p, opened++;
return &opened;
}
int hos_sdl_audio_alive(void *stream) { CHECK(stream == &opened); return alive; }
void hos_sdl_audio_close(void *stream) { CHECK(stream == &opened); pull = NULL, closed++; }
/* host/rumble_renhdrum.c: the vibration's stream on a cabled DualSense, none unless a test gives the pad one */
static void *vib_owner;
static int vib_alive = 1;
void *rh_usb_owner(void) { return vib_owner; }
int rh_usb_alive(void) { return vib_alive; }
int rh_usb_restart_audio(void) { return vib_alive; }
static int vib_token = 9; /* (the vibration's endpoint: the pad's own, 9, unless a test moves it) */
int rh_usb_token(void) { return vib_owner && vib_alive ? vib_token : -1; }
static int vib_want = -1, vib_gain = -1; /* (what the speaker last asked of the vibration's stream: RenHDrum's to open) */
int rh_usb_speaker(int want, int gain) { vib_want = want, vib_gain = gain; return 1; }
int hos_sdl_pad_effect(void *pad, const void *data, int size) {
CHECK(size <= (int)sizeof report);
memcpy(report, data, (size_t)size), report_size = size, report_pad = pad, reports++;
return !reject_report;
}
#include "pad_speaker.c"
#ifndef _WIN32
void Sleep(DWORD ms) { (void)ms; } /* (host/posix's in the game) */
#endif
static float out[4800 * 4], in[4800];
static void play(int frames) { CHECK(pull); memset(out, 0x55, sizeof out); pull(NULL, (uint8_t *)out, frames * 4 * (int)sizeof(float)); }
static void second(void) { now_ns += 1000000000; }
/* the mixer: frames of a sine, on from where the last call stopped, in its 240-sample frames */
static double tone_phase;
static void tone(double hz, float amp, int frames) {
for (int done = 0; done < frames; done += 240) {
for (int i = 0; i < 240; i++) in[i] = amp * (float)sin(tone_phase), tone_phase += 2 * 3.14159265358979323846 * hz / 48000;
hos_pad_speaker_write(in, 240);
}
}
static float peak(int from, int to) { /* the loudest of the speaker's channel over out[from..to) */
float p = 0;
for (int i = from; i < to; i++) p = fabsf(out[i * 4]) > p ? fabsf(out[i * 4]) : p;
return p;
}
static uint32_t fill_now(void) { return ring_fill(); }
int main(int argc, char **argv) {
int pad_a, pad_b;
CHECK(argc == 2);
if (!strcmp(argv[1], "wrap")) {
hos_pad_speaker_pad(&pad_a, 1);
CHECK(hos_pad_speaker_active());
InterlockedExchange((volatile LONG *)&ring_w, (LONG)(UINT32_MAX - 119));
InterlockedExchange((volatile LONG *)&ring_r, (LONG)(UINT32_MAX - 119));
tone(440, 0.5f, 1200);
CHECK(ring_fill() == 1200);
play(240);
CHECK(ring_fill() < 1200 && ring_fill() > 900);
return 0;
}
if (!strcmp(argv[1], "reject")) {
reject_report = 1;
hos_pad_speaker_pad(&pad_a, 1);
CHECK(!hos_pad_speaker_active() && !hos_pad_speaker_headphones_all());
return 0;
}
if (!strcmp(argv[1], "defaults")) { /* (Triforce) no choice made: every kind Off, headphones Off, nothing opens */
no_renderer = 1;
hos_pad_speaker_pad(&pad_a, 1);
for (int c = AUDIO_SOURCE_NONE; c < AUDIO_SOURCE_CLASSES; c++) CHECK(hos_pad_speaker_mode(c) == HOS_PAD_SPEAKER_OFF);
pad_headphones = 1; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened && !reports && !hos_pad_speaker_active() && !hos_pad_speaker_headphones_all());
no_renderer = 0; /* (the menu's rows at their defaults: the same) */
for (int i = 0; i < 12; i++) menu_class[i] = 0;
menu_headphones = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened && !reports && !hos_pad_speaker_active() && !hos_pad_speaker_headphones_all());
puts("pad speaker: by default nothing goes to the pad, and it keeps its own sound");
return 0;
}
if (!strcmp(argv[1], "off")) { /* HOS_PAD_SPEAKER=0 */
hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened && !reports && !hos_pad_speaker_active());
puts("pad speaker: switched off, a DualSense on a cable is left alone");
return 0;
}
if (!strcmp(argv[1], "modes")) { /* HOS_PAD_SPEAKER_UI=0, HOS_PAD_SPEAKER_OCARINA=1, HOS_PAD_SPEAKER_AGONY=7 */
hos_pad_speaker_pad(NULL, 0);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_NONE) == HOS_PAD_SPEAKER_OFF && hos_pad_speaker_mode(AUDIO_SOURCE_CLASSES) == HOS_PAD_SPEAKER_OFF);
CHECK(hos_pad_speaker_mode(-3) == HOS_PAD_SPEAKER_OFF);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_NAVI_VOICE) == HOS_PAD_SPEAKER_ONLY && hos_pad_speaker_mode(AUDIO_SOURCE_NAVI_SOUND) == HOS_PAD_SPEAKER_BOTH);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_UI) == HOS_PAD_SPEAKER_OFF && hos_pad_speaker_mode(AUDIO_SOURCE_OCARINA) == HOS_PAD_SPEAKER_ONLY);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_AGONY) == HOS_PAD_SPEAKER_BOTH); /* (out of range: the nearest) */
menu_class[AUDIO_SOURCE_NAVI_VOICE - 1] = 2, menu_class[AUDIO_SOURCE_UI - 1] = 2, menu_class[AUDIO_SOURCE_FAIRY - 1] = 9;
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_NAVI_VOICE) == HOS_PAD_SPEAKER_ONLY); /* (read at the poll, not at every sound) */
hos_pad_speaker_pad(NULL, 0);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_NAVI_VOICE) == HOS_PAD_SPEAKER_BOTH); /* the menu's row */
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_FAIRY) == HOS_PAD_SPEAKER_BOTH);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_UI) == HOS_PAD_SPEAKER_OFF); /* the switch, over the menu's */
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_LOW_HEALTH) == HOS_PAD_SPEAKER_ONLY); /* (the later classes: their own rows) */
menu_class[AUDIO_SOURCE_BOTTLE - 1] = 2, menu_class[AUDIO_SOURCE_FISHING - 1] = 0;
hos_pad_speaker_pad(NULL, 0);
CHECK(hos_pad_speaker_mode(AUDIO_SOURCE_BOTTLE) == HOS_PAD_SPEAKER_BOTH && hos_pad_speaker_mode(AUDIO_SOURCE_FISHING) == HOS_PAD_SPEAKER_OFF);
puts("pad speaker: each class's mode from the menu's row, or its switch over it");
return 0;
}
if (!strcmp(argv[1], "menu")) { /* no switch: the menu's rows alone */
menu_volume = 60;
for (int i = 0; i < 12; i++) menu_class[i] = 0;
hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened && !reports); /* every kind Off: the pad keeps its sound */
menu_class[AUDIO_SOURCE_OCARINA - 1] = 1; second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 1 && reports == 1 && report[5] == 100 && hos_pad_speaker_mode(AUDIO_SOURCE_OCARINA) == HOS_PAD_SPEAKER_ONLY);
second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 1 && !test_left); /* (nothing moved: nothing sent) */
menu_volume = 30; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 1 && reports == 1 && test_left > 0); /* a tone at the new volume (ours: the pad's own stays at its top) */
InterlockedExchange(&test_left, 0);
for (int k = 0; k < 20; k++) tone(1000, 0.1f, 240), play(240);
CHECK(peak(0, 240) > 0.057f && peak(0, 240) < 0.063f); /* 30%: 0.3 x 2 of the mixer's */
menu_volume = 200; second(); hos_pad_speaker_pad(&pad_a, 1); InterlockedExchange(&test_left, 0);
for (int k = 0; k < 20; k++) tone(1000, 0.1f, 240), play(240);
CHECK(peak(0, 240) > 0.38f && peak(0, 240) < 0.42f); /* 200%: four times */
menu_volume = 900; second(); hos_pad_speaker_pad(&pad_a, 1); InterlockedExchange(&test_left, 0);
CHECK(volume == 200);
menu_class[AUDIO_SOURCE_OCARINA - 1] = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(closed == 1 && reports == 2 && report[7] == 0 && !hos_pad_speaker_active()); /* the last kind Off: the jack back */
puts("pad speaker: open while a kind of sound plays there, the menu's volume sent when it moves");
return 0;
}
if (!strcmp(argv[1], "ride_other")) { /* the vibration found an endpoint by name that is not this pad's own */
vib_owner = &pad_a, vib_token = 5;
hos_pad_speaker_pad(&pad_a, 1);
CHECK(!riding && opened == 1 && vib_want == -1 && hos_pad_speaker_active()); /* (not shared: our own, on the pad's) */
vib_token = 9; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(riding && closed == 1 && vib_want == RH_SPEAKER_GAME); /* (matched: shared) */
puts("pad speaker: the vibration's stream shared only on the endpoint matched to the pad");
return 0;
}
if (!strcmp(argv[1], "ride")) { /* the vibration's stream on the pad carries the speaker's channels */
hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 1 && !riding && hos_pad_speaker_active()); /* (no vibration on it: our own) */
vib_owner = &pad_a; second(); hos_pad_speaker_pad(&pad_a, 1);
/* ours gone; the speaker opened by RenHDrum's block at our gain, no second report of ours */
CHECK(closed == 1 && riding && hos_pad_speaker_active() && reports == 1 && !pull && vib_want == RH_SPEAKER_GAME && vib_gain == 4);
for (int k = 0; k < 10; k++) tone(1000, 0.25f, 240);
static float buf[480 * 4];
for (int i = 0; i < 480; i++) buf[i * 4] = 0.0f, buf[i * 4 + 1] = 0.25f, buf[i * 4 + 2] = 0.5f, buf[i * 4 + 3] = -0.5f;
hos_pad_speaker_fill(buf, 480);
float p = 0;
for (int i = 0; i < 480; i++) { /* (HD Haptics' taps on the second channel kept: the game's added to them) */
CHECK(buf[i * 4 + 2] == 0.5f && buf[i * 4 + 3] == -0.5f && fabsf(buf[i * 4 + 1] - 0.25f - buf[i * 4]) < 1e-6f);
p = fabsf(buf[i * 4]) > p ? fabsf(buf[i * 4]) : p;
}
CHECK(p > 0.4f); /* (the game's sounds added, the voice coils' left as the vibration wrote them) */
for (int k = 0; k < 10; k++) tone(1000, 0.25f, 240);
for (int i = 0; i < 480; i++) buf[i * 4] = -0.9f, buf[i * 4 + 1] = 0.9f;
hos_pad_speaker_fill(buf, 480);
for (int i = 0; i < 480; i++) CHECK(fabsf(buf[i * 4]) <= 1.0f && fabsf(buf[i * 4 + 1]) <= 1.0f); /* (clamped) */
for (int i = 0; i < 12; i++) menu_class[i] = 0;
second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(!riding && vib_want == RH_SPEAKER_NONE && reports == 1); /* nothing there: the speaker RenHDrum's again */
for (int i = 0; i < 12; i++) menu_class[i] = -1;
second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(riding && vib_want == RH_SPEAKER_GAME);
vib_alive = 0; second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(!riding && opened == 2 && pull && hos_pad_speaker_active()); /* the vibration's stream gone: ours again */
hos_pad_speaker_fill(buf, 480); /* (nothing written into a stream that no longer carries it) */
hos_pad_speaker_shutdown();
CHECK(closed == 2 && !hos_pad_speaker_active());
puts("pad speaker: on the vibration's stream while it plays the pad, on its own otherwise");
return 0;
}
if (!strcmp(argv[1], "legacy")) { /* HOS_PAD_SPEAKER_HPF=0, _LIMITER=0, _LOW_LATENCY=0: each fix turned back for a run */
hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 1 && target == 48 * 40); /* (SDL's own pull size, checked by the opener above; the 40 ms ring) */
for (int k = 0; k < 40; k++) tone(60, 0.25f, 240), play(240);
CHECK(peak(0, 240) > 0.2f); /* the bass kept */
for (int k = 0; k < 40; k++) tone(1000, 3.0f, 240), play(240);
int flat = 0;
for (int i = 0; i < 240; i++) flat += fabsf(out[i * 4]) > 0.99f;
CHECK(flat > 20 && peak(0, 240) <= 1.0f); /* the earlier curve: the tops pressed flat against full scale */
for (int k = 0; k < 100; k++) tone(1000, 0.25f, 480), play(481);
CHECK(underruns > 0 || fill_now() < 48 * 40); /* (no following of the pad's clock) */
puts("pad speaker: each fix turned back for a run: the bass, the earlier curve, the 40 ms ring");
return 0;
}
CHECK(!strcmp(argv[1], "play")); /* HOS_PAD_SPEAKER_VOLUME=50: the mixer's own level (half of twice) */
/* nothing opens without a pad, on a wireless pad, or while the pad has no four-channel endpoint */
hos_pad_speaker_pad(NULL, 0); second();
hos_pad_speaker_pad(&pad_a, 0); second();
endpoints = 0; hos_pad_speaker_pad(&pad_a, 1); second();
endpoints = 1; endpoint_channels = 2; hos_pad_speaker_pad(&pad_a, 1); second();
endpoint_channels = 4; unmatched_pad = &pad_a; hos_pad_speaker_pad(&pad_a, 1); second();
CHECK(!opened && !reports && !hos_pad_speaker_active());
for (int i = 0; i < 240; i++) in[i] = 0.5f;
hos_pad_speaker_write(in, 240); /* (not open: dropped) */
unmatched_pad = NULL; open_fails = 1; second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened && !reports);
open_fails = 0; hos_pad_speaker_pad(&pad_a, 1);
CHECK(!opened); /* (asked again only two seconds later) */
second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 1 && hos_pad_speaker_active());
/* the pad was told: audio control and speaker volume, the speaker alone, its volume at the top, gain through the second control */
CHECK(reports == 1 && report_pad == &pad_a && report_size == 47);
CHECK(report[0] == 0xa0 && report[1] == 0x80 && report[5] == 100 && report[7] == 0x30 && report[37] == 4);
for (int i = 0; i < 47; i++) if (i != 0 && i != 1 && i != 5 && i != 7 && i != 37) CHECK(!report[i]);
/* silence until 20 ms are there, then the mixer's sound on the speaker's two channels and nothing on the coils' */
play(480);
for (int i = 0; i < 480 * 4; i++) CHECK(out[i] == 0);
tone(1000, 0.25f, 720); /* 15 ms */
play(240);
for (int i = 0; i < 240 * 4; i++) CHECK(out[i] == 0);
tone(1000, 0.25f, 240); /* 20 ms */
play(240);
CHECK(peak(0, 240) > 0.05f);
for (int k = 0; k < 40; k++) tone(1000, 0.25f, 240), play(240);
for (int i = 0; i < 240; i++) CHECK(out[i * 4 + 1] == out[i * 4] && out[i * 4 + 2] == 0 && out[i * 4 + 3] == 0);
CHECK(peak(0, 240) > 0.23f && peak(0, 240) < 0.27f && underruns == 0); /* (1 kHz passes as it is) */
/* the bass goes: a 60 Hz rumble comes out at a few percent of itself */
for (int k = 0; k < 40; k++) tone(60, 0.25f, 240), play(240);
float bass = 0;
for (int k = 0; k < 8; k++) tone(60, 0.25f, 240), play(240), bass = peak(0, 240) > bass ? peak(0, 240) : bass;
CHECK(bass < 0.025f);
/* far too loud: turned down to under full scale as a whole, never cut flat (no run of samples at the top) */
for (int k = 0; k < 40; k++) tone(1000, 3.0f, 240), play(240);
int flat = 0;
for (int k = 0; k < 8; k++) {
tone(1000, 3.0f, 240), play(240);
CHECK(peak(0, 240) > 0.8f && peak(0, 240) <= 0.9f);
for (int i = 0; i < 240; i++) flat += fabsf(out[i * 4]) >= 0.999f;
}
CHECK(flat == 0);
/* and the gain comes back once it is quiet again (100 ms) */
for (int k = 0; k < 120; k++) tone(1000, 0.25f, 240), play(240);
CHECK(peak(0, 240) > 0.23f && peak(0, 240) < 0.27f);
/* the two clocks apart by 0.2% either way: the ring stays near its 20 ms, nothing dropped, nothing runs dry */
for (int dir = -1; dir <= 1; dir += 2) {
for (int k = 0; k < 2000; k++) tone(1000, 0.25f, 480), play(480 + dir); /* (10 ms at a time, as the two do) */
CHECK(underruns == 0 && trims == 0);
CHECK(fill_avg > 960 - 400 && fill_avg < 960 + 400); /* (within 8 ms of the target, as the pull sees it) */
}
/* a stall (the pad stopped pulling): back to the target at once, the newest samples kept */
tone(1000, 0.25f, 4800);
play(240);
CHECK(trims == 1 && fill_now() <= 960 && fill_now() > 960 - 300);
/* a stopped pull never lets the ring wrap */
for (int f = 0; f < 200; f++) tone(1000, 0.25f, 240);
CHECK(ring_w - ring_r <= RING);
/* the test tone: 0.6 s over whatever plays, on the speaker's channels only, then nothing more */
while (primed) play(4800); /* (drained: silence from here) */
CHECK(hos_pad_speaker_test());
play(4800);
int loud = 0;
for (int i = 0; i < 4800; i++) { CHECK(out[i * 4 + 2] == 0 && out[i * 4 + 3] == 0); loud += out[i * 4] > 0.15f; }
CHECK(loud > 100);
for (int i = 0; i < 12; i++) play(4800);
play(4800);
for (int i = 0; i < 4800 * 4; i++) CHECK(out[i] == 0);
/* the menu's Controller sync holds the pad's sound back by that much more: the ring's target with it */
menu_sync = 50; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(target == 48 * 70);
menu_sync = 900; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(target == 48 * 170 && hos_pad_speaker_tv_delay() == 0); /* (150 ms at most) */
/* below 0 the TV's copy waits instead: the pad's ring at its own 20 ms */
menu_sync = -30; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(target == 48 * 20 && hos_pad_speaker_tv_delay() == 48 * 30);
menu_sync = -900; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(hos_pad_speaker_tv_delay() == 48 * 100); /* (-100 ms at most) */
menu_sync = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(target == 48 * 20 && hos_pad_speaker_tv_delay() == 0);
/* the ocarina on the pad: the rumble at half while it plays, and for 200 ms after */
CHECK(hos_pad_speaker_rumble_percent() == 100);
hos_pad_speaker_ocarina_seen();
CHECK(hos_pad_speaker_rumble_percent() == 50);
now_ns += 150000000;
CHECK(hos_pad_speaker_rumble_percent() == 50);
now_ns += 100000000;
CHECK(hos_pad_speaker_rumble_percent() == 100);
/* headphones in the jack (All sound, the default): the whole mix to them in stereo, nothing classed, the pad told */
pad_headphones = 1; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 1 && report[0] == 0x90 && report[4] == 0x7f * 80 / 100 && report[7] == 0 && report[5] == 0);
CHECK(hos_pad_speaker_headphones_all() && !hos_pad_speaker_active() && hos_pad_speaker_tv_delay() == 0);
{
static int16_t mix[480 * 6];
for (int i = 0; i < 480; i++) mix[2 * i] = 16384, mix[2 * i + 1] = -8192;
InterlockedExchange((volatile LONG *)&ring_r, ring_w), InterlockedExchange(&primed, 0); /* (the ring emptied of what came before) */
for (int k = 0; k < 6; k++) hos_pad_speaker_write_stereo(mix, 480, 2);
hos_pad_speaker_write(in, 240); /* (the classed sounds' mono: not while all of it goes there) */
play(480);
for (int i = 0; i < 480; i++) CHECK(fabsf(out[i * 4] - 0.5f) < 0.001f && fabsf(out[i * 4 + 1] + 0.25f) < 0.001f);
for (int i = 0; i < 480 * 3; i++) mix[i] = 0;
for (int i = 0; i < 480; i++) mix[6 * i + 2] = 16384; /* (5.1: the centre to both sides) */
InterlockedExchange((volatile LONG *)&ring_r, ring_w), InterlockedExchange(&primed, 0); /* (the ring emptied of what came before) */
for (int k = 0; k < 6; k++) hos_pad_speaker_write_stereo(mix, 480, 6);
play(480);
CHECK(fabsf(out[0] - 0.3535f) < 0.001f && fabsf(out[1] - 0.3535f) < 0.001f);
}
CHECK(hos_pad_speaker_rumble_percent() == 100);
hos_pad_speaker_ocarina_seen();
CHECK(hos_pad_speaker_rumble_percent() == 100); /* (no speaker playing: the rumble as it is) */
/* Unplug while full-mix samples are queued: none may reach the speaker. */
CHECK(fill_now() > 0);
pad_headphones = 0; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(hos_pad_speaker_active() && fill_now() == 0 && !primed);
play(480);
CHECK(peak(0, 480) == 0);
pad_headphones = 1; second(); hos_pad_speaker_pad(&pad_a, 1);
/* the headphone volume moved: told again */
menu_headphone_volume = 40; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 1 && report[4] == 0x7f * 40 / 100);
/* Controller sounds: the classed sounds to the headphones (bass kept), the rest stays on the TV */
menu_headphones = 1; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 1 && report[0] == 0x90 && !hos_pad_speaker_headphones_all() && hos_pad_speaker_active());
InterlockedExchange((volatile LONG *)&ring_r, ring_w), InterlockedExchange(&primed, 0);
for (int k = 0; k < 40; k++) tone(60, 0.25f, 240), play(240);
CHECK(peak(0, 240) > 0.2f); /* (60 Hz: headphones play it, at the mixer's own level) */
/* pulled out: back to the speaker */
pad_headphones = 0; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 1 && report[0] == 0xa0 && report[7] == 0x30 && hos_pad_speaker_active());
/* Off: headphones in, the speaker plays all the same */
menu_headphones = 0; pad_headphones = 1; reports = 0; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 0 && hos_pad_speaker_active() && !hos_pad_speaker_headphones_all());
pad_headphones = 0; menu_headphones = -1; second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(reports == 0);
reports = 1; opened = 1; closed = 0; /* (the current stream, for the counts below) */
/* the cable is pulled (the pad is on Bluetooth now): the jack gets its sound back and the endpoint closes */
second(); hos_pad_speaker_pad(&pad_a, 0);
CHECK(closed == 1 && !hos_pad_speaker_active() && reports == 2 && report[0] == 0x80 && report[7] == 0 && report[5] == 0);
CHECK(!hos_pad_speaker_test());
/* back on the cable; then the endpoint dies under it and comes back */
second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 2 && reports == 3 && report[7] == 0x30);
alive = 0; second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(closed == 2 && opened == 3 && hos_pad_speaker_active());
alive = 1;
/* another DualSense takes its place */
second(); second(); hos_pad_speaker_pad(&pad_b, 1);
CHECK(closed == 3 && opened == 4 && report_pad == &pad_b);
/* the pad is gone: no report to a pad that is not there */
reports = 0; second(); hos_pad_speaker_pad(NULL, 0);
CHECK(closed == 4 && reports == 0 && !hos_pad_speaker_active());
/* the game closes: the jack back, and nothing opens after */
second(); second(); hos_pad_speaker_pad(&pad_a, 1);
CHECK(opened == 5);
hos_pad_speaker_shutdown();
CHECK(closed == 5 && reports == 2 && report[7] == 0 && !hos_pad_speaker_active());
second(); second(); hos_pad_speaker_pad(&pad_a, 1);
hos_pad_speaker_shutdown();
CHECK(opened == 5 && closed == 5 && reports == 2);
puts("pad speaker: opens on a wired DualSense's endpoint, routes the pad, primes, plays without bass or clipping, follows the pad's clock, trims a stall, tests, syncs and closes");
return 0;
}

View File

@@ -41,6 +41,10 @@ using VkBuffer = int;
using VkCommandBuffer = int;
VkBuffer guest_pages_buffer = 7;
std::atomic<bool> par_active{false};
// ((Triforce) RX_VK_GP_TABLE's cover, which the cut part feeds and these checks do not use: off)
std::atomic<bool> table_cover_on{false};
void table_mark_changed(uint64_t, uint64_t) {}
void table_flushed_keep() {}
struct Update {
uint64_t first;
std::vector<uint64_t> values;

View File

@@ -192,6 +192,13 @@ bool memory_mirror_bind_wait(VkSemaphoreSubmitInfo*) { return false; }
// checked by tests/test_barrier_rules.py): texture_begin_recording has none of its own to reset)
bool is_bc(VkFormat) { return false; }
bool is_astc(VkFormat) { return false; }
struct {
VkDevice device = VK_NULL_HANDLE;
VkQueue queue = VK_NULL_HANDLE;
uint32_t queue_family = 0;
std::mutex present_mu;
} dev;
#include "init_pieces.inc" // ((Triforce) an upload command buffer that goes on in pieces: upload_piece_next)
#include "init_upload.inc"
#include "init_hooks.inc"
@@ -299,6 +306,23 @@ void texture_look() {
early.done();
look.upload_value = rec_value, look.upload_seg = up_seg, look.uploaded = true;
}
/// ((Triforce) upload_piece_next) A long ASTC upload, cut twice: its first part where an upload goes (this thread's uploads, or
/// the earliest open segment's init command buffer: UploadRedirect), the rest in two pieces of that command buffer, a write of
/// the texture in each; what is recorded after it goes on in the last piece
void texture_long() {
std::lock_guard lk(par_lock);
if (textures.empty()) create(kTex);
UploadRedirect early(upload_earliest::wanted(upload_earliest_on(), false, false) && tl_seg_index >= 0);
VkCommandBuffer c = upload_cmd();
record(c, 'W', kTex);
for (int k = 0; k < 2; k++) {
const VkCommandBuffer next = upload_piece_next(c);
CHECK(next != c && upload_cmd() == next);
c = next;
record(c, 'W', kTex);
}
early.done();
}
bool tex2_made = false;
void texture2_use() { // (another new texture, made by whichever worker gets there first and copied into in its uploads)
std::lock_guard lk(par_lock);
@@ -338,6 +362,7 @@ int64_t record_segment(VkCommandBuffer& cmd, const Segment& g) { // (vk_replay
if (a == 't') texture_use(), record(cmd, 'U', kTex);
if (a == 'u') texture_look(), record(cmd, 'R', kTex);
if (a == 'n') texture2_use(), record(cmd, 'U', kTex2);
if (a == 'P') texture_long(), record(cmd, 'R', kTex); // ((Triforce) an upload in pieces, then a draw that samples it)
if (a == 'r') std::this_thread::sleep_for(std::chrono::microseconds(std::rand() % 3000));
if (a == 's' || a == 'S') scratch_use(a == 'S');
if (a == 'x' || a == 'z' || a == 'w') latch[(int)a].wait();
@@ -365,11 +390,9 @@ void draw_flush_recording(int slot) { CHECK(slot >= 0 && slot < 8); published_sl
void queue_flush_locked() {}
void checkpoints_report() {}
[[noreturn]] void device_lost() { std::_Exit(3); } // (vk_replay.cpp: the report, then the process ends)
struct {
VkDevice device = VK_NULL_HANDLE;
VkQueue queue = VK_NULL_HANDLE;
std::mutex present_mu;
} dev;
VkResult submit_again(VkResult first, const VkSubmitInfo2&, VkFence) { return first; } // (submit_retry.h: no refusal here)
void host_read_barrier(VkCommandBuffer) {} // (a recording's last command, for the host's reads: nothing to order here)
#include "init_alone.inc" // ((Triforce) submit_alone_locked, pieces_alone: an upload command buffer and its pieces, each alone)
std::atomic<int64_t> par_lock_wait_ns{0}, par_locks{0};
std::atomic<bool> par_active{false};
std::vector<int> run_order; // (the order the workers run in, one after another; empty: all at once)
@@ -429,6 +452,10 @@ void occ_seal(Recording&, uint64_t) {}
Recording recordings[8];
int recording_count = 0;
uint64_t rec_cur_value = 1;
bool seg_setup_par_on() { return false; } // (RX_VK_SEG_SETUP_PAR: off, the default)
void segment_begin_here(Recording&) {} // (its job's part of that: nothing with it off)
Recording& begin_segment_recording(uint64_t value);
Recording& begin_segment_slot(uint64_t value) { return begin_segment_recording(value); } // (never called with it off)
Recording& begin_segment_recording(uint64_t value) {
const int k = recording_count++;
published_slots.erase(k);
@@ -629,7 +656,100 @@ int main(int argc, char** argv) {
std::fflush(stdout);
std::_Exit(1);
}).detach();
if (c == "later_makes") { // (segment 1's worker makes the texture, then segment 0's uploads it again and draws with it)
if (c == "upload_pieces") { // ((Triforce) an upload command buffer that went on in pieces: each a submission of its own,
// in order, right after the command buffer it followed and before its segment's commands
// (the queue from `from`: `base`, then `want` pieces, then `then`, nothing between them)
const auto follows = [&](const char* name, size_t from, const char* base, int want, const char* then) {
size_t i = from;
while (i < queue.size() && queue[i]->name != base) i++;
int got = 0;
while (i + 1 + got < queue.size() && queue[i + 1 + got]->name.rfind("pool_", 0) == 0) got++;
const bool ok = i < queue.size() && got == want && i + 1 + got < queue.size() && queue[i + 1 + got]->name == then;
if (!ok) std::printf(" FAIL: %s: want %s, %d pieces, %s in the queue%s\n", name, base, want, then, queue_text().c_str()), failures++;
for (size_t k = i + 1; ok && k <= i + got; k++)
if (queue[k]->ops.empty() || queue[k]->ops[0].kind != 'F')
std::printf(" FAIL: %s: piece %s does not begin with a full barrier\n", name, queue[k]->name.c_str()), failures++;
};
const auto run = [&](const char* name, const std::vector<std::string>& scripts, const std::vector<int>& order) {
std::vector<Segment> seg;
for (const auto& s : scripts) seg.push_back({s});
const size_t from = queue.size();
submit_segments(seg, order);
play(name);
const int n = play_content(name, from);
if (n != 3) std::printf(" FAIL: %s: %d writes of the texture in the queue, want 3\n", name, n), failures++;
return from;
};
// the earliest segment's own uploads; its segment end's barrier and what it uploads after go into the last piece
size_t from = run("upload_pieces (its own uploads)", {"Pn", "-"}, {0, 1});
follows("upload_pieces (its own uploads)", from, "upload_0", 2, "cmd_0");
if (named("upload_0") && ops_text(named("upload_0")).find("t2") != std::string::npos)
std::printf(" FAIL: an upload made after the cut went into the first command buffer, ahead of the pieces\n"), failures++;
reset_run();
// a later segment's worker first: into segment 0's init command buffer, whose end's barrier goes into its last piece
from = run("upload_pieces (an earlier segment's init)", {"t", "P"}, {1, 0});
follows("upload_pieces (an earlier segment's init)", from, "init_0", 2, "upload_0");
reset_run();
// segment 2's into init_0, then segment 0 makes another texture (into its last piece) and segment 1 uses the first
from = run("upload_pieces (init, then its own)", {"n", "t", "P"}, {2, 0, 1});
follows("upload_pieces (init, then its own)", from, "init_0", 2, "upload_0");
reset_run();
std::srand(11);
const char* pick[] = {"-", "P", "rP", "Pr", "r", "t", "n"};
int runs = 3;
for (int i = 0; i < 60 && !failures; i++, runs++) { // (at once, the workers' timing mixed: one long upload a run)
reset_run();
std::vector<std::string> scripts;
const int who = std::rand() % 4;
for (int k = 0; k < 4; k++) scripts.push_back(k == who ? pick[1 + std::rand() % 3] : pick[std::rand() % 7 > 3 ? 4 + std::rand() % 3 : 0]);
std::vector<Segment> seg;
for (const auto& s : scripts) seg.push_back({s});
const size_t q0 = queue.size();
submit_segments(seg, {});
int pieces = 0;
for (size_t q = q0; q < queue.size(); q++) pieces += queue[q]->name.rfind("pool_", 0) == 0;
for (auto* cb : all_cbs)
if (!cb->ops.empty() && !cb->submitted && cb->ops.size() > (size_t)std::count_if(cb->ops.begin(), cb->ops.end(), [](const Op& o) {
return o.kind == 'F' || o.kind == 'G'; }))
std::printf(" FAIL: upload_pieces (at once): %s has commands and was never submitted\n", cb->name.c_str()), failures++;
if (pieces != 2 || play_content("upload_pieces (at once)", q0) != 3)
std::printf(" FAIL: upload_pieces (at once): %d pieces in the queue%s\n", pieces, queue_text().c_str()), failures++;
}
// upload_astc_gpu's count (AstcChunk): Kokiri Forest's terrain array, 1365 x 1365 x 90, a layer a dispatch at its first
// level: 16 million texels a command buffer (the default) are 8 layers, so 90 layers go on in 11 pieces, and the count
// is the command buffer's, carried from one upload to the next (2 layers in the last piece, then 6 more before a 12th)
reset_run();
{
VkCommandBuffer up = make_cb("longupload", 0);
vkBeginCommandBuffer(up, nullptr);
texture_begin_recording(up, rec_cur_value);
int cuts = 0;
{
AstcChunk chunk(upload_cmd());
VkCommandBuffer at = chunk.at;
for (int layer = 0; layer < 90; layer++) {
const VkCommandBuffer now = chunk.before(1365ull * 1365);
cuts += now != at, at = now;
record(now, 'W', kTex2);
}
CHECK(chunk.per == 16000000ull && cuts == 11 && chunk.n == 2 * 1365ull * 1365);
}
{
AstcChunk chunk(upload_cmd());
CHECK(chunk.n == 2 * 1365ull * 1365); // (as the upload before left it)
VkCommandBuffer at = chunk.at;
for (int layer = 0; layer < 7; layer++) cuts += chunk.before(1365ull * 1365) != at, at = chunk.at;
CHECK(cuts == 12 && chunk.before(1) == at && chunk.n == 1365ull * 1365 + 65536); // (a small dispatch counts 64 K)
}
std::vector<UploadPiece> taken;
CHECK(texture_upload_last(up) != up && texture_upload_pieces(up, taken) == 12 && texture_upload_last(up) == up);
for (const UploadPiece& p : taken) CHECK(p.ended && p.cmd->ended && !p.cmd->submitted);
CHECK(!up->ended); // (the first command buffer is its recording's to end)
texture_upload_pieces_free(taken);
CHECK(taken.empty() && texture_upload_pieces(up, taken) == 0);
}
std::printf("%s: %d runs, every piece sent alone after its command buffer and before the commands\n", c.c_str(), runs);
} else if (c == "later_makes") { // (segment 1's worker makes the texture, then segment 0's uploads it again and draws with it)
submit_segments({{"t"}, {"t"}}, {1, 0});
play(c.c_str());
} else if (c == "three") { // (segment 0 is done; 2 makes it while 1 still records, and 1 uses it)

View File

@@ -33,6 +33,10 @@ using VkBuffer = int;
using VkCommandBuffer = int;
VkBuffer guest_pages_buffer = 7;
std::atomic<bool> par_active{false};
// ((Triforce) RX_VK_GP_TABLE's cover, which the cut part feeds and these checks do not use: off)
std::atomic<bool> table_cover_on{false};
void table_mark_changed(uint64_t, uint64_t) {}
void table_flushed_keep() {}
int updates = 0;
void vkCmdUpdateBuffer(VkCommandBuffer, VkBuffer b, uint64_t offset, uint64_t bytes, const void* data) {
require(b == guest_pages_buffer && offset % 8 == 0 && bytes % 8 == 0, "an update of the table, in whole entries");

View File

@@ -55,6 +55,7 @@ unsigned long long program_cache_stamp() { return 0x1122334455667788ull; }
std::uint64_t pcache_bound_bytes = 0;
std::string pcache_path;
std::atomic<int64_t> pcache_built_since_save{32};
bool pcache_no_save = false; // ((Triforce) RX_VK_PCACHE_LOAD=0: not set here)
std::atomic<std::size_t> pcache_saved_size{0};
// The size the driver gives for the cache's data; a case grows it for pipelines taken in between saves.
std::atomic<std::size_t> cache_size{64};

View File

@@ -41,10 +41,25 @@ namespace fsr3fi { bool wanted = false; bool frames_wanted() { return wanted; }
// (Triforce) whether RivaTuner Statistics Server holds the display thread's presents (vk_pace.h): not here
namespace pace { bool display_yields() { return false; } }
int fsr_calls = 0, fsr_result = 1;
int fsr3fi_frame(VkCommandBuffer, OutSet&, int, uint32_t w, uint32_t h, uint64_t sequence) {
// ((Triforce) 11-24) AMD FSR 3.1's frame interpolation at any multiplier (the Frame generation by row): a set's frames at k/m,
// each into its own slot; made (fsr_result) or none. Its HUD source is recorded first (hud_source: nothing here)
int fsr3fi_frames(VkCommandBuffer, OutSet&, int, uint32_t w, uint32_t h, uint64_t sequence, const float* t, const int* slot,
int count) {
CHECK(w == allocated_w && h == allocated_h && sequence > 0);
++fsr_calls; return fsr_result;
for (int i = 0; i < count; i++) CHECK(t[i] > 0.0f && t[i] < 1.0f && slot[i] == i);
++fsr_calls; return fsr_result ? count : 0;
}
bool hud_source(VkCommandBuffer, int, uint32_t, uint32_t, int, int, uint32_t w, uint32_t h) {
CHECK(w == allocated_w && h == allocated_h);
return false;
}
enum { kMakerNone = 0, kMakerOwn = 1, kMakerFsr3 = 2, kMakerAmd = 3 };
std::atomic<int> last_maker{0};
// ((Triforce) 11-24) AMD Anti-Lag 2's frame of a set, and the game's timeline (RX_VK_FG_GAME_TIMELINE, off here)
uint64_t antilag_frame() { return 0; }
bool game_timeline() { return false; }
void fixed_dues(int64_t, int64_t, int, int64_t, int64_t*) { std::abort(); }
int64_t pace_lead(int64_t, int) { std::abort(); }
// (Triforce) AMD FSR 4's frame generation (vk_framegen.cpp fsr4_frame, vk_fsr4.h): a stand-in that answers as told
int fsr4_calls = 0;
bool fsr4_blend = false;

View File

@@ -94,6 +94,13 @@ FILE* disk_out = nullptr;
FILE* disk_idx = nullptr;
std::mutex disk_mu;
std::unordered_map<uint64_t, std::vector<DiskRecord>> disk_records;
// ((Triforce) the records read in already, as vk_shader.cpp keeps them for the prediction)
std::unordered_map<uint64_t, std::vector<DiskRecord>> disk_taken;
void disk_note_taken(uint64_t key, const std::vector<DiskRecord>& recs) {
if (recs.empty()) return;
auto& taken = disk_taken[key];
taken.insert(taken.end(), recs.begin(), recs.end());
}
std::atomic<int64_t> st_cache_hits{0};
// ((Triforce) vk_shader.cpp's count of programs translated again after a cache of other translations was thrown away, for the
// log: none was here. tests/test_program_carry.py has the carry)
@@ -110,6 +117,11 @@ const std::vector<uint32_t>* renodx_replacement(uint32_t) { return nullptr; }
void exact_note(VkShaderModule, const std::vector<uint32_t>&) {}
void lanes_note(VkShaderModule, const std::vector<uint32_t>&) {} // (PIPE-52: make_module's note of a module's Subgroup barriers)
void size_note(VkShaderModule, const std::vector<uint32_t>&) {} // (PIPE-56: its OpPhi and OpFunctionCall counts)
// ((Triforce) make_module's module made inside the driver fault guard, for the program translate_into names: here the stub above)
thread_local uint64_t module_program = 0;
int extern_guarded_shader_module(const VkShaderModuleCreateInfo* ci, VkShaderModule* m, uint64_t) {
return vkCreateShaderModule(dev.device, ci, nullptr, m);
}
void size_move(VkShaderModule, VkShaderModule) {}
// (Triforce, RX_VK_SPV_PACK: vk_shader.cpp's packing of a ready program's stages. Off here, as with RX_VK_SPV_PACK=0:
// every stage keeps its module, which is what this test counts. tests/test_spv_store.py has the packing)
@@ -149,6 +161,12 @@ void readahead_drop(std::vector<std::unique_ptr<Program>>& variants) { // (as
}
// ((Triforce) the sessions' order, program_order.h: off here; tests/test_program_order.py has it)
bool order_on() { return false; }
void programs_load_wait(uint64_t) {} // (vk_programs.cpp: no load at create here)
bool light_computes() { return false; }
struct { uint64_t loads = 0, load_ns = 0; } thread_local use_counters; // (vk_programs.h's census: counted, not read here)
struct { uint64_t play_loads = 0, play_load_ns = 0; } census;
std::atomic<bool> programs_in_play{false};
std::unique_ptr<Program> read_light(FILE*, std::mutex*, uint64_t, const DiskRecord&) { return nullptr; }
void order_note(uint64_t) {}
void readahead_why(uint64_t) {}
#include <chrono>

111
tests/program_life_test.cpp Normal file
View File

@@ -0,0 +1,111 @@
// program_life (gpu/vk/program_life.h): the states of what the game's programs need loaded. A unit is queued once when the game
// first makes a program of its stages, a first use waits only for a load that is under way, a unit is let go only by count, only
// when the game has freed every program of it and it was drawn, the longest freed first, and is loaded again by the next create.
// No game, no GPU.
#include "../gpu/vk/program_life.h"
#include <cstdio>
namespace {
using program_life::State;
using program_life::Table;
using program_life::Use;
int failures = 0;
void expect(bool ok, const char* what) {
if (!ok) std::printf("FAIL: %s\n", what), failures++;
}
void create_and_use() {
Table t;
expect(t.use(7) == Use::Miss, "a unit no create call named is a miss: the first-use path as before");
expect(t.create(1, 7, true), "the first program of prepared stages queues a load");
expect(t.find(7)->state == State::Created, "created until the job is queued");
expect(t.use(7) == Use::Miss, "not queued yet: a draw does not wait for a job that does not exist");
t.loading(7);
expect(!t.create(2, 7, true), "a second program of the same stages does not queue a second load");
expect(t.use(7) == Use::Wait, "a draw while the job runs waits for it");
t.loaded(7, true);
expect(t.find(7)->state == State::Ready && !t.find(7)->drawn, "loaded: ready, not drawn yet");
expect(!t.create(3, 7, true), "a program of stages already loaded queues nothing");
expect(t.use(7) == Use::Ready && t.find(7)->drawn, "a draw of a ready unit goes ahead, and it counts as drawn");
expect(t.find(7)->live == 3 && t.programs() == 3 && t.units() == 1, "three programs, one unit");
expect(t.unit_of(2) == 7 && t.unit_of(9) == 0, "a serial's unit; none for a serial never created");
}
void nothing_prepared() {
Table t;
expect(!t.create(1, 5, false), "stages the prepare kept nothing for queue no load: never a translation at create");
t.loading(5);
expect(t.find(5)->state == State::Loading, "(loading is the caller's to call only after a true create)");
Table u;
expect(!u.create(1, 5, false) && u.use(5) == Use::Miss, "and their first draw is a miss: translated there, as before");
expect(u.create(2, 5, true), "once something is prepared for them (learned), the next create queues it");
}
void failed_job() {
Table t;
expect(t.create(1, 5, true), "queued");
t.loading(5);
t.loaded(5, false);
expect(t.find(5)->state == State::Created && t.use(5) == Use::Miss, "a job that loaded nothing leaves the first-use path");
expect(!t.create(2, 5, false), "and is not queued again for the same stages");
expect(t.find(5)->loads == 0, "nothing was loaded");
}
void set_shaders_again() {
Table t;
t.create(1, 5, true);
t.loading(5), t.loaded(5, true);
expect(t.create(1, 6, true), "the same program given other shaders, with no free call: the new stages queue");
expect(t.find(5)->live == 0 && t.find(6)->live == 1 && t.unit_of(1) == 6, "the old stages' unit lost that program");
t.free(1);
t.free(1);
expect(t.find(6)->live == 0 && t.programs() == 0, "a free call counts once");
}
void release_by_count() {
Table t;
for (uint64_t u = 1; u <= 6; u++) {
t.create(u, 100 + u, true);
t.loading(100 + u), t.loaded(100 + u, true);
}
for (uint64_t u = 1; u <= 5; u++) t.use(100 + u); // (106 is loaded and never drawn)
expect(t.release_candidates(0).empty(), "nothing is let go while the game still has the programs");
t.free(3), t.free(1), t.free(6), t.free(2); // (freed in this order; 104 and 105 are still alive)
expect(t.release_candidates(3).empty(), "three freed and drawn units, three kept: none let go");
const auto one = t.release_candidates(2);
expect(one.size() == 1 && one[0] == 103, "above the count only the excess goes, the longest freed first");
const auto all = t.release_candidates(0);
expect(all.size() == 3 && all[0] == 103 && all[1] == 101 && all[2] == 102, "oldest first, in the order they were freed");
for (const uint64_t u : all) expect(u != 106, "a unit loaded and never drawn is not let go early");
for (const uint64_t u : all) expect(u != 104 && u != 105, "a unit the game still has a program of is never let go");
t.released(103);
expect(t.find(103)->state == State::Released && t.use(103) == Use::Miss, "let go: a use finds nothing loaded");
t.released(104);
expect(t.find(104)->state == State::Ready, "released() refuses a unit that is still alive");
expect(t.release_candidates(0).size() == 2, "a released unit is not a candidate again");
// the game makes a program of the released stages again (back and forth between two areas)
expect(t.create(7, 103, true), "a create of released stages queues the load again, from prepared data");
t.loading(103), t.loaded(103, true);
expect(t.find(103)->loads == 2 && t.find(103)->state == State::Ready && !t.find(103)->drawn, "loaded a second time: a reload");
expect(t.release_candidates(0).size() == 2, "alive again: not a candidate");
// a unit freed and made again before any release keeps what it has
t.free(4);
expect(!t.create(8, 104, true) && t.find(104)->state == State::Ready, "freed and made again without a release: nothing is reloaded");
expect(t.count(State::Ready) == 6 && t.count(State::Released) == 0, "the counts by state");
}
} // namespace
int main() {
create_and_use();
nothing_prepared();
failed_job();
set_shaders_again();
release_by_count();
if (failures) return std::printf("%d checks failed\n", failures), 1;
std::printf("program_life: ok\n");
return 0;
}

View File

@@ -247,6 +247,8 @@ def cpp_checks(tools, timeout):
out.append((regmap, build_and_run(regmap, ["-O1", "-Wno-everything", "-I" + eden, "-I" + compat], [])))
ldsm = "gpu/vk/tests/ldsm_address_test.cpp" # (LDSM's row addresses kept apart from its shuffles' registers)
out.append((ldsm, build_and_run(ldsm, ["-O1", "-Wno-everything", "-I" + eden, "-I" + compat], [])))
far = "gpu/vk/tests/far_branch_test.cpp" # (programs over 1 MiB lower; branches past 8 MiB of lowered code are absolute)
out.append((far, build_and_run(far, ["-O1", "-Wno-everything", "-I" + eden, "-I" + compat], [])))
return out, ([] if cxx else ["a C++ compiler"])
@@ -273,6 +275,11 @@ def compile_all():
def main():
# ((Triforce) a check's output with a character the console's code page lacks (U+FFFD on cp1252) no longer stops the run
# and loses every later result)
for stream in (sys.stdout, sys.stderr):
if hasattr(stream, "reconfigure"):
stream.reconfigure(errors="replace")
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("names", nargs="*")
p.add_argument("--jobs", type=int, default=os.cpu_count() or 2)

View File

@@ -3,11 +3,13 @@
#include <algorithm>
#include <array>
#include <atomic>
#include <condition_variable>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <exception>
#include <memory>
#include <mutex>
@@ -19,7 +21,7 @@
#include <vector>
namespace fixture {
enum Cache { None = -1, Owner, Seen, Mine, Failure };
enum Cache { None = -1, Owner, Seen, Mine, Failure, Alias, Retire };
std::atomic<int> fail_cache{None};
std::atomic<unsigned> allocation_faults{0};
template<class T, int Tag> struct FaultAllocator : std::allocator<T> {
@@ -33,18 +35,20 @@ template<class T, int Tag> struct FaultAllocator : std::allocator<T> {
return std::allocator<T>{}.allocate(n);
}
};
template<class K, class V, int Tag> using FaultMap = std::unordered_map<K, V, std::hash<K>, std::equal_to<K>, FaultAllocator<std::pair<const K, V>, Tag>>;
template<class K, class V, int Tag, class H = std::hash<K>> using FaultMap = std::unordered_map<K, V, H, std::equal_to<K>, FaultAllocator<std::pair<const K, V>, Tag>>;
template<class K, int Tag> using FaultSet = std::unordered_set<K, std::hash<K>, std::equal_to<K>, FaultAllocator<K, Tag>>;
template<class T, int Tag> using FaultVector = std::vector<T, FaultAllocator<T, Tag>>;
/* PARAMS */
/* ENUMS */
struct {
VkDevice device{}; VkPhysicalDeviceProperties props{}; VkPhysicalDeviceFeatures features{};
bool custom_border_color = false;
} dev;
FaultMap<uint64_t, VkSampler, Owner> samplers;
std::mutex replay_mu;
struct ParLock { std::lock_guard<std::mutex> lock; ParLock() : lock(replay_mu) {} };
uint64_t generation = 1, frame_no = 1;
std::atomic<uint64_t> generation{1}; // (sampler_registrations_generation: a registration, the bias, or the book moved it)
uint64_t frame_no = 1;
bool lod_per_id = false; // (the limit cases: each id its own sampler, by its base level)
unsigned creates = 0, destroyed = 0;
VkResult create_result = VK_SUCCESS;
bool garbage = false, arm_owner_commit = false, arm_failure_commit = false, cache_off = false;
@@ -81,6 +85,15 @@ bool sampler_of(int id, nvn_samp_par* p) {
if (policy == "lod-clamp") p->lod_bias = 100, p->lod_min = -3, p->lod_max = -1;
// ((Triforce, v0.5.2) the anisotropy only where U and V repeat: a clamped one (anisotropy-clamped) reads a screen buffer
if (policy == "anisotropy") p->ws = NVN_WRAP_MODE_REPEAT, p->wt = NVN_WRAP_MODE_MIRRORED_REPEAT;
if (policy == "limit-reuse") { // (keys apart only in what no sample reaches share a sampler; 3, 5 and 6 sample otherwise)
p->minf = NVN_MIN_FILTER_NEAREST, p->magf = NVN_MAG_FILTER_NEAREST, p->lod_bias = 0;
if (id == 1) p->border[0] = 0.5f, p->border[3] = 1; // (a custom border colour no address mode clamps to)
if (id == 2) p->aniso = 4; // (anisotropy on a device without anisotropic filtering: Vulkan ignores it)
if (id == 3) p->cmp_func = 3; // (a comparison the sampler is not enabled for: kept, a driver may compare anyway)
if (id == 4) p->lod_max = 2; // (no mip filter: the base level only, whatever the range)
if (id >= 5) p->ws = NVN_WRAP_MODE_CLAMP_TO_BORDER, p->border[0] = id == 5 ? 0.5f : 0.25f, p->border[3] = 1;
}
if (lod_per_id) p->lod_bias = 0, p->lod_min = id / 64.0f;
return true;
}
const char* getenv(const char* name) {
@@ -93,9 +106,22 @@ const char* getenv(const char* name) {
return nullptr;
}
void logf(const char*, ...) {}
// (sampler reuse) The recordings' timeline: the value the GPU reached, and the one the recording being made will signal, which
// vk_replay.cpp's vk_retirement_value gives (a signal after every recording made so far)
uint64_t gpu_done = 0, next_signal = 1;
uint64_t vk_timeline_completed() { return gpu_done; }
uint64_t vk_retirement_value() { return next_signal; }
void sampler_bias_changed() { generation++; } // (vk_bank.cpp: moves sampler_registrations_generation)
unsigned limit_failures = 0; // (creations the driver refused for its maxSamplerAllocationCount, as NVIDIA's does)
std::unordered_map<VkSampler, uint64_t> last_use; // (the recording that last took each sampler, by use() below)
struct Saved;
extern std::unordered_map<VkSampler, Saved> live;
size_t live_count();
VkResult vkCreateSampler(VkDevice, const VkSamplerCreateInfo* ci, const VkAllocationCallbacks*, VkSampler* out) {
creates++;
*out = garbage ? reinterpret_cast<VkSampler>(uintptr_t(0xdead)) : VK_NULL_HANDLE;
const uint32_t most = dev.props.limits.maxSamplerAllocationCount; // (0: the other cases' device, no limit modelled)
if (most && live_count() >= most) { limit_failures++; return VK_ERROR_OUT_OF_DEVICE_MEMORY; }
if (create_result != VK_SUCCESS) {
if (arm_failure_commit) { arm_failure_commit = false; fail_cache = Failure; }
return create_result;
@@ -116,8 +142,12 @@ VkResult vkCreateSampler(VkDevice, const VkSamplerCreateInfo* ci, const VkAlloca
if (arm_owner_commit) { arm_owner_commit = false; fail_cache = Owner; }
return VK_SUCCESS;
}
size_t live_count() { return live.size(); }
void vkDestroySampler(VkDevice, VkSampler sampler, const VkAllocationCallbacks*) {
if (!sampler) return; // (Vulkan permits null destruction; a non-null error output is still undefined)
if (auto u = last_use.find(sampler); u != last_use.end()) { // (destroyed only once the GPU is past every recording that took it)
assert(u->second <= gpu_done); last_use.erase(u);
}
assert(live.erase(sampler) == 1); destroyed++; // (not undefined error output or an already-owned sampler)
}
struct { int aniso = 0; } opts; // (the Texture filtering row: off, the game's own)
@@ -191,10 +221,153 @@ void retry(const std::string& test) {
else next = get();
valid(next); assert(creates == 2 && get() == next);
}
// (sampler reuse) A recording thread that lives through a whole case, as a parallel replay's segment workers do: its own tables
// (sampler_for's by id, sampler_make's mine) stay from one recording to the next
struct Worker {
std::mutex m;
std::condition_variable cv;
std::function<void()> job;
bool busy = false, quit = false;
std::thread t{[this] {
std::unique_lock l(m);
for (;;) {
cv.wait(l, [this] { return busy || quit; });
if (quit) return;
l.unlock(); job(); l.lock();
busy = false; cv.notify_all();
}
}};
void start(std::function<void()> f) { { std::lock_guard l(m); job = std::move(f); busy = true; } cv.notify_all(); }
void join() { std::unique_lock l(m); cv.wait(l, [this] { return !busy; }); }
~Worker() { { std::lock_guard l(m); quit = true; } cv.notify_all(); t.join(); }
};
// A draw's sampler for id in the recording that will signal next_signal: checked under the replay's lock (the fake driver's tables
// change under it), its own key's (lod_per_id), and noted as used by that recording
VkSampler use(int id) {
const VkSampler s = get(id);
std::lock_guard g(replay_mu);
valid(s); assert(live.at(s).ci.minLod == id / 64.0f);
last_use[s] = next_signal;
return s;
}
// A present, the GPU `behind` recordings behind the one made next
void present(uint64_t behind = 0) {
frame_no++, next_signal++;
gpu_done = next_signal > behind + 1 ? next_signal - 1 - behind : 0;
}
// The limit cases: a driver that makes at most 80 samplers, as NVIDIA's makes about 4000 (vkCreateSampler fails past it). The
// renderer's room is 60 of them (80 less a quarter for its other samplers), retiring from 45. vkDestroySampler above checks no
// sampler goes before the GPU is past the last recording that took it. (Triforce) What is retired is what no draw took for a
// whole frame (vk_draw.cpp sampler_book): the book asks which are in use by moving the samplers' generation, and waits two
// presents for the answer
bool limit_case(const std::string& test) {
if (test == "limit") { // (300 recordings on two threads, each drawing with 10 samplers every recording uses and 20 of a window
// that moves 5 a recording: 1525 in all. The GPU 2 recordings behind)
lod_per_id = true; dev.props.limits.maxSamplerAllocationCount = 80;
Worker worker;
size_t most = 0;
for (uint64_t r = 0; r < 300; r++) {
next_signal = r + 1, gpu_done = r ? r - 1 : 0;
const auto draws = [r] {
for (int id = 0; id < 10; id++) use(id);
for (int id = 100 + 5 * (int)r; id < 120 + 5 * (int)r; id++) use(id);
};
worker.start(draws); draws(); worker.join();
most = std::max(most, live.size());
frame_no++; // (a present)
}
// (each made once: none retired while recordings still drew with it, the 10 of every recording kept throughout; none
// refused by the room or by the driver)
assert(!limit_failures && creates == 1525 && most <= 60 && destroyed == creates - live.size() && destroyed > 1400);
return true;
}
if (test == "limit-full") { // (the room filled within one frame, the GPU stopped: nothing is known to be unused yet)
lod_per_id = true; dev.props.limits.maxSamplerAllocationCount = 80;
std::vector<VkSampler> first;
for (int id = 0; id < 60; id++) first.push_back(use(id));
assert(creates == 60 && destroyed == 0 && !limit_failures);
assert(!get(60) && !get(60) && creates == 60 && !limit_failures); // (none made past the room: the draw waits, as for a failure)
// (the book asked which are in use before the room filled, in that same frame, when all of them were; two presents on it
// asks again, the draws going on with 30 to 59)
for (int k = 0; k < 3; k++) {
present(8);
assert(!get(60) && creates == 60 && destroyed == 0);
for (int id = 30; id < 60; id++) assert(use(id) == first[id]);
}
present(8);
// (two presents after that, 0 to 29 were not drawn with: 16 of them retired, the least recently resolved, but the GPU has them still)
assert(!get(60) && creates == 60 && destroyed == 0 && live.size() == 60);
present(0); // (the GPU past every recording made)
use(60);
assert(destroyed == 16 && creates == 61 && live.size() == 45 && !limit_failures);
for (int id = 30; id < 60; id++) assert(use(id) == first[id]); // (those drawn with were never retired)
assert(use(29) == first[29] && creates == 61); // (the 16 retired were 0 to 15)
assert(use(0) != first[0] && creates == 62); // (a retired one's key made anew)
return true;
}
if (test == "limit-reuse") { // (keys apart only in what no sample reaches share one sampler; the others do not)
policy = test; dev.features.samplerAnisotropy = VK_FALSE;
const VkSampler s0 = get(0); valid(s0);
assert(get(1) == s0 && get(2) == s0 && get(4) == s0 && creates == 1);
const VkSampler s3 = get(3), s5 = get(5), s6 = get(6);
valid(s3); valid(s5); valid(s6);
assert(s3 != s0 && s5 != s0 && s6 != s0 && s5 != s6 && creates == 4 && live.size() == 4);
assert(!live.at(s3).ci.compareEnable && live.at(s3).ci.compareOp == VK_COMPARE_OP_EQUAL);
assert(live.at(s5).custom && live.at(s5).border[0] == 0.5f && live.at(s6).border[0] == 0.25f);
return true;
}
if (test == "limit-alias-commit") { // (the keys' table could not take a key: its sampler is found again by what it samples)
fail_cache = Alias; const VkSampler s = get(); valid(s);
assert(allocation_faults == 1 && get() == s && creates == 1 && destroyed == 0);
return true;
}
if (test == "limit-retire-commit") { // (no room to note a retirement: that sampler stays made, none lost or destroyed early)
lod_per_id = true; dev.props.limits.maxSamplerAllocationCount = 80;
for (int id = 0; id < 45; id++) use(id); // (the book's first question on the way, when all of them were just made)
present(); use(45);
present(); for (int id = 20; id < 46; id++) use(id);
use(46); // (past the retiring point and none known unused: the book asks again; made meanwhile)
present(); for (int id = 20; id < 47; id++) use(id);
present(); for (int id = 20; id < 47; id++) use(id);
assert(creates == 47 && destroyed == 0 && live.size() == 47);
fail_cache = Retire; use(47); // (0 to 19 were not drawn with for a frame; the first retirement cannot be noted)
assert(allocation_faults == 1 && creates == 48 && destroyed == 0 && live.size() == 48);
use(48); assert(creates == 49 && destroyed == 0 && live.size() == 49); // (back to 44 made, then this one: 4 retired, the GPU's still)
present(); use(49); // (the GPU past them: destroyed; one more retired for this one)
assert(destroyed == 4 && creates == 50 && live.size() == 45 + 1 && !limit_failures);
return true;
}
if (test == "limit-held") { // (Triforce) what a draw may still hold when its sampler is retired: all of it follows the generation
lod_per_id = true; dev.props.limits.maxSamplerAllocationCount = 80;
const VkSampler old0 = use(0);
for (int id = 1; id < 45; id++) use(id); // (the book's first question on the way)
present(8); for (int id = 1; id < 45; id++) use(id);
present(8); for (int id = 1; id < 45; id++) use(id);
use(45); // (at the retiring point, and every sampler resolved in or after the frame of that question: asked again)
const uint64_t g0 = sampler_registrations_generation();
present(8); for (int id = 1; id < 46; id++) use(id);
present(8); for (int id = 1; id < 46; id++) use(id);
assert(creates == 46 && sampler_registrations_generation() == g0);
use(46); // (0 was not drawn with for a frame: retired, though the GPU has not passed its recordings; 1 to 45 stay)
assert(live.count(old0) && destroyed == 0 && creates == 47);
// (a kept descriptor or a thread's table made before stands on a generation that is gone: kept_texture's now.samp,
// sampler_for's e.gen, sampler_make's mine_gen)
assert(sampler_registrations_generation() != g0);
const VkSampler new0 = use(0);
assert(new0 != old0 && live.count(old0) && creates == 48); // (made anew, another handle, while the old one is the GPU's)
for (int id = 1; id < 47; id++) use(id);
assert(creates == 48); // (none of those drawn with was retired)
present(0); use(47); // (the GPU past every recording that may hold it: destroyed)
assert(!live.count(old0) && live.count(new0) && destroyed >= 1);
return true;
}
return false;
}
void run(const std::string& test) {
cache_off = route == "cache-off";
dev.props.limits.maxSamplerLodBias = 16; dev.props.limits.maxSamplerAnisotropy = 8;
dev.features.samplerAnisotropy = VK_TRUE; dev.custom_border_color = true;
if (limit_case(test)) return;
if (test.find("descriptor-") == 0) {
descriptor_policy = test;
recording.pool = make_pool(); // A live recording already owns its initial pool before binding.

View File

@@ -55,6 +55,11 @@ static volatile LONG ask_next; /* (what a row asked: the worker takes it) */
2 no frame is ever shown */
static int shot_mode, shot_asked, shot_polls, shot_dropped;
static char shot_file[MAX_PATH + 64];
/* ((Triforce) 11-24) the menu's settings changed from the defaults (HOS_OPT_BUG_SETTINGS), a byte a question; none from a
renderer that has not the text (the "nopicture" capture's: an older renderer) */
static const char settings_text[] = "Field of view: 110% (default: 100%)\nText size: 125% (default: Off)\n";
static const char *settings_at;
static int settings_none;
int rx_option(int id, int otherwise) {
if (id == HOS_OPT_SHARE_ASK) return (int)InterlockedExchange(&ask_next, 0);
if (id == HOS_OPT_BUG_SHOT) {
@@ -65,9 +70,11 @@ int rx_option(int id, int otherwise) {
if (f) fputs("the frame's picture", f), fclose(f);
return 2;
}
if (id == HOS_OPT_BUG_SETTINGS) return settings_at && *settings_at ? (unsigned char)*settings_at++ : (settings_at = NULL, 0);
return id == 1 ? 0 : otherwise;
}
void rx_option_set(int id, int value) {
if (id == HOS_OPT_BUG_SETTINGS && value) settings_at = settings_none ? NULL : settings_text;
if (id == HOS_OPT_BUG_SHOT) {
if (value) shot_asked++, shot_polls = 0;
else shot_dropped++;
@@ -99,6 +106,7 @@ void hos_oot_live_crawl(const char *line) {
}
#include "../host/bug_capture.c"
#include "../host/log_redact.c" /* ((Triforce) 11-24: the log's copy leaves the home folder and the user's name out, as it is) */
/* ---- a save of three files, one in a slot folder, all written with one tag (as tests/test_save_tx.py's) ---- */
static void put(const char *dir, const char *name, const char *text) {
@@ -412,6 +420,7 @@ int main(int argc, char **argv) {
snprintf(shot_file, sizeof shot_file, "%s\\captures\\frame-pending.png", game);
shot_mode = !strcmp(mode, "nopicture") ? 1 : !strcmp(mode, "noframes") ? 2 : 0;
f8_bound = !strcmp(mode, "bound");
settings_none = !strcmp(mode, "nopicture");
link_in_play = strcmp(mode, "title") != 0;
CHECK(game_mount() != NULL);
for (int i = 0; i < 14; i++) { /* (1.4 s of play at 60 frames a second, as the worker counts it) */

View File

@@ -118,15 +118,15 @@ static int game_menu_open;
static volatile LONG64 game_menu_seen_ns;
static volatile LONG gm_wheel, play_wheel;
static volatile LONG64 play_wheel_ns;
static LONG gm_mx, gm_my;
static LONG64 InterlockedCompareExchange64(volatile LONG64 *target, LONG64 value, LONG64 compare) {
const LONG64 was = *target;
if (was == compare) *target = value;
return was;
}
static int64_t hos_now_ns(void) { return 0; }
static void gm_mouse_used(void) { unexpected(); }
static int gm_cursor_shown(void) { unexpected(); return 1; }
static void gm_mouse_moved(HWND w) { (void)w; unexpected(); }
/* (the timer asks in play too: a cursor shown is left alone) */
static int gm_cursor_shown(void) { return 1; }
static void game_menu_press(LPARAM lp, LONG bit) { (void)lp; (void)bit; unexpected(); }
static void menus_mouse(HWND w, int insert_open, int game_open) { (void)w; (void)insert_open; (void)game_open; unexpected(); }
static void gm_cursor_off(HWND w) { (void)w; unexpected(); }

View File

@@ -0,0 +1,93 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// The simulated-turf capacity policy without Vulkan: demand grows only the saturated list, allocation failure leaves the
// installed cap alone, and sustained lower demand observes the configured floor.
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include "sim_turf_capacity.h"
using mkwvk::sim_turf_capacity::Policy;
using mkwvk::sim_turf_capacity::mirror_span;
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
int main() {
// The stock-compatible copy keeps forward lists at their start and reverse lists aligned at their occupied end.
CHECK((mirror_span(200, 100, 8, false) == mkwvk::sim_turf_capacity::MirrorSpan{0, 0, 800}));
CHECK((mirror_span(200, 100, 8, true) == mkwvk::sim_turf_capacity::MirrorSpan{800, 0, 800}));
CHECK((mirror_span(50, 100, 8, true) == mkwvk::sim_turf_capacity::MirrorSpan{0, 400, 400}));
CHECK((mirror_span(0, 100, 8, true) == mkwvk::sim_turf_capacity::MirrorSpan{}));
Policy blades{143360, 64, 1048576, 143360};
Policy pool{138240, 32, 786432, 138240};
CHECK(blades.capacity() == 143360 && blades.target() == 143360);
CHECK(pool.capacity() == 138240 && pool.target() == 138240);
CHECK(!blades.observe(90000, 1));
CHECK(!pool.observe(80000, 1));
// Only the saturated blade list asks to grow. Its target includes 25% headroom and is group-aligned.
CHECK(blades.observe(143360, 2));
CHECK(blades.target() == 179200);
CHECK(pool.target() == 138240);
// A failed allocation does not lie to the shader about the installed capacity; the next sample can retry.
blades.install_failed();
CHECK(blades.capacity() == 143360);
// The adaptive floor still starts safely at stock. Sustained demand shrinks to its aligned target with headroom;
// zero demand can release every record, and the next reservation grows it again.
Policy lean{143360, 64, 1048576, 0};
CHECK(lean.capacity() == 143360);
CHECK(!lean.observe(20000, 1));
CHECK(lean.observe(20000, 602));
CHECK(lean.target() == 25024);
lean.installed();
CHECK(!lean.observe(0, 700));
CHECK(lean.observe(0, 1301));
CHECK(lean.target() == 0);
lean.installed();
CHECK(lean.observe(1, 1302));
CHECK(lean.target() == 64);
// Shrinking uses the highest demand in the whole quiet window, not an unusually low final sample.
Policy variable{143360, 64, 1048576, 0};
CHECK(!variable.observe(20000, 1));
CHECK(!variable.observe(30000, 300));
CHECK(variable.observe(10000, 602));
CHECK(variable.target() == 37504);
CHECK(blades.observe(143360, 3));
blades.installed();
CHECK(blades.capacity() == 179200);
CHECK(!blades.observe(150000, 4));
// A transient low sample does not shrink. Sustained quiet can, but never below the game's stock cap.
CHECK(!blades.observe(20000, 300));
CHECK(blades.observe(20000, 901));
CHECK(blades.target() == 143360);
blades.installed();
CHECK(blades.capacity() == 143360);
// A pathological counter is bounded by what the device/buffer representation permits.
CHECK(pool.observe(UINT32_MAX, 700));
CHECK(pool.target() == 786432);
// ((Triforce) a reader's bound, the mesh fallback's records area: a list past it goes back to it at the next resize, a
// growth stops there, and nothing goes under the game's own size)
Policy bounded{138240, 32, 786432, 138240};
CHECK(bounded.observe(300000, 1));
bounded.installed();
CHECK(bounded.capacity() == 375008);
bounded.limit(200000);
CHECK(bounded.maximum() == 200000);
CHECK(bounded.target() == 200000 && bounded.capacity() == 375008);
bounded.installed();
CHECK(!bounded.observe(300000, 2));
CHECK(bounded.capacity() == 200000);
bounded.limit(1000);
CHECK(bounded.maximum() == 138240 && bounded.target() == 138240);
std::puts("PASS: adaptive simulated-turf capacity policy");
}

356
tests/sim_turf_pools_ir.cpp Normal file
View File

@@ -0,0 +1,356 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Simulated turf's lists made larger (ir_opt/sim_turf_pool_pass.h) on synthetic programs shaped as the game's: the blade list's producer
// (d5a9475f2790532e), the pools' producer (3de6d86ec7e6720e) and a mesh program drawing a pool. Each is checked made larger: its
// caps derived from what the bound buffers hold, its record accesses moved to a private descriptor (shader_info.h IsSimTurfStorage),
// placed before the tables, the headers left where the game has them; pool 2's records written at the same place in the new
// buffer as in the game's (the addresses are worked out here, before and after). Programs that differ a little are left exactly
// as they are. And the switch, through vk_shader.cpp's own sim_turf_pools (cut out by tests/test_sim_turf_pools.py): `on` runs the
// pass, `off` (RX_VK_SIM_TURF_POOLS=0) leaves every program as it is.
//
// sim_turf_pools_ir on|off; tests/test_sim_turf_pools.py builds and runs it.
#include <atomic>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <string>
#include <vector>
#include "shader_recompiler/frontend/ir/program.h"
#include "shader_recompiler/object_pool.h"
#include "shader_recompiler/ir_opt/sim_turf_pool_pass.h"
using namespace Shader;
namespace GP = Shader::Optimization;
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
// (stand-ins for what vk_shader.cpp's sim_turf_pools calls besides the pass)
static std::vector<std::string> logged;
static int dce_runs = 0;
static void sim_turf_log(const char* fmt, ...) {
char line[512];
va_list a;
va_start(a, fmt);
std::vsnprintf(line, sizeof line, fmt, a);
va_end(a);
logged.emplace_back(line);
}
namespace Shader::Optimization {
void DeadCodeEliminationPass(IR::Program&) { dce_runs++; }
}
#define logf sim_turf_log
#include "sim_turf_pools_cut.inc" // vk_shader.cpp: sim_turf_pools_on, sim_turf_pools
#undef logf
constexpr u32 kMask = 0xffffffc0u;
// (the constant bank 0 words the programs read: the lists' addresses, low and high halves)
const std::map<u32, u32> kC0 = {{0x40, 0x10000000u}, {0x44, 0x2u}, {0x50, 0x10400000u}, {0x54, 0x2u},
{0x60, 0x20000000u}, {0x64, 0x3u}, {0x70, 0x30000000u}, {0x74, 0x3u}};
constexpr u32 kCount = 5; // what every atomic and every other unknown returns, for the addresses worked out below
constexpr u32 kBladeRuntimeCap = 200000, kBladeInputRuntimeCap = 300000;
constexpr u32 kPool2RuntimeCap = 250000, kPool1RuntimeCap = 180000;
struct Prog {
ObjectPool<IR::Inst> insts{512};
ObjectPool<IR::Block> blocks{4};
IR::Program program;
IR::Block* block = nullptr;
Prog(Stage stage, std::vector<StorageBufferDescriptor> descs) {
block = blocks.Create(insts);
program.blocks.push_back(block);
program.post_order_blocks.push_back(block);
program.stage = stage;
for (const auto& d : descs) program.info.storage_buffers_descriptors.push_back(d);
}
IR::Inst* E(IR::Opcode op, std::initializer_list<IR::Value> args) { return &*block->PrependNewInst(block->end(), op, args); }
static IR::Value V(u32 v) { return IR::Value{v}; }
static IR::Value V(IR::Inst* i) { return IR::Value{i}; }
IR::Inst* Cbuf(u32 off) { return E(IR::Opcode::GetCbufU32, {V(0u), V(off)}); }
IR::Inst* Base(u32 off) { return E(IR::Opcode::BitwiseAnd32, {V(Cbuf(off)), V(kMask)}); }
/// A header access's offset, as the storage buffer pass writes it: ISub32(c0 word + at, c0 word & mask)
IR::Inst* Header(u32 off, u32 at) {
IR::Inst* x = Cbuf(off);
if (at) x = E(IR::Opcode::IAdd32, {V(x), V(at)});
return E(IR::Opcode::ISub32, {V(x), V(Base(off))});
}
/// A record's: ISub32(c0 word + index (+ extra), c0 word & mask)
IR::Inst* Record(u32 off, IR::Inst* index, u32 extra) {
IR::Inst* x = E(IR::Opcode::IAdd32, {V(Cbuf(off)), V(index)});
if (extra) x = E(IR::Opcode::IAdd32, {V(x), V(extra)});
return E(IR::Opcode::ISub32, {V(x), V(Base(off))});
}
std::vector<IR::Inst*> All(IR::Opcode op) const {
std::vector<IR::Inst*> r;
for (IR::Inst& i : block->Instructions())
if (i.GetOpcode() == op) r.push_back(&i);
return r;
}
const std::vector<StorageBufferDescriptor> Descs() const {
return {program.info.storage_buffers_descriptors.begin(), program.info.storage_buffers_descriptors.end()};
}
};
/// The value an instruction computes, for the few opcodes these programs use (an atomic or a load: kCount)
u64 Eval(IR::Value v) {
v = v.Resolve();
if (v.IsImmediate()) return v.Type() == IR::Type::U64 ? v.U64() : v.U32();
const IR::Inst* i = v.InstRecursive();
const auto a = [i](size_t n) { return Eval(i->Arg(n)); };
switch (i->GetOpcode()) {
case IR::Opcode::GetCbufU32: return a(0) == 0 ? kC0.at(static_cast<u32>(a(1))) : kCount;
case IR::Opcode::GetCbufU32x2: return kC0.at(static_cast<u32>(a(1))) | u64{kC0.at(static_cast<u32>(a(1)) + 4)} << 32;
case IR::Opcode::CompositeExtractU32x2: return a(1) == 0 ? a(0) & 0xffffffffu : a(0) >> 32;
case IR::Opcode::CompositeConstructU32x2: return (a(0) & 0xffffffffu) | (a(1) << 32);
case IR::Opcode::PackUint2x32: return a(0);
case IR::Opcode::IAdd32: return (a(0) + a(1)) & 0xffffffffu;
case IR::Opcode::ISub32: return (a(0) - a(1)) & 0xffffffffu;
case IR::Opcode::IMul32: return (a(0) * a(1)) & 0xffffffffu;
case IR::Opcode::BitwiseAnd32: return a(0) & a(1);
case IR::Opcode::UMin32: return std::min(a(0), a(1));
case IR::Opcode::UMax32: return std::max(a(0), a(1));
case IR::Opcode::UDiv32: return a(1) ? a(0) / a(1) : 0;
case IR::Opcode::StorageBufferLength:
switch (a(0)) {
case 1: return 64 + kPool2RuntimeCap * 48; // a mesh reader's private pool
case 2: return 64 + kBladeRuntimeCap * 8; // the blade producer's private list
case 3: return 64 + kBladeInputRuntimeCap * 8; // the pool producer's private input
case 4: return 64 + kPool2RuntimeCap * 48; // the pool producer's first private output
case 5: return 64 + kPool1RuntimeCap * 48; // the pool producer's second private output
default: return 0;
}
case IR::Opcode::IAdd64: return a(0) + a(1);
default: return kCount;
}
}
bool IsPrivate(const StorageBufferDescriptor& d, u32 orig, bool pool, bool creator) {
return IsSimTurfStorage(d) && SimTurfStorageOrig(d) == orig && ((d.cbuf_offset & kSimTurfStoragePool) != 0) == pool &&
((d.cbuf_offset & kSimTurfStorageCreator) != 0) == creator && d.is_written == creator;
}
// ---- d5a9: the blade list's producer ----
enum class Blade { Game, ThirdWrite, OneGuard, CountNotCapped, TableUsed };
struct BladeProg : Prog {
IR::Inst *cap, *umax, *bump, *load, *g1, *g2, *w1, *w2;
explicit BladeProg(Blade s)
: Prog(Stage::Compute, {{0, 0x40, 1, true}, {0, 0x50, 1, false}, {0, 0x100, 4, false}}) {
using O = IR::Opcode;
IR::Inst* demand = E(O::GetCbufU32, {V(3u), V(0x180u)});
cap = E(O::UMin32, {V(demand), V(GP::kSimTurfBladeCap)});
IR::Inst* groups = E(O::IAdd32, {V(s == Blade::CountNotCapped ? demand : cap), V(63u)});
if (s == Blade::CountNotCapped) E(O::IAdd32, {V(cap), V(1u)});
umax = E(O::StorageAtomicUMax32, {V(0u), V(Header(0x40, 0)), V(groups)});
bump = E(O::StorageAtomicIAdd32, {V(0u), V(Header(0x40, 4)), V(1u)});
load = E(O::LoadStorage32, {V(1u), V(Record(0x50, bump, 0)), });
g1 = E(O::Identity, {V(GP::kSimTurfBladeCap - 1)});
IR::Inst* i1 = E(O::ISub32, {V(g1), V(bump)});
w1 = E(O::WriteStorage32, {V(0u), V(Record(0x40, i1, 0)), V(load)});
g2 = s == Blade::OneGuard ? nullptr : E(O::Identity, {V(GP::kSimTurfBladeCap - 1)});
IR::Inst* i2 = E(O::ISub32, {V(g2 ? g2 : g1), V(bump)});
w2 = E(O::WriteStorage32, {V(0u), V(Record(0x40, i2, 4)), V(load)});
if (s == Blade::ThirdWrite) E(O::WriteStorage32, {V(0u), V(Record(0x40, i2, 8)), V(load)});
if (s == Blade::TableUsed) E(O::LoadStorage32, {V(2u), V(Record(0x100, bump, 0))});
}
bool Untouched() const {
return Descs().size() == 3 && cap->Arg(1).U32() == GP::kSimTurfBladeCap && g1->Arg(0).U32() == GP::kSimTurfBladeCap - 1 &&
(!g2 || g2->Arg(0).U32() == GP::kSimTurfBladeCap - 1) && w1->Arg(0).U32() == 0 && w2->Arg(0).U32() == 0;
}
bool MadeLarger() const {
const auto d = Descs();
return d.size() == 4 && IsPrivate(d[2], 0x40, false, true) && d[3].cbuf_offset == 0x100 && d[3].count == 4 &&
Eval(cap->Arg(1)) == kBladeRuntimeCap && Eval(g1->Arg(0)) == kBladeRuntimeCap - 1 &&
Eval(g2->Arg(0)) == kBladeRuntimeCap - 1 && All(IR::Opcode::StorageBufferLength).size() == 3 &&
w1->Arg(0).U32() == 2 && w2->Arg(0).U32() == 2 &&
umax->Arg(0).U32() == 0 && bump->Arg(0).U32() == 0 && load->Arg(0).U32() == 1;
}
};
// ---- 3de6: the pools' producer ----
enum class Pool { Game, NineWrites, GuardAfter, SharedCap, BladeHeaderTwice };
struct PoolProg : Prog {
IR::Inst *count_in, *blade_a, *blade_b, *in_guard, *cap2, *cap1, *g0, *g1;
std::vector<u64> pool2_addresses; // the game's addresses of pool 2's records, in program order
explicit PoolProg(Pool s) : Prog(Stage::Compute, {{0, 0x40, 1, false}, {0, 0x60, 1, true}, {0, 0x70, 1, true}}) {
using O = IR::Opcode;
count_in = E(O::LoadStorage32, {V(0u), V(Header(0x40, 12))});
if (s == Pool::BladeHeaderTwice) E(O::LoadStorage32, {V(0u), V(Header(0x40, 12))});
in_guard = E(O::Identity, {V(GP::kSimTurfBladeCap - 1)});
IR::Inst* i = E(O::ISub32, {V(in_guard), V(E(O::GetCbufU32, {V(3u), V(0u)}))});
blade_a = E(O::LoadStorage32, {V(0u), V(Record(0x40, i, 0))});
blade_b = E(O::LoadStorage32, {V(0u), V(Record(0x40, i, 4))});
IR::Inst* n2 = E(O::StorageAtomicIAdd32, {V(1u), V(Header(0x60, 4)), V(1u)});
cap2 = E(O::UMin32, {V(n2), V(GP::kSimTurfPoolCap)});
E(O::StorageAtomicUMax32, {V(1u), V(Header(0x60, 0)), V(E(O::IAdd32, {V(cap2), V(31u)}))});
IR::Inst* n1 = E(O::StorageAtomicIAdd32, {V(2u), V(Header(0x70, 4)), V(1u)});
cap1 = E(O::UMin32, {V(n1), V(GP::kSimTurfPoolCap)});
E(O::StorageAtomicUMax32, {V(2u), V(Header(0x70, 0)), V(E(O::IAdd32, {V(s == Pool::SharedCap ? cap2 : cap1), V(31u)}))});
if (s != Pool::GuardAfter) g0 = E(O::Identity, {V(GP::kSimTurfPoolCap)});
// pool 2's ten records: 48 bytes each, the slot from the counter; two through IAdd64(address), one 64-bit
IR::Inst* slot2 = E(O::IMul32, {V(n2), V(48u)});
for (u32 k = 0; k < (s == Pool::NineWrites ? 9u : 10u); k++) {
IR::Inst* at = E(O::IAdd32, {V(slot2), V(k < 8 ? 4 * k : 0u)});
IR::Inst* lo;
if (k == 1) lo = E(O::IAdd32, {V(E(O::CompositeExtractU32x2, {V(E(O::GetCbufU32x2, {V(0u), V(0x60u)})), V(0u)})), V(at)});
else if (k == 5) lo = E(O::IAdd32, {V(at), V(Cbuf(0x60))});
else lo = E(O::IAdd32, {V(Cbuf(0x60)), V(at)});
IR::Inst* a = E(O::PackUint2x32, {V(E(O::CompositeConstructU32x2, {V(lo), V(Cbuf(0x64))}))});
if (k >= 8) a = E(O::IAdd64, {V(a), IR::Value{u64{8 + 4 * (k - 8)}}});
if (k == 3) E(O::WriteGlobal64, {V(a), V(E(O::CompositeConstructU32x2, {V(blade_a), V(blade_b)}))});
else E(O::WriteGlobal32, {V(a), V(k & 1 ? blade_b : blade_a)});
pool2_addresses.push_back(Eval(V(a)));
if (s == Pool::GuardAfter && k == 0) g0 = E(O::Identity, {V(GP::kSimTurfPoolCap)});
}
g1 = E(O::Identity, {V(GP::kSimTurfPoolCap)});
// pool 1's ten, after its guard
IR::Inst* slot1 = E(O::IMul32, {V(E(O::ISub32, {V(g1), V(n1)})), V(48u)});
for (u32 k = 0; k < 10; k++) {
IR::Inst* lo = E(O::IAdd32, {V(Cbuf(0x70)), V(E(O::IAdd32, {V(slot1), V(4 * k)}))});
E(O::WriteGlobal32, {V(E(O::PackUint2x32, {V(E(O::CompositeConstructU32x2, {V(lo), V(Cbuf(0x74))}))})), V(blade_a)});
}
}
int GlobalWrites(u32 base) {
int n = 0;
for (IR::Opcode op : {IR::Opcode::WriteGlobal32, IR::Opcode::WriteGlobal64})
for (IR::Inst* w : All(op))
if ((Eval(w->Arg(0)) >> 32) == kC0.at(base + 4) && (Eval(w->Arg(0)) & 0xf0000000u) == kC0.at(base)) n++;
return n;
}
bool Untouched() {
return Descs().size() == 3 && cap2->Arg(1).U32() == GP::kSimTurfPoolCap && cap1->Arg(1).U32() == GP::kSimTurfPoolCap &&
g0->Arg(0).U32() == GP::kSimTurfPoolCap && g1->Arg(0).U32() == GP::kSimTurfPoolCap &&
in_guard->Arg(0).U32() == GP::kSimTurfBladeCap - 1 && blade_a->Arg(0).U32() == 0 && blade_b->Arg(0).U32() == 0 &&
GlobalWrites(0x60) == static_cast<int>(pool2_addresses.size()) && GlobalWrites(0x70) == 10 &&
All(IR::Opcode::WriteStorage32).empty() && All(IR::Opcode::WriteStorage64).empty();
}
bool MadeLarger() {
const auto d = Descs();
CHECK(d.size() == 6 && IsPrivate(d[3], 0x40, false, false) && IsPrivate(d[4], 0x60, true, true) &&
IsPrivate(d[5], 0x70, true, true));
CHECK(blade_a->Arg(0).U32() == 3 && blade_b->Arg(0).U32() == 3 && count_in->Arg(0).U32() == 0);
CHECK(Eval(cap2->Arg(1)) == kPool2RuntimeCap && Eval(cap1->Arg(1)) == kPool1RuntimeCap);
CHECK(Eval(g0->Arg(0)) == kPool2RuntimeCap && Eval(g1->Arg(0)) == kPool1RuntimeCap);
CHECK(Eval(in_guard->Arg(0)) == kBladeInputRuntimeCap - 1);
CHECK(All(IR::Opcode::StorageBufferLength).size() == 5);
CHECK(GlobalWrites(0x60) == 0 && GlobalWrites(0x70) == 0);
// pool 2's records in the private pool, each at its place in the game's: its address less the pool's base
std::vector<u64> written;
size_t wide = 0;
for (IR::Inst& w : block->Instructions()) {
const IR::Opcode op = w.GetOpcode();
if (op != IR::Opcode::WriteStorage32 && op != IR::Opcode::WriteStorage64) continue;
CHECK(w.Arg(0).U32() == 4 || w.Arg(0).U32() == 5);
const u32 base = w.Arg(0).U32() == 4 ? 0x60 : 0x70;
written.push_back(Eval(w.Arg(1)) + (u64{kC0.at(base + 4)} << 32 | kC0.at(base)));
wide += op == IR::Opcode::WriteStorage64;
}
CHECK(std::equal(pool2_addresses.begin(), pool2_addresses.end(), written.begin()));
CHECK(written.size() == 20 && wide == 1);
return true;
}
};
// ---- a mesh program drawing a pool ----
enum class Reader { Game, TwoGuards, Writes, NotMesh };
struct ReaderProg : Prog {
IR::Inst *count, *guard, *r1, *r2;
explicit ReaderProg(Reader s) : Prog(s == Reader::NotMesh ? Stage::Fragment : Stage::Mesh, {{0, 0x60, 1, false}}) {
using O = IR::Opcode;
count = E(O::LoadStorage32, {V(0u), V(Header(0x60, 12))});
guard = E(O::Identity, {V(GP::kSimTurfPoolCap)});
if (s == Reader::TwoGuards) E(O::Identity, {V(GP::kSimTurfPoolCap)});
IR::Inst* slot = E(O::IMul32, {V(E(O::ISub32, {V(guard), V(count)})), V(48u)});
r1 = E(O::LoadStorage32, {V(0u), V(Record(0x60, slot, 0))});
r2 = E(O::LoadStorage64, {V(0u), V(Record(0x60, slot, 16))});
if (s == Reader::Writes) E(O::WriteStorage32, {V(0u), V(Record(0x60, slot, 4)), V(r1)});
}
bool Untouched() const {
return Descs().size() == 1 && guard->Arg(0).U32() == GP::kSimTurfPoolCap && r1->Arg(0).U32() == 0 && r2->Arg(0).U32() == 0;
}
bool MadeLarger() const {
const auto d = Descs();
return d.size() == 2 && IsPrivate(d[1], 0x60, true, false) && Eval(guard->Arg(0)) == kPool2RuntimeCap &&
All(IR::Opcode::StorageBufferLength).size() == 1 &&
r1->Arg(0).U32() == 1 && r2->Arg(0).U32() == 1 && count->Arg(0).U32() == 0;
}
};
void ThePass() {
{ // d5a9
BladeProg p{Blade::Game};
CHECK(GP::SimTurfPools(p.program, GP::kSimTurfBladeKey) == "blade list made larger");
CHECK(p.MadeLarger());
}
for (const Blade s : {Blade::ThirdWrite, Blade::OneGuard, Blade::CountNotCapped, Blade::TableUsed}) {
BladeProg p{s};
CHECK(GP::SimTurfPools(p.program, GP::kSimTurfBladeKey).starts_with("blade list left as it is: "));
CHECK(p.Untouched());
}
{ // another program of the same shape: not simulated turf's
BladeProg p{Blade::Game};
CHECK(GP::SimTurfPools(p.program, GP::kSimTurfBladeKey ^ 1).empty());
CHECK(p.Untouched());
}
{ // the other cached phase-0 key uses the same pass
BladeProg p{Blade::Game};
CHECK(GP::SimTurfPools(p.program, 0xbdcc9ddf7ca7cabdULL) == "blade list made larger");
CHECK(p.MadeLarger());
}
{ // 3de6
PoolProg p{Pool::Game};
CHECK(p.Untouched());
CHECK(GP::SimTurfPools(p.program, GP::kSimTurfPoolKey) == "both pools made larger");
CHECK(p.MadeLarger());
}
for (const u64 key : {0x64978274654e224cULL, 0x9a6fe9d7a7ce2007ULL, 0xb0cc49ac253104ccULL}) {
PoolProg p{Pool::Game};
CHECK(GP::SimTurfPools(p.program, key) == "both pools made larger");
CHECK(p.MadeLarger());
}
for (const Pool s : {Pool::NineWrites, Pool::GuardAfter, Pool::SharedCap, Pool::BladeHeaderTwice}) {
PoolProg p{s};
CHECK(GP::SimTurfPools(p.program, GP::kSimTurfPoolKey).starts_with("pools left as they are: "));
CHECK(p.Untouched());
}
{ // the mesh reader
ReaderProg p{Reader::Game};
CHECK(GP::SimTurfPools(p.program, 0x1234) == "pool reader made larger");
CHECK(p.MadeLarger());
}
for (const Reader s : {Reader::TwoGuards, Reader::Writes, Reader::NotMesh}) {
ReaderProg p{s};
CHECK(GP::SimTurfPools(p.program, 0x1234).empty());
CHECK(p.Untouched());
}
std::printf("pass: both phase-0 keys, all four phase-1 keys and the mesh reader use runtime capacities; 11 programs that differ left as they are\n");
}
/// vk_shader.cpp's sim_turf_pools, the way translation calls it: on, the three made larger and logged; off, all left as they are
void TheSwitch(bool on) {
BladeProg blade{Blade::Game};
PoolProg pool{Pool::Game};
ReaderProg reader{Reader::Game};
sim_turf_pools(blade.program, GP::kSimTurfBladeKey);
sim_turf_pools(pool.program, GP::kSimTurfPoolKey);
sim_turf_pools(reader.program, 0x1234);
CHECK(sim_turf_pools_on() == on);
if (on) {
CHECK(blade.MadeLarger() && pool.MadeLarger() && reader.MadeLarger());
CHECK(dce_runs == 3 && logged.size() == 3);
CHECK(logged[0] == "vk: simulated turf: program d5a9475f2790532e: blade list made larger");
CHECK(logged[1] == "vk: simulated turf: program 3de6d86ec7e6720e: both pools made larger");
CHECK(logged[2] == "vk: simulated turf: program 0000000000001234: pool reader made larger");
} else {
CHECK(blade.Untouched() && pool.Untouched() && reader.Untouched());
CHECK(dce_runs == 0 && logged.empty());
}
std::printf("switch %s: %s\n", on ? "on" : "off (RX_VK_SIM_TURF_POOLS=0)", on ? "made larger, logged" : "left as they are");
}
int main(int argc, char** argv) {
const std::string mode = argc > 1 ? argv[1] : "";
CHECK(mode == "on" || mode == "off");
ThePass();
TheSwitch(mode == "on");
std::printf("PASS\n");
return 0;
}

View File

@@ -0,0 +1,180 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// The per-area simulated-turf settings (gpu/vk/sim_turf_settings.h) over a sparse stand-in for the guest window, without Vulkan
// or the game. ((Triforce) The area comes from the host's word, a byte at a time (HOS_OPT_SIM_TURF_AREA_TEXT), and the file is
// written whole by file_whole.h, as the renderer writes it.)
#define NOMINMAX
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/mman.h>
#include <unistd.h>
#endif
#include <array>
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <string>
#include "vk_api.h"
#include "file_whole.h"
namespace mkwvk {
static uint8_t* memory;
static int64_t clock_ns;
static std::filesystem::path fixture;
static uint8_t* mock_base() { return memory; }
static uint64_t mock_size() { return 0x85000000ull; }
static int64_t mock_now() { return clock_ns; }
static MkwVkHost mock;
const MkwVkHost* host = &mock;
void logf(const char*, ...) {}
} // namespace mkwvk
#include "sim_turf_settings.h"
namespace mkwvk::sim_turf_settings {
bool write_config(const std::string& path, const std::string& text) { return file_writers::write_whole(path, text); }
}
namespace {
using namespace mkwvk;
using namespace mkwvk::sim_turf_settings;
template<class T> void put(uint64_t at, T value) { std::memcpy(memory + at, &value, sizeof value); }
template<class T> T get(uint64_t at) {
T value{};
assert(read(at, value));
return value;
}
void scene_data(uint64_t address, float start, float density, int blades, float far_power) {
put(address, vtable);
put(address + 8, address + 1);
put(address + 0x7c, start);
put(address + 0x68, density);
put(address + 0x70, blades);
put(address + 0x6c, far_power);
for (const auto& field : fields) put(address + field.flag, uint8_t{1});
}
void load(uint64_t address, const char* area) {
put<uint64_t>(0x14150, address);
for (const char* c = area; *c; ++c) area_byte((unsigned char)*c); // (the host's word: HOS_OPT_SIM_TURF_AREA_TEXT, then the end)
area_end(1);
for (int i = 0; i < 5; ++i) {
clock_ns += 250'000'000;
tick(clock_ns);
}
assert(ready);
}
std::string config_text() {
std::ifstream in(config_file);
return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
}
} // namespace
int main(int argc, char** argv) {
assert(argc == 2);
using namespace mkwvk;
using namespace mkwvk::sim_turf_settings;
// ((Triforce) the options file's folder by its ANSI path, as GetModuleFileNameA gives it: the options file's own way)
fixture = std::filesystem::path(argv[1]) / "sim-turf-test";
assert(std::filesystem::create_directories(fixture));
config_file = (fixture / "sim_turf_settings.ini").string();
assert(!std::filesystem::exists(config_file));
mock.guest_base = mock_base;
mock.guest_size = mock_size;
mock.now_ns = mock_now;
#ifdef _WIN32
memory = static_cast<uint8_t*>(VirtualAlloc(nullptr, mock_size(), MEM_RESERVE, PAGE_READWRITE));
assert(memory);
assert(VirtualAlloc(memory + 0x10000, 0x10000, MEM_COMMIT, PAGE_READWRITE));
assert(VirtualAlloc(memory + 0x84e42000, 4096, MEM_COMMIT, PAGE_READWRITE));
#else
void* reserved = mmap(nullptr, mock_size(), PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
assert(reserved != MAP_FAILED);
memory = static_cast<uint8_t*>(reserved);
assert(mprotect(memory + 0x10000, 0x10000, PROT_READ | PROT_WRITE) == 0);
assert(mprotect(memory + 0x84e42000, 4096, PROT_READ | PROT_WRITE) == 0);
#endif
put<uint64_t>(0x84e42540, 0x10000);
put<uint64_t>(0x100f0, 0x11000);
put<uint64_t>(0x13a90, 0x14000);
constexpr uint64_t field = 0x18000, market = 0x19000, parent = 0x1a000;
scene_data(field, 20.0f, 100.0f, 24, 0.8f);
scene_data(market, 8.0f, 200.0f, 2, 0.0f);
scene_data(parent, 8.0f, 200.0f, 2, 2.0f);
put(market + 0xb1, uint8_t{0});
put<uint64_t>(market + 0x10, 1);
put<uint64_t>(market + 0x18, 0x1b000);
put<uint64_t>(0x1b000, parent);
put<uint32_t>(market + 0x20, 1);
put<uint32_t>(0x1b000 + 0xc, 1);
load(field, "HyruleField_Adult (adult)");
assert((values == std::array<int, 4>{200, 100, 24, 80}));
// The explicit low-end mode writes both zero controls live and saves them for only this area.
values[0] = 0;
area_changed(0);
values[2] = 0;
area_changed(2);
flush_config();
assert(get<float>(field + 0x7c) == 0.0f && get<int>(field + 0x70) == 0);
assert(!config_dirty && config_text().find("HyruleField_Adult") != std::string::npos);
assert(edited_now.load()); // ((Triforce) an edit of this area: the renderer's own turf lists in use)
// Global multipliers temporarily replace the area edit, including inherited values, then restore it.
global = 1;
mode_changed();
multipliers[1] = 20;
multiplier_changed();
assert(get<int>(field + 0x70) == 24 && get<float>(field + 0x68) == 50.0f);
load(market, "Market_Adult (adult)");
assert(get<float>(market + 0x68) == 100.0f && values[3] == 200);
multipliers[3] = 20;
multiplier_changed();
assert(get<float>(market + 0x6c) == 4.0f);
global = 0;
mode_changed();
assert(get<float>(market + 0x68) == 200.0f && get<uint8_t>(market + 0xb1) == 0);
// A failed atomic reset keeps both the saved edit and the live values; a successful one restores the install.
values[2] = 4;
area_changed(2);
values[3] = 300;
area_changed(3);
flush_config();
assert(can_reset_area() && get<int>(market + 0x70) == 4 && get<float>(market + 0x6c) == 3.0f);
const auto before_reset = config_text();
const std::filesystem::path blocked_temp = config_file + ".part"; // (file_whole.h's: a folder there, the write fails)
assert(std::filesystem::create_directory(blocked_temp));
reset_area();
assert(save_failed && can_reset_area() && config_text() == before_reset);
assert(get<int>(market + 0x70) == 4 && get<float>(market + 0x6c) == 3.0f);
assert(!std::filesystem::exists(blocked_temp) || std::filesystem::remove(blocked_temp));
reset_area();
assert(!save_failed && !can_reset_area());
assert(!edited_now.load()); // ((Triforce) the game's own values again: the game's own turf lists)
assert(get<int>(market + 0x70) == 2 && get<uint8_t>(market + 0xb1) == 0);
// Returning to the first area reapplies its own zero-turf edit, not Market's values.
load(field, "HyruleField_Adult (adult)");
assert(get<float>(field + 0x7c) == 0.0f && get<int>(field + 0x70) == 0);
load(market, "Market_Adult (adult)");
assert(get<int>(market + 0x70) == 2 && !can_reset_area());
#ifdef _WIN32
assert(VirtualFree(memory, 0, MEM_RELEASE));
#else
assert(munmap(memory, mock_size()) == 0);
#endif
std::puts("PASS: per-area simulated-turf settings, zero-turf mode, inheritance, persistence and reset rollback");
}

207
tests/srccut.py Normal file
View File

@@ -0,0 +1,207 @@
"""Cutting a piece of C, C++ or GLSL source out by its text, for the checks that compile or read one function of a source file
. Standard library only.
sys.path.insert(0, str(Path(__file__).resolve().parent)) # (python -I leaves the check's own folder off the path)
from srccut import block, between
block(text, marker): from the marker to the brace that closes the first { after it. Braces in string and character
literals (raw strings too), comments and preprocessor lines are not counted, as the copies of a brace counter in the checks
counted them. between(text, start, end): from start up to, not including, the first end after it.
A marker that is missing, or that appears more than once, stops the check with one message naming the source and the
marker: a function renamed or reshaped in the source is then one clear failure, and a marker that matches two places (a
declaration and its definition) cannot cut the wrong one. unique=False takes the first of several on purpose. A check
need not say which source it cut (where=): the message then names the tracked source file the text was read from, when
exactly one holds it, and the check that called.
SRCCUT_CHECK_NAIVE=1 also cuts each block as the old brace counter did and stops if the two differ: what a migration from
a check's own copy runs once to show the check cuts the same text as before.
"""
import os
from pathlib import Path
import subprocess
import sys
__all__ = ["block", "between", "find", "CutError"]
class CutError(SystemExit):
"""A marker missing, repeated, or a block that does not close: the check stops with this message"""
ROOT = Path(__file__).resolve().parent.parent
_SOURCE_SUFFIXES = (".c", ".cc", ".cpp", ".h", ".hpp", ".inl", ".m", ".mm", ".glsl", ".comp", ".vert", ".frag")
def _tracked_sources():
"""The C, C++ and GLSL files git tracks in this checkout (none when git is not there to ask)"""
try:
out = subprocess.run(["git", "-C", str(ROOT), "ls-files", "-z"], capture_output=True, timeout=30).stdout
except (OSError, subprocess.SubprocessError):
return []
return [name for name in out.decode("utf-8", "replace").split("\0") if name.endswith(_SOURCE_SUFFIXES)]
def _source_of(text):
"""The tracked source file this text was read from (or that holds it, for a cut of a cut), when exactly one fits.
Only a failing cut asks, so reading the sources here costs a passing check nothing."""
holding = []
for name in _tracked_sources():
try:
raw = (ROOT / name).read_bytes().decode("utf-8", "replace")
except OSError:
continue
for content in (raw, raw.replace("\r\n", "\n")): # (read_text() reads CRLF as \n; decoded bytes keep it)
if text == content:
return name
if text in content:
holding.append(name)
break
return holding[0] if len(holding) == 1 else None
def _caller():
"""The check that called srccut: the first frame outside this file, as a path from the repo root when it is in it"""
here = os.path.normcase(os.path.abspath(__file__))
frame = sys._getframe(1)
while frame is not None and os.path.normcase(os.path.abspath(frame.f_code.co_filename)) == here:
frame = frame.f_back
if frame is None:
return None
path = Path(os.path.abspath(frame.f_code.co_filename))
try:
return path.relative_to(ROOT).as_posix()
except ValueError:
return path.name
def _where(where, text):
"""where as the check gave it; when it gave none, the source file the text came from and the check that cut it"""
if where is not None:
return where
source, caller = _source_of(text), _caller()
if source and caller:
return "%s (cut by %s)" % (source, caller)
if source:
return source
if caller:
return "the source %s cut" % caller
return "the source"
def find(text, marker, where=None, unique=True, start=0):
"""Where marker is in text: the only place (or the first, unique=False)"""
at = text.find(marker, start)
if at < 0:
raise CutError("srccut: %r is not in %s (renamed or reshaped? update the check with the source)"
% (marker, _where(where, text)))
if unique:
again = text.find(marker, at + 1)
if again >= 0:
raise CutError("srccut: %r is in %s more than once (lines %d and %d): make the marker longer, or pass unique=False"
% (marker, _where(where, text), text.count("\n", 0, at) + 1, text.count("\n", 0, again) + 1))
return at
def _skip_literal(text, i, quote):
"""The index after the string or character literal whose opening quote is at i"""
i += 1
while i < len(text):
c = text[i]
if c == "\\":
i += 2
continue
if c == quote or c == "\n": # (an unclosed literal ends at the line's end, as a compiler would complain)
return i + 1
i += 1
return i
def _raw_string_end(text, i):
"""i is at R"delim( : the index after its )delim\" """
open_paren = text.find("(", i + 2)
delim = text[i + 2:open_paren]
close = text.find(")" + delim + '"', open_paren + 1)
return len(text) if close < 0 else close + len(delim) + 2
def _digit_separator(text, i):
"""The ' at i is C++14's digit separator (1'000'000), not a character literal"""
j = i - 1
while j >= 0 and (text[j].isalnum() or text[j] in "'_"):
j -= 1
token = text[j + 1:i]
return bool(token) and token[0].isdigit() and i + 1 < len(text) and text[i + 1].isalnum()
def _closing_brace(text, open_at, where, marker):
"""The index after the } that closes the { at open_at, not counting braces in literals, comments or preprocessor lines"""
depth, i, n = 0, open_at, len(text)
line_start = True
while i < n:
c = text[i]
if line_start and c in " \t":
i += 1
continue
if line_start and c == "#": # (a preprocessor line, with its continuations)
while i < n and text[i] != "\n":
i += 2 if text[i] == "\\" else 1
continue
line_start = c == "\n"
if text.startswith("//", i):
nl = text.find("\n", i)
i = n if nl < 0 else nl
continue
if text.startswith("/*", i):
end = text.find("*/", i + 2)
i = n if end < 0 else end + 2
continue
if c == '"':
if i and text[i - 1] == "R" and (i < 2 or not (text[i - 2].isalnum() or text[i - 2] == "_") or text[i - 2] in "uUL8"):
i = _raw_string_end(text, i - 1)
else:
i = _skip_literal(text, i, '"')
continue
if c == "'" and not _digit_separator(text, i):
i = _skip_literal(text, i, "'")
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return i + 1
i += 1
raise CutError("srccut: the block at %r in %s does not close" % (marker, _where(where, text)))
def _naive(text, marker):
start = text.index(marker)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def block(text, marker, where=None, unique=True):
"""From marker to the brace that closes the first { after it"""
start = find(text, marker, where, unique)
brace = text.find("{", start)
if brace < 0:
raise CutError("srccut: no { after %r in %s" % (marker, _where(where, text)))
cut = text[start:_closing_brace(text, brace, where, marker)]
if os.environ.get("SRCCUT_CHECK_NAIVE") == "1" and cut != _naive(text, marker):
raise CutError("srccut: %r in %s cuts differently from the old brace counter (a brace in a string or a comment?)"
% (marker, _where(where, text)))
return cut
def between(text, start, end, where=None, unique=True):
"""From start up to, not including, the first end after it"""
at = find(text, start, where, unique)
stop = text.find(end, at + len(start))
if stop < 0:
raise CutError("srccut: %r does not follow %r in %s" % (end, start, _where(where, text)))
return text[at:stop]

144
tests/stack_commit_test.c Normal file
View File

@@ -0,0 +1,144 @@
/* A thread's stack at Windows' commit limit (host/mkw_glue.c stack_on_touch), around the real handler cut out by
tests/test_stack_commit.py (stack_commit.inc), registered as hos_commit_init registers it (stack_commit_handlers.inc).
Windows only: the process puts itself in a Job object whose commit limit it then fills, as a PC at its limit is, and a
thread with a 64 MB stack that is only reserved (as host/hos_thread.c makes the guest's) grows it. No game, window or GPU.
stack_commit_test.exe recovers [small] [guarantee] | never [small] [guarantee] | ran-out
- recovers: commit comes back 300 ms after the thread starts (another thread gives back 8 MB, as the renderer's textures
give commit back): the thread grows its stack 6.4 MB deep and returns; exit 0.
- never: nothing is given back: the thread dies with 0xc00000fd after the out-of-memory line (the process's exit code).
- small (with recovers or never): the thread's frames are 512 bytes, not 16 KB, so its stack pointer is in the last
committed page when the next is refused (16 KB frames probe ahead of it, leaving the handler plenty).
- guarantee (with recovers or never): the thread asks for 32 KB of stack for its own overflow first
(SetThreadStackGuarantee), as the game's threads and fibers do (host/hos_thread.c hos_stack_guarantee).
- ran-out: no commit limit, a stack (1 MB asked for) that really runs out, 1.6 GB deep: 0xc00000fd at once, not tried
again for ever. */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "host_alloc.h" /* (host/: HOS_COMMIT_WAIT_MS's rule and the step the handler waits in) */
/* ---- stand-ins for what the cut code calls ---- */
/* (as much stack as the real one, hos_thread.c's hos_vlog: 4.3 KB of buffers. A handler that logs before its stack has room
runs off the page Windows committed, as it would in the game. Written with no heap: the process is at its commit limit) */
static void hos_log(const char *fmt, ...) {
char buf[1024], line[3300];
va_list a;
va_start(a, fmt);
int n = vsnprintf(buf, sizeof buf, fmt, a);
va_end(a);
if (n < 0) return;
n = snprintf(line, sizeof line, "[hos test] %s\n", buf);
if (n < 0) return;
if (n > (int)sizeof line - 1) n = (int)sizeof line - 1;
DWORD w;
WriteFile(GetStdHandle(STD_ERROR_HANDLE), line, (DWORD)n, &w, NULL);
}
static DWORD WINAPI hos_out_of_memory_box(LPVOID unused) { (void)unused; return 0; } /* (no notice window in a test) */
int hos_commit_wait_ms(void) { return host_alloc_wait_ms(getenv("HOS_COMMIT_WAIT_MS")); } /* (host_alloc.h declares it) */
#include "stack_commit.inc"
static void register_handlers(void) {
#include "stack_commit_handlers.inc"
}
/* ---- the case ---- */
static void *ballast[8];
static HANDLE go, ready;
static int guarantee;
/* (16 KB frames: each probed a page at a time below a stack pointer that is still well above, as large frames are) */
static int deep(int n) {
volatile char buf[16384];
buf[0] = (char)n;
if (n == 0) return buf[0];
return deep(n - 1) + buf[0];
}
/* (512-byte frames: the stack pointer itself is in the page Windows committed when the next one is refused, so the handler
has under 4 KB to run on where the thread asked for no guarantee) */
static int shallow(int n) {
volatile char buf[480];
buf[0] = (char)n;
if (n == 0) return buf[0];
return shallow(n - 1) + buf[0];
}
static void begin(void) {
if (guarantee) { /* (host/hos_thread.c hos_stack_guarantee) */
ULONG bytes = 32768;
SetThreadStackGuarantee(&bytes);
}
SetEvent(ready);
WaitForSingleObject(go, INFINITE);
}
static DWORD WINAPI grower(LPVOID depth) {
begin();
return (DWORD)deep((int)(intptr_t)depth) == 0xFFFFFFFF;
}
static DWORD WINAPI grower_small(LPVOID depth) {
begin();
return (DWORD)shallow((int)(intptr_t)depth) == 0xFFFFFFFF;
}
static DWORD WINAPI giver(LPVOID unused) {
(void)unused;
WaitForSingleObject(go, INFINITE);
Sleep(300);
for (int i = 0; i < 8; i++) VirtualFree(ballast[i], 0, MEM_RELEASE);
return 0;
}
int main(int argc, char **argv) {
const char *c = argc > 1 ? argv[1] : "";
int small = 0;
for (int i = 2; i < argc; i++) {
if (!strcmp(argv[i], "small")) small = 1;
if (!strcmp(argv[i], "guarantee")) guarantee = 1;
}
register_handlers();
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
go = CreateEventA(NULL, TRUE, FALSE, NULL);
ready = CreateEventA(NULL, TRUE, FALSE, NULL);
if (!strcmp(c, "ran-out")) {
HANDLE t = CreateThread(NULL, 1 << 20, grower, (LPVOID)(intptr_t)100000, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
SetEvent(go);
const DWORD waited = WaitForSingleObject(t, 20000);
DWORD code = 0;
GetExitCodeThread(t, &code);
hos_log("FAIL: a 1 MB stack 1.6 GB deep came back (wait %lu, thread exit %#lx, error %lu)", waited, code, GetLastError());
return 1;
}
if (strcmp(c, "recovers") && strcmp(c, "never")) return 2;
/* the threads first (their first stack pages, and the guarantee's), then the process's commit filled to the limit */
HANDLE t = small ? CreateThread(NULL, 64 << 20, grower_small, (LPVOID)(intptr_t)12800, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL)
: CreateThread(NULL, 64 << 20, grower, (LPVOID)(intptr_t)400, STACK_SIZE_PARAM_IS_A_RESERVATION, NULL); /* (6.4 MB) */
/* (the giver's 256 KB of stack committed now, not as it grows: at the limit it would need commit itself to give any back) */
HANDLE g = !strcmp(c, "recovers") ? CreateThread(NULL, 256 << 10, giver, NULL, 0, NULL) : NULL;
if (t) WaitForSingleObject(ready, INFINITE);
HANDLE job = CreateJobObjectA(NULL, NULL);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION li = {0};
li.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
li.ProcessMemoryLimit = 256 << 20;
if (!t || !job || !SetInformationJobObject(job, JobObjectExtendedLimitInformation, &li, sizeof li) ||
!AssignProcessToJobObject(job, GetCurrentProcess())) {
hos_log("SKIP: no Job object with a commit limit here (error %lu)", GetLastError());
return 4;
}
for (int i = 0; i < 8; i++) ballast[i] = VirtualAlloc(NULL, 1 << 20, MEM_COMMIT, PAGE_READWRITE);
for (SIZE_T step = 1 << 20; step >= 4096; step >>= 4)
while (VirtualAlloc(NULL, step, MEM_COMMIT, PAGE_READWRITE)) {}
if (!ballast[7] || GetLastError() != ERROR_COMMITMENT_LIMIT) {
hos_log("FAIL: the commit limit was not reached (error %lu)", GetLastError());
return 1;
}
SetEvent(go);
WaitForSingleObject(t, INFINITE);
DWORD code = 0;
GetExitCodeThread(t, &code);
if (g) WaitForSingleObject(g, INFINITE);
hos_log("the thread grew its stack 6.4 MB deep at the commit limit and returned %lu", code);
return (int)code;
}

View File

@@ -0,0 +1,46 @@
"""RX_A64_RT_O2=1 (nx2/build.py a64_rt_flags): the shared A64 helpers (a64_rt.c, a64_suyu.c) at -O2, the lifted chunks and the
hot pieces as they were. Off by default, the flags then the cold code's own, so the objects and their keys are as before.
Game-free.
python -I -B tests/test_a64_helper_flags.py
"""
import importlib.util
import os
from pathlib import Path
import sys
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "nx2"), str(ROOT / "third_party" / "a64-kit" / "tools")]
spec = importlib.util.spec_from_file_location("build_a64_helpers", ROOT / "nx2" / "build.py")
build = importlib.util.module_from_spec(spec)
spec.loader.exec_module(build)
FL = ["--target=x86_64-w64-mingw32", "-O1", "-g0", "-DA64_POLLING"]
class A64HelperFlags(unittest.TestCase):
def test_off_by_default_the_same_flags(self):
for value in (None, "", "0", "off"):
env = {} if value is None else {"RX_A64_RT_O2": value}
with mock.patch.dict(os.environ, env, clear=False):
if value is None:
os.environ.pop("RX_A64_RT_O2", None)
self.assertIs(build.a64_rt_flags(FL, "O1"), FL)
def test_on_only_the_level_changes(self):
with mock.patch.dict(os.environ, {"RX_A64_RT_O2": "1"}):
fl = build.a64_rt_flags(FL, "O1")
self.assertEqual(fl, ["--target=x86_64-w64-mingw32", "-O2", "-g0", "-DA64_POLLING"])
self.assertNotEqual(build.flag_text(fl), build.flag_text(FL)) # (another object key: compiled again)
def test_the_build_gives_them_to_the_two_helpers_alone(self):
src = (ROOT / "nx2" / "build.py").read_text(encoding="utf-8")
self.assertIn('rt_fl if os.path.basename(s) in ("a64_rt.c", "a64_suyu.c") else\n', src)
make = (ROOT / "nx2" / "make_game.py").read_text(encoding="utf-8")
self.assertIn('"RX_A64_RT_O2")', make[make.index("COMPILE_ONLY_ENV = "):][:120]) # (no new translation for it)
if __name__ == "__main__":
raise SystemExit(unittest.main(verbosity=1))

View File

@@ -248,6 +248,7 @@ int main() {
'''
MENU = r'''#include "@ROOT@/gpu/vk/aa_rows.h"
#include "@ROOT@/gpu/vk/evil_hd.h" /* ((Triforce, 11-23) the Anti-aliasing note while Evil HD is on) */
#include "@ROOT@/gpu/vk/n64_rules.h"
#include <algorithm>
#include <cctype>
@@ -275,6 +276,7 @@ bool antilag_available() { return true; }
unsigned upscalers_available() { return ~0u; }
bool filter_needed() { return true; }
const char* dlss_preset_env() { return nullptr; }
int fsr4_model_env() { return -1; } /* ((Triforce) RX_VK_FSR4_MODEL unset: row_fixed asks it for the FSR 4 model row */
int output_choice(int v) { return v; }
/* ((Triforce, 11-22, N64 Classic) its 3D pass drawing in the upscaler's place (vk_n64.cpp n64_in_front), RX_VK_N64, and the
Remembered page's rows (none here) */
@@ -331,7 +333,7 @@ int main() {
Classic's */
int n = 0;
while (hn_aa(v, n)) n++;
CHECK(n == 6 && !hn_aa(v, 6) && !hn_aa(v, 7));
CHECK(n == 8 && hn_aa(v, 6) && hn_aa(v, 7) && !hn_aa(v, 8)); /* ((Triforce) 6 Intel XeSS's, 7 Evil HD on */
for (int w = 0; w < v; w++) CHECK(std::strcmp(hn_aa(v, 0), hn_aa(w, 0)));
/* replaced: nothing more to say */
state_now = aa_rows::REPLACED;
@@ -350,9 +352,10 @@ int main() {
for (int v = 0; v < aa_rows::kValues; v++) {
opts.aa = v, up_now = up, env_now = -1, state_now = aa_rows::MISSING;
const bool nvidia = up == ur::DLSS || up == ur::DLAA;
CHECK(!std::strcmp(tx_aa(v), nvidia ? "DLSS's own" : "FSR's own") && row_fixed(&opts.aa));
CHECK(hn_aa(v, -1) == hn_aa(v, nvidia ? 1 : 2) && std::strstr(hn_aa(v, -1), "nothing to set here"));
CHECK(std::strstr(hn_aa(v, -1), nvidia ? "NVIDIA DLSS and DLAA" : "AMD FSR") && std::strstr(hn_aa(v, -1), "kept"));
const bool intel = up == ur::XESS || up == ur::XESS_AA; /* ((Triforce) Intel XeSS) */
CHECK(!std::strcmp(tx_aa(v), nvidia ? "DLSS's own" : intel ? "XeSS's own" : "FSR's own") && row_fixed(&opts.aa));
CHECK(hn_aa(v, -1) == hn_aa(v, nvidia ? 1 : intel ? 6 : 2) && std::strstr(hn_aa(v, -1), "nothing to set here"));
CHECK(std::strstr(hn_aa(v, -1), nvidia ? "NVIDIA DLSS and DLAA" : intel ? "Intel XeSS" : "AMD FSR") && std::strstr(hn_aa(v, -1), "kept"));
CHECK(opts.aa == v);
}
/* RX_VK_AA: the run's choice shown whatever the row holds, nothing to choose, and the line says why */
@@ -398,7 +401,7 @@ def main():
at = [menu.find(row) for row in order]
check(-1 not in at and at == sorted(at), "vk_menu.cpp: the Anti-aliasing row is not in its group after the Upscaling group")
check(menu.count('"Anti-aliasing", &opts.aa') == 1, "vk_menu.cpp: more than one Anti-aliasing row")
check("(rows[i].value != &opts.aa || up == ur::GAME)" in definition(menu, "bool row_shown"),
check("(rows[i].value != &opts.aa || up == ur::GAME || up == ur::OFF)" in definition(menu, "bool row_shown"),
"vk_menu.cpp: the Anti-aliasing row shows while DLSS or FSR smooths the edges itself")
entry = block(menu, menu.rindex("{TAB_GRAPHICS,", 0, at[4]))
check(re.search(r"\bint aa = 0;", header), "vk_menu.h: Anti-aliasing is not the game's own by default")
@@ -415,7 +418,8 @@ def main():
# the renderer's side: what is in effect is the row's rule, asked with what upscales as the menu's Upscaler row shows it
mode = definition(aa, "int aa_mode")
choice = definition(aa, "int choice_now")
check("const int choice = choice_now();" in mode and "ar::chosen(opts.aa, env_choice())" in choice and
# ((Triforce, 11-23) the row as Evil HD has it: SMAA Ultra while on, evil_hd.h; tests/test_evil_hd.py)
check("const int choice = choice_now();" in mode and "ar::chosen(evil_hd::aa(evil_hd_now(), opts.aa), env_choice())" in choice and
"ar::effective(choice, upscaler_now(), temporal_before_bloom(), env_choice() >= 0)" in mode,
"aa_mode does not take the row's choice (RX_VK_AA over it) through aa_rows.h's effective")
# ((Triforce, 11-22, N64 Classic) Off while its 3D pass draws the gameplay upscale; RX_VK_AA still over it)
@@ -426,7 +430,9 @@ def main():
check(re.sub(r"\s+", " ", definition(aa, "int upscaler_now")).endswith(
"{ if (fsr3_wanted()) return fsr3_native() ? upscaler_rows::FSR3_AA : upscaler_rows::FSR3; return temporal_mode(); }"),
"vk_aa.cpp's upscaler_now is not what the menu's Upscaler row shows")
check(re.search(r"int upscaler\(\) \{ return fsr3_wanted\(\) \? \(int\)\(fsr3_native\(\) \? ur::FSR3_AA : ur::FSR3\) : temporal_mode\(\); \}", menu),
# ((Triforce) 11-24: and the Upscaler's Off, which is the game's own here: its SMAA runs, upscaler_now's GAME)
check("if (fsr3_wanted()) return fsr3_native() ? ur::FSR3_AA : ur::FSR3;\n const int t = temporal_mode();\n"
" return t == ur::GAME && opts.dlss == ur::OFF ? (int)ur::OFF : t;" in menu,
"vk_menu.cpp's upscaler() changed: vk_aa.cpp's upscaler_now follows it")
check('getenv("RX_VK_AA")' in aa and 'getenv("RX_VK_AA_KEEP")' in aa, "vk_aa.cpp no longer reads its two switches")
# the game's own chosen and nothing left to free: a dispatch asks a comparison and nothing else
@@ -454,8 +460,8 @@ def main():
places = [dispatch.find(s) for s in ("if (!cp || !cp->ready.load(std::memory_order_acquire) || cp->failed) SKIP_HERE();",
"if (aa_leave_out(cp->key)) return;", "build_descriptors(s, p);",
'full_barrier(cmd, "barrier (dispatch)");', "if (taau_stand_in(cmd, s, p)) return void(st_dispatches++);",
"if (aa_stand_in(cmd, s, p)) return void(st_dispatches++);", "if (!p.compute_pipeline) SKIP_HERE();",
"vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, p.compute_pipeline);")]
"if (aa_stand_in(cmd, s, p)) return void(st_dispatches++);", "if (!pipe) SKIP_HERE();",
"vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);")]
check(-1 not in places and places == sorted(places), "dispatch no longer asks aa_leave_out and aa_stand_in where it did")
stand = definition(draw, "bool aa_stand_in")
check(stand.split("{", 1)[1].lstrip().startswith("if (aa_rows::role(p.key) != aa_rows::COMPOSE || !aa_asked()) return false;"),
@@ -491,7 +497,8 @@ def main():
("@HINT@", definition(menu, "const char* hn_aa")),
("@FIXED@", definition(menu, "bool row_fixed")),
("@KEY@", definition(menu, "const char* ini_key")),
("@INI_ROW@", "bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */\n" + definition(menu, "bool ini_row")),
("@INI_ROW@", "bool is_merged(const int*) { return false; } /* ((Triforce, options_version 7) no merged row here */\n"
"int output_pick; /* ((Triforce) the Output device row: saved by its device's id */\n" + definition(menu, "bool ini_row")),
("@ENTRY@", entry + ","),
("@READ@", read)):
fixture = fixture.replace(mark, text)

View File

@@ -53,7 +53,17 @@ def main():
check("#ifdef _WIN32" in wanted and 'getenv("RX_VK_ACQUIRE_AHEAD")' in wanted, "the switch is not read, or not on Windows alone")
check("if (asked == 0 || !acquire_fence_on() || dlssg::active()) return false;" in wanted,
"it runs without the acquire's fence, with DLSS frame generation, or with the switch at 0")
check("return asked > 0 || dev.props.vendorID == 0x1002;" in wanted, "it is not AMD's by default, or =1 does not turn it on")
check("if (asked > 0 || dev.props.vendorID == 0x1002) return true;" in wanted, "it is not AMD's by default, or =1 does not turn it on")
# ((Triforce) elsewhere only with Threaded rendering, never under FIFO or frame generation, its acquire with a zero timeout)
check("return acquire_ahead_threaded();" in wanted,
"it is on elsewhere without Threaded rendering")
threaded = block(replay, "bool acquire_ahead_threaded() {")
check("static const bool v = threaded_on();" in threaded and "framegen_on()" in threaded and "present_mode::kFifo" not in threaded
and "mode == present_mode::kMailbox || mode == present_mode::kImmediate" in threaded,
"Threaded rendering's acquire ahead runs under FIFO or frame generation")
timeout = block(replay, "uint64_t acquire_ahead_timeout() {")
check("return UINT64_MAX;" in timeout and " return 0;" in timeout,
"the acquire's timeout is not as before on AMD and =1, and 0 for Threaded rendering alone")
ahead = block(replay, "void acquire_ahead() {")
check("present_image_mu" not in ahead.split("//")[0] and "std::lock_guard lk(present_image_mu)" not in ahead,
@@ -61,7 +71,7 @@ def main():
check(before(ahead, "if (held_image.on || !dev.swapchain || dev.swap_resize.load(std::memory_order_acquire) ||",
"surface_lost_noted.load(std::memory_order_acquire)", "return;", "vkAcquireNextImageKHR("),
"it acquires while an image is held, with no swapchain, or before present_image made the swapchain again")
check("vkAcquireNextImageKHR(dev.device, dev.swapchain, UINT64_MAX, VK_NULL_HANDLE, fence, &index);" in ahead,
check("vkAcquireNextImageKHR(dev.device, dev.swapchain, acquire_ahead_timeout(), VK_NULL_HANDLE, fence, &index);" in ahead,
"the acquire does not signal the fence alone")
check(before(ahead, "if (res != VK_SUCCESS && res != VK_SUBOPTIMAL_KHR) {", "return;", "image_free(250000000ull)",
"held_image = {true, index, dev.swap_generation, 0, false, ready == VK_SUCCESS};"),

View File

@@ -33,7 +33,7 @@ def main():
raise SystemExit(why)
# (stages pinned to 32 lanes keep the short path: the long one in every compute program was new, longer SPIR-V that AMD
# compiled for hours, and they need none of it)
if "EmitSPIRV(profile_pinned(), rt, t->program, bindings)" not in shader:
if "EmitSPIRV(profile_pinned(uint64_t(wg[0]) * wg[1] * wg[2]), rt, t->program, bindings)" not in shader:
raise SystemExit("compute programs take the long warp path though they are pinned to 32 lanes")
if shader.count("EmitSPIRV(fallback ? profile_pinned() : profile_graphics(") != 2:
raise SystemExit("the mesh fallback's compute stages take the long warp path though they are pinned to 32 lanes")
@@ -42,7 +42,7 @@ def main():
graphics = graphics[:graphics.index("\n}\n")]
for needle, why in (
("q.warp_size_potentially_larger_than_guest = false, q.max_subgroup_size = 32", "a pinned graphics stage takes the long path"),
("!forced && (dev.sg32_stages & stage) ? pinned : profile()", "the stage's pinning does not pick its path"),
("!forced && pins_32(stage) ? pinned : profile()", "the stage's pinning does not pick its path"),
('getenv("RX_VK_WARP64")', "RX_VK_WARP64 no longer sets every graphics stage"),
):
if needle not in graphics:

View File

@@ -21,6 +21,9 @@ FIXTURE = r'''
enum VkShaderStageFlagBits : uint32_t {
VK_SHADER_STAGE_VERTEX_BIT = 1,
VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT = 2,
VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT = 4,
VK_SHADER_STAGE_GEOMETRY_BIT = 8,
VK_SHADER_STAGE_FRAGMENT_BIT = 16,
VK_SHADER_STAGE_COMPUTE_BIT = 32,
VK_SHADER_STAGE_TASK_BIT_EXT = 64,
@@ -29,10 +32,32 @@ enum VkShaderStageFlagBits : uint32_t {
VK_SHADER_STAGE_ALL = 0x7fffffff,
};
using VkShaderStageFlags = uint32_t;
using VkBool32 = uint32_t;
constexpr VkBool32 VK_FALSE = 0;
enum VkShaderFloatControlsIndependence { VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL = 1, VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_NONE = 2 };
constexpr uint32_t VK_DRIVER_ID_AMD_PROPRIETARY = 1;
constexpr uint32_t VK_DRIVER_ID_MESA_RADV = 3; // (make_profile: RADV before Mesa 26.2.5 keeps NumWorkgroups live)
#define VK_MAKE_VERSION(major, minor, patch) ((((uint32_t)(major)) << 22U) | (((uint32_t)(minor)) << 12U) | ((uint32_t)(patch)))
struct {
uint32_t sg32_stages = 0, subgroup_size = 32, subgroup_max = 32, driver_id = 0;
struct { struct { uint64_t minStorageBufferOffsetAlignment = 16; } limits; } props;
uint32_t max_workgroup_subgroups = 32; // (pins_32: 32-lane subgroups cover the 64 invocations profile_pinned assumes)
VkShaderStageFlags subgroup_stages = 0xff; // (make_profile: subgroups in every stage, float modes and 64-bit atomics on)
struct {
VkShaderFloatControlsIndependence denormBehaviorIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL,
roundingModeIndependence = VK_SHADER_FLOAT_CONTROLS_INDEPENDENCE_ALL;
VkBool32 shaderSignedZeroInfNanPreserveFloat16 = 1, shaderSignedZeroInfNanPreserveFloat32 = 1,
shaderDenormPreserveFloat32 = 1, shaderDenormFlushToZeroFloat32 = 1;
} float_controls;
struct {
bool shaderFloat16 = true; // (f16 lowered where the GPU has none; here it has)
// (make_profile: storage image and texel buffer arrays indexed nonuniformly where the GPU can)
bool shaderStorageImageArrayNonUniformIndexing = true, shaderUniformTexelBufferArrayNonUniformIndexing = true,
shaderStorageTexelBufferArrayNonUniformIndexing = true;
VkBool32 shaderBufferInt64Atomics = 1;
} vk12;
bool float_atomic_add = false;
bool mesh_shader = true;
struct { struct { uint64_t minStorageBufferOffsetAlignment = 16; } limits; uint32_t driverVersion = 0; } props;
struct { bool gather_offset = false; } fixes; // (vk_vendor.h: make_profile reads the gather offset from it)
} dev;
@@ -120,7 +145,8 @@ void check_stamp(uint32_t size, uint32_t pinned, bool workaround, bool forced) {
}
'''
internal = (VK / "vk_internal.h").read_text(encoding="utf-8")
fixture = (FIXTURE + section(internal, "inline uint64_t storage_binding_align()", "/// A range of guest memory")
fixture = (FIXTURE + section(internal, "inline bool pins_32(", "/// (hookshot) Where a storage buffer binding starts")
+ section(internal, "inline uint64_t storage_binding_align()", "/// A range of guest memory")
+ section(shader, "Shader::Profile make_profile(", "Shader::HostTranslateInfo host_info()")
+ section(shader, "const Shader::Profile& profile()", "const std::vector<Code>& codes_of(")
+ section(warp, "Id HostThreadId(", "Id GuestLane(")
@@ -149,7 +175,7 @@ void check_stamp(uint32_t size, uint32_t pinned, bool workaround, bool forced) {
env = {k: v for k, v in os.environ.items() if k not in ("RX_VK_WARP64", "RX_VK_FRAG_SHUFFLE_FALLBACK")}
for device, expected, overrides in cases:
subprocess.run([str(exe), *map(str, device + expected)], env=env | overrides, check=True, timeout=10)
assert "EmitSPIRV(profile_pinned(), rt, t->program, bindings)" in shader
assert "EmitSPIRV(profile_pinned(uint64_t(wg[0]) * wg[1] * wg[2]), rt, t->program, bindings)" in shader
for stage in ("TASK", "MESH"):
assert f"fallback ? profile_pinned() : profile_graphics(VK_SHADER_STAGE_{stage}_BIT_EXT)" in shader
for start, end in (("Id ShuffleRelative(", "Id BroadcastLane("), ("Id EmitShuffleIndex(", "Id EmitShuffleUp("),

View File

@@ -11,9 +11,14 @@ them; the file names taken; the readers' states (none before a figure is chosen,
looks, mounted, read, lifted off a second later, one touch a choice, taken away); and the game's own task, as its code
has it, run against them: it waits in the search state with no figure and ends with the figure's data with one.
Also (Triforce): a Flipper Zero NFC file (.nfc) read as the tag's bytes, cut short anywhere; and the application area a
game may keep on a figure: made, opened by its access ID, set, flushed, kept in a file of its own (never the dump),
closed when the figure is lifted off.
Reads the source for what cannot be run without the game: every SDK function answers as the lift's stub did (0, nothing
written) for a handle that is not a listed reader's; the file is opened by a checked name inside the amiibo folder and
at most 1025 bytes of it are read; nothing names or opens a key; the choice is taken at the pad read; the option ids.
its read is bounded; the only file written is the area's, under the amiibo folder's "areas", by the serial number;
nothing names or opens a key; the choice is taken at the pad read; the option ids.
python -I -B tests/test_amiibo.py [--cc gcc]
"""
@@ -36,6 +41,13 @@ FUNCTIONS = (
"_ZN2nn3nfp13StopDetectionERKNS0_12DeviceHandleE", "_ZN2nn3nfp10GetTagInfoEPNS0_7TagInfoERKNS0_12DeviceHandleE",
"_ZN2nn3nfp5MountERKNS0_12DeviceHandleENS0_9ModelTypeENS0_11MountTargetE",
"_ZN2nn3nfp12GetModelInfoEPNS0_9ModelInfoERKNS0_12DeviceHandleE")
# ((Triforce) the application area's, for a game that keeps data on a figure: answered for a figure of ours only)
AREA_FUNCTIONS = (
"_ZN2nn3nfp19OpenApplicationAreaERKNS0_12DeviceHandleEj", "_ZN2nn3nfp18GetApplicationAreaEPvPmRKNS0_12DeviceHandleEm",
"_ZN2nn3nfp18SetApplicationAreaERKNS0_12DeviceHandleEPKvm",
"_ZN2nn3nfp21CreateApplicationAreaERKNS0_12DeviceHandleERKNS0_25ApplicationAreaCreateInfoE",
"_ZN2nn3nfp23RecreateApplicationAreaERKNS0_12DeviceHandleERKNS0_25ApplicationAreaCreateInfoE",
"_ZN2nn3nfp5FlushERKNS0_12DeviceHandleE")
def check(ok, why):
@@ -61,10 +73,20 @@ def check_source():
sys.path.insert(0, str(ROOT / "nx2"))
import standalone
have = standalone.implemented()
for name in FUNCTIONS:
for name in FUNCTIONS + AREA_FUNCTIONS:
check("imp_" + name in have, "host/ has no " + name)
code = nfp[nfp.index("#include"):]
check(len(re.findall(r"^HLE\(", code, re.M)) == len(FUNCTIONS), "host/nn_nfp.c has other SDK functions than the game's request makes")
check(len(re.findall(r"^HLE\(", code, re.M)) == len(FUNCTIONS + AREA_FUNCTIONS),
"host/nn_nfp.c has other SDK functions than the game's request and the application area's")
for name in AREA_FUNCTIONS: # (a figure of ours only: 0 and nothing written for any other handle)
text = body(nfp, name)
check("reader_of(ARG(" in text or "area_create(c, " in text, name + " does not ask whose handle it is")
for write in re.findall(r"^[^\n]*(?:memcpy\(out|G64\(ARG|area_save\()[^\n]*$", text, re.M):
check("reader >= 0" in write or "if (save)" in write, name + " writes for a handle that is not a reader's: " + write.strip())
create = nfp[nfp.index("static uint32_t area_create("):]
create = create[:create.index("\n}\n")]
check("reader >= 0 && info ? nfp_area_create(" in create and "if (save) area_save(&tag, bytes)" in create,
"CreateApplicationArea makes or writes an area for a handle that is not a reader's")
# a handle that is not a listed reader's: 0 and nothing written, as the lift's stub answers
for name in FUNCTIONS[4:]:
text = body(nfp, name)
@@ -83,9 +105,15 @@ def check_source():
load = nfp[nfp.index("static int load_dump("):nfp.index("void hos_amiibo_poll(")]
check("if (!amiibo_name_ok(name) || !hos_share_game_dir(dir, sizeof dir)) return NFP_SAID_NO_FILE;" in load
and 'snprintf(path, sizeof path, "%s/amiibo/%s", dir, name);' in load, "the dump is not opened by a checked name inside the amiibo folder")
check("uint8_t data[AMIIBO_FILE_MAX + 1];" in load and "fread(data, 1, sizeof data, f)" in load and "amiibo_parse(data, n, tag)" in load,
check("static uint8_t data[AMIIBO_NFC_MAX + 1], pages[540];" in load and "fread(data, 1, sizeof data, f)" in load and
"amiibo_parse(data, n, tag)" in load and "n <= AMIIBO_NFC_MAX && amiibo_flipper((const char *)data, n, pages)" in load,
"the dump's read is not bounded")
check(nfp.count("fopen(") == 1 and "fwrite" not in nfp and "fopen" not in header, "host/nn_nfp.c opens another file than the dump, or writes one")
# ((Triforce) the dump is only read: the one file written is the area's, in the amiibo folder's areas, by its serial number)
area = nfp[nfp.index("static int area_path("):nfp.index("void hos_amiibo_poll(")]
check(nfp.count("fopen(") == 3 and nfp.count('fopen(path, "rb")') == 2 and nfp.count("fwrite(") == 1 and "fopen" not in header,
"host/nn_nfp.c opens other files than the dump and the area's, or writes another")
check('snprintf(path, cap, "%s/amiibo/areas/%s", dir, name);' in area and "amiibo_area_name(tag, name);" in area and
'fopen(path, "wb")' in area and "fwrite(bytes, 1, NFP_AREA_FILE, f)" in area, "the area is written somewhere else than its own file")
for text, where in ((code, "host/nn_nfp.c"), (header[header.index("#pragma once"):], "host/amiibo.h")):
stripped = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
check(not re.search(r"key|retail|hmac|aes|decrypt\w*\(", stripped, re.I), where + " has code that names a key or decrypts")
@@ -99,6 +127,11 @@ def check_source():
check("availability_event = 0;" in body(nfp, FUNCTIONS[1]), "the game's event is kept after Finalize")
check("enum { HOS_OPT_DEBUG_ASK = 115, HOS_OPT_DEBUG_TEXT, HOS_OPT_DEBUG_SAID, HOS_OPT_AMIIBO_ASK, HOS_OPT_AMIIBO_SAID };" in api,
"gpu/vk/vk_api.h: the option ids 115 to 119")
# (the System tab's NFC group: the same Scan amiibo page for every player, not only with the Debug tab's tools on)
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
if not re.search(r'MENU_HEADING\(TAB_SYSTEM, "NFC"\),\s*\{TAB_SYSTEM, kNfcTag, nullptr,', menu) or \
"else if (press[7] && r.name == kNfcTag) names_open(kNamesAmiibo)" not in menu:
raise SystemExit("FAIL: vk_menu.cpp: the System tab's NFC tag row does not open the Scan amiibo page")
print("PASS: the SDK's functions answer as before until a figure is chosen, and no key is read")

View File

@@ -20,6 +20,12 @@ WANT = {
"licenses/libertinus/OFL.txt": "third_party/fonts/libertinus/OFL.txt",
"licenses/libertinus/PROVENANCE.md": "third_party/fonts/PROVENANCE.md",
"licenses/fidelityfx/LICENSE.md": "third_party/fidelityfx/LICENSE.md", # ((Triforce) 11-20: FSR 4's headers in the image)
"licenses/fidelityfx-sdk/LICENSE.txt": "third_party/fidelityfx-sdk/LICENSE.txt", # ((Triforce) 11-24: FSR 3.1's shaders
"licenses/fidelityfx-sdk/PROVENANCE.md": "third_party/fidelityfx-sdk/PROVENANCE.md",
"licenses/reshade_fx/LICENSE.md": "third_party/reshade_fx/LICENSE.md", # ((Triforce) the ReShade presets' compiler
"licenses/reshade_fx/PROVENANCE.md": "third_party/reshade_fx/PROVENANCE.md",
"licenses/stb_image/LICENSE": "third_party/stb_image/LICENSE",
"licenses/stb_image/PROVENANCE.md": "third_party/stb_image/PROVENANCE.md",
}

View File

@@ -0,0 +1,154 @@
"""Frees that waited on a frame count, not on the GPU's progress, game-free. No GPU. Each is a hazard on every GPU, reached
when the GPU runs late.
- Frees counted in frames: what the temporal upscalers (DLSS and FSR 4 through temporal_later) and the FSR 3 inputs let go
(later, free_dead) waits for the timeline value that followed it (vk_retirement_value) as well as for its frames, and
never for a value of 0: the real functions run on a clock and a timeline of the test's. With no window nothing waits for
the present ring, and 4 frames are fewer than the recordings the GPU may be behind.
- AMD FSR 3.1's own images and its frame interpolation's (vk_fsr3.cpp, vk_fsr3fi.cpp: drop_image, free_dead) wait the same
way: read from the source.
python -I -B tests/test_async_safe_frees.py --headers <Vulkan-Headers/include> [--cxx clang++] [--source <tree>]
--source <tree> reads another tree's sources (the negative control: a tree without the fixes fails each check).
"""
import argparse
from pathlib import Path
import re
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cxx", "{cxx}", "--headers", "{vulkan_headers}"]
ROOT = Path(__file__).resolve().parents[1]
def block(text, marker):
start = text.index(marker)
at = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[at] == "{") - (text[at] == "}")
at += 1
return text[start:at]
def compile_run(a, name, code, failures):
with tempfile.TemporaryDirectory(prefix="async-safe-frees-") as tmp:
cpp, exe = Path(tmp) / (name + ".cpp"), Path(tmp) / (name + ".exe")
cpp.write_text(code, encoding="utf-8")
r = subprocess.run([a.cxx, "-std=c++20", "-O1", "-Wall", "-Wextra", "-Werror", "-Wno-unused-function",
"-Wno-missing-field-initializers", "-I" + str(a.headers), str(cpp), "-o", str(exe)],
capture_output=True, text=True, timeout=300)
if r.returncode:
failures.append("%s: the fixture did not build: %s" % (name, (r.stdout + r.stderr).strip()[-600:]))
return
r = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60)
if r.returncode:
failures.append("%s: %s" % (name, (r.stdout + r.stderr).strip()[-600:]))
PRELUDE = r'''
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan_core.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <mutex>
#include <vector>
static int failed;
static void check(bool ok, const char* what) { if (!ok) { std::printf("FAIL: %s\n", what); failed++; } }
'''
F6_LATER = r'''
// ---- the replay's frame count and timeline, as a test sets them ----
uint64_t frame_no = 0, retirement = 0, done = 0;
uint64_t texture_frame_no() { return frame_no; }
uint64_t vk_retirement_value() { return retirement; }
uint64_t vk_timeline_completed() { return done; }
/* SYSTEMS */
template <class Later, class Free> void run(const char* name, Later later, Free free_dead) {
char what[160];
int freed = 0;
frame_no = 10, retirement = 20, done = 0;
later([&] { freed++; });
frame_no = 15, done = 19;
free_dead();
std::snprintf(what, sizeof what, "%s: not freed before the timeline value that followed it, 5 frames on", name);
check(freed == 0, what);
done = 20;
free_dead();
std::snprintf(what, sizeof what, "%s: freed once the timeline is past it and its frames are", name);
check(freed == 1, what);
frame_no = 30, retirement = 40, done = 1000;
later([&] { freed++; });
frame_no = 34;
free_dead();
std::snprintf(what, sizeof what, "%s: still not before its frames, the timeline past it", name);
check(freed == 1, what);
frame_no = 35;
free_dead();
std::snprintf(what, sizeof what, "%s: freed at its frames, the timeline past it, as before", name);
check(freed == 2, what);
frame_no = 50, retirement = 0;
later([&] { freed++; });
frame_no = 5000, done = 5000;
free_dead();
std::snprintf(what, sizeof what, "%s: never freed on a value of 0 (no safe value)", name);
check(freed == 2, what);
}
int main() {
run("temporal upscalers", [](std::function<void()> f) { temporal::later(std::move(f)); }, [] { temporal::free_dead(false); });
run("FSR 3 inputs", [](std::function<void()> f) { fsr3_inputs::later(std::move(f)); }, [] { fsr3_inputs::free_dead(); });
return failed ? 1 : 0;
}
'''
def later_system(namespace, source, failures):
dead = re.search(r"\n struct Dead \{[^\n]*\};\n", source)
if not dead:
failures.append("%s: no Dead list" % namespace)
return ""
return ("namespace %s {\nstruct State {%s std::vector<Dead> dead;\n};\nState& st() { static State s; return s; }\n%s\n%s\n}\n"
% (namespace, dead.group(0), block(source, "void later("), block(source, "void free_dead(")))
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--headers", type=Path, required=True)
p.add_argument("--cxx", default="c++")
p.add_argument("--source", type=Path, default=ROOT)
a = p.parse_args()
vk = a.source.resolve() / "gpu" / "vk"
failures = []
# the three later() lists, run
systems = "".join(later_system(ns, (vk / name).read_text(encoding="utf-8"), failures)
for ns, name in (("temporal", "vk_temporal.cpp"), ("fsr3_inputs", "vk_fsr3_inputs.cpp")))
if systems.count("namespace ") == 2:
compile_run(a, "f6_later", PRELUDE + F6_LATER.replace("/* SYSTEMS */", systems), failures)
temporal = (vk / "vk_temporal.cpp").read_text(encoding="utf-8")
if "void temporal_later(std::function<void()> f) { later(std::move(f)); }" not in temporal:
failures.append("DLSS's and FSR 4's frees (temporal_later) do not go through the temporal list")
# AMD FSR 3.1's images and its frame interpolation's: let go with the value, freed on both
for name in ("vk_fsr3.cpp", "vk_fsr3fi.cpp"):
text = (vk / name).read_text(encoding="utf-8")
drop, free = block(text, "void drop_image("), block(text, "void free_dead(")
if "vk_retirement_value()" not in drop:
failures.append("%s: drop_image does not keep the timeline value that follows the work" % name)
if "vk_timeline_completed()" not in free or not re.search(r"\.value && done >= \S+\.value", free):
failures.append("%s: free_dead does not wait for the timeline value (never at 0)" % name)
for f in failures:
print("FAIL " + f)
if failures:
raise SystemExit("FAIL: %d" % len(failures))
print("PASS: the upscalers' frees wait for the GPU's progress")
if __name__ == "__main__":
main()

73
tests/test_audio_aux.py Normal file
View File

@@ -0,0 +1,73 @@
"""The actual Aux API and its effect code from host/nn_audio.c, around authored signals; no game or audio device.
The game's own effects (its CPU effect workers) read what a mix sends them with ReadAuxSendBuffer and hand the result
back with WriteAuxReturnBuffer. The host accepted an Aux and passed its mix through: the effect's send was heard as one
more dry source and the effect never. Checked: the buffer size the game is told, whole planar frames out to the worker
and back in place of the send, the channel maps (crossed too), changes waiting for the update, an underrun as silence
and never an old return again, an overflow never queuing a part of a frame, a removed Aux's buffers left alone at once,
its slot taken again before the update, the order across a reverb and an Aux, and a released mix. With HOS_AUDIO_AUX=0
or HOS_AUDIO_EFFECTS=0 an Aux is accepted and passed through, as before.
python -I -B tests/test_audio_aux.py [--cc clang] [--source host/nn_audio.c]
"""
import argparse
import os
from pathlib import Path
import subprocess
import sys
import tempfile
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
def function(source, marker):
start = source.index(marker)
end = source.index('{', start) + 1
depth = 1
while depth:
depth += (source[end] == '{') - (source[end] == '}')
end += 1
return source[start:end]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--cc', default='cc')
parser.add_argument('--source', type=Path, default=ROOT / 'host/nn_audio.c')
args = parser.parse_args()
source = args.source.read_text(encoding='utf-8')
# (the file's own types, update queue, effect code and entry points, in the file's order)
api = source.index('/* ---- Aux effects: the API')
reverb = source.index('static Reverb *reverb_of(')
chunks = [
source[source.index('#define FRAME'):source.index('/* ---- wave buffers')],
function(source, 'static void release_wb('),
source[source.index('/* ---- I3DL2 reverb ('):source.index('/* ---- the mixer')],
source[source.index('/* ---- parameter updates'):source.index("/* The mixer's next deadline.")],
function(source, 'HLE(_ZN2nn5audio43GetRequiredBufferSizeForAuxSendReturnBuffer'),
source[api:source.index('HLE(_ZN2nn5audio17IsReverbRemovable', api)],
source[reverb:source.index('static void ret_float(', reverb)],
]
flags = subprocess.CREATE_NO_WINDOW | subprocess.BELOW_NORMAL_PRIORITY_CLASS if os.name == 'nt' else 0
with tempfile.TemporaryDirectory(prefix='audio-aux-') as tmp:
directory = Path(tmp)
(directory / 'audio_aux.inc').write_text('\n'.join(chunks), encoding='utf-8')
exe = directory / 'audio_aux.exe'
build = [args.cc, '-std=c11', '-O1', '-Wall', '-Wextra', '-Werror', '-Wno-unused-function',
'-Wno-unused-variable', '-Wno-unused-parameter', '-I' + str(directory),
str(ROOT / 'tests/audio_aux_test.c'), '-lm', '-o', str(exe)]
env = {k: v for k, v in os.environ.items() if not k.startswith('HOS_AUDIO')}
for command, environment in ((build, env), ([str(exe)], env), ([str(exe)], dict(env, HOS_AUDIO_AUX='0')),
([str(exe)], dict(env, HOS_AUDIO_EFFECTS='0'))):
result = subprocess.run(command, creationflags=flags, capture_output=True, text=True, env=environment,
encoding='utf-8', errors='replace', timeout=120)
print(result.stdout, end='')
print(result.stderr, end='', file=sys.stderr)
if result.returncode:
raise SystemExit(result.returncode)
if __name__ == '__main__':
main()

View File

@@ -49,18 +49,26 @@ FIXTURE = r'''
static int64_t clock_ns = 1000000000;
int64_t hos_now_ns(void) { return clock_ns; }
int hos_mic_gain(void) { return 100; } /* ((Triforce) the Microphone gain row at its default: the microphone's own samples) */
static int logged;
void hos_log(const char *fmt, ...) { (void)fmt; logged++; }
const char *hos_sdl_error(void) { return "no device"; }
/* SDL's microphones: "Test microphone", two "Twin" and a long name, as ids id_base.. ; the default (id 0) opens unless
no_default */
static int listed = 1, no_default, opens, opened, closed, mic_bytes, next_sample, last_format, last_rate, last_channels;
static int expanded_list;
static uint32_t id_base = 7, last_id = 99;
#define LONG_NAME "Microphone Array (Intel\xc2\xae Smart Sound Technology for Digital Microphones)"
int hos_sdl_mic_list(uint32_t *ids, char (*names)[128], int max) {
static const char *const all[4] = {"Test microphone", "Twin", "Twin", LONG_NAME};
int n = 0;
for (; n < listed && n < max && n < 4; n++) ids[n] = id_base + (uint32_t)n, strcpy(names[n], all[n]);
for (; n < listed && n < max && (expanded_list || n < 4); n++) {
ids[n] = id_base + (uint32_t)n;
if (expanded_list) {
if (n == 23) strcpy(names[n], "Discord VAIO Output");
else snprintf(names[n], 128, "Expanded microphone %d", n);
} else strcpy(names[n], all[n]);
}
return n;
}
void *hos_sdl_mic_open(uint32_t id, int freq, int channels, uint16_t format) {
@@ -287,6 +295,33 @@ int main(void) {
for (int k = 0; k < 12; k++) MS(1000), (void)FILLED(big); /* (silence comes a second at most a poll) */
if (FILLED(big) != 480000) FAIL(42, "a huge frame count: %d frames held, not 10 s", FILLED(big));
cases += 2;
/* More than sixteen recording endpoints: the real device at slot 24 must be found, including after its id changes. */
expanded_list = 1, listed = 70;
if (hos_mic_count() != 64 || strcmp(hos_mic_name(23), "Discord VAIO Output") ||
strcmp(hos_mic_name(63), "Expanded microphone 63") || hos_mic_name(64)[0])
FAIL(43, "the expanded list and its boundary");
hos_mic_select(2, "Discord VAIO Output", 23);
(void)FILLED(big);
if (last_id != id_base + 23) FAIL(44, "the named microphone beyond sixteen: id %u", last_id);
hos_mic_select(2, "Expanded microphone 63", 63);
(void)FILLED(big);
if (last_id != id_base + 63) FAIL(45, "the last microphone in the expanded list: id %u", last_id);
hos_mic_select(2, "Expanded microphone 64", 64);
(void)FILLED(big);
if (last_id != 0) FAIL(46, "a name past the list boundary uses the default: id %u", last_id);
hos_mic_select(2, "Discord VAIO Output", 23);
(void)FILLED(big);
listed = 0, MS(5100);
(void)FILLED(big);
if (last_id != 0) FAIL(47, "the unplugged high-index microphone uses the default: id %u", last_id);
listed = 70, id_base += 100, MS(3100);
(void)FILLED(big);
if (last_id != id_base + 23) FAIL(48, "the high-index microphone reconnects under its new id: %u", last_id);
hos_mic_select(1, "", -1);
(void)FILLED(big);
if (last_id != 0) FAIL(49, "Default stays independent of the expanded list: id %u", last_id);
CALL(imp__ZN2nn5audio16CloseInputStreamEPNS0_15InputStreamTypeE, U(big));
cases += 7;
printf("PASS: %d input stream cases (device list, open, start, silence, a shared microphone, capacity, a lost one and its"
" retries, a quiet one, named ones, a stand-in, stop, close)\n", cases);
return 0;
@@ -350,7 +385,25 @@ int main() {
refresh_mics();
CHECK(mic_want == "USB Mic" && !mic_missing && opts.mic == 2 && !std::strcmp(tx_mic(2), "USB Mic") && told.index == 0);
}
std::puts("PASS: the Microphone row keeps its choice by name, and tells the host");
names.clear();
for (int i = 0; i < 70; i++) names.push_back(i == 23 ? "Discord VAIO Output" : "Expanded microphone " + std::to_string(i));
opts.mic = 1, mic_chosen(), refresh_mics();
CHECK(mic_listed == 64 && rows[0].hi == 65 && opts.mic == 1 && told.mode == 1);
opts.mic = 25, mic_chosen();
CHECK(mic_want == "Discord VAIO Output" && told.index == 23);
refresh_mics();
CHECK(opts.mic == 25 && !mic_missing);
opts.mic = 65, mic_chosen();
CHECK(mic_want == "Expanded microphone 63" && told.index == 63);
names.resize(63);
refresh_mics();
CHECK(mic_missing && opts.mic == 65 && rows[0].hi == 65 && told.index == -1);
names.push_back("Expanded microphone 63");
refresh_mics();
CHECK(!mic_missing && opts.mic == 65 && told.index == 63);
opts.mic = 1, mic_chosen(), refresh_mics();
CHECK(opts.mic == 1 && mic_want.empty() && told.mode == 1);
std::puts("PASS: the Microphone row keeps its choice by name, and tells the host (including more than sixteen devices)");
return 0;
}
"""
@@ -397,8 +450,9 @@ def main():
'the start lists the microphones (and starts SDL audio) even with none chosen')
with tempfile.TemporaryDirectory(prefix='audio-in-') as t:
folder = Path(t)
# ((Triforce) host/mic_gain.h, the Microphone gain row's rule, as it is; the row at its default: FIXTURE's hos_mic_gain)
for name, text in (('hos.h', HOS_H), ('windows.h', WINDOWS_H), ('hos_sdl.h', sdl_h), ('nn_audio_in.c', source),
('fixture.c', FIXTURE)):
('mic_gain.h', (ROOT / 'host' / 'mic_gain.h').read_text(encoding='utf-8')), ('fixture.c', FIXTURE)):
(folder / name).write_text(text, encoding='utf-8')
exe = folder / 'fixture'
subprocess.run([a.cc, '-std=gnu11', '-Wall', '-Wextra', '-Werror', '-I', str(folder), str(folder / 'fixture.c'),

View File

@@ -5,7 +5,8 @@ The "Volcano eruption audio bugged" ticket: the game's AddBiquadFilter, AddDelay
SetSplitterBiquadFilterParameter were import stubs, so what it routes through them played unfiltered and too loud.
Checked: a low pass passes a low tone and takes a high one down, a delay's echo lands at the delay time and decays by
the feedback gain, the channel spread moves the echo to the other channel, the plain reverb adds a tail on top of the
dry signal, a splitter destination's filter reaches the voice's mix through render_voice, and with
dry signal, a splitter destination's filter reaches the voice's mix through render_voice with a history of each
voice's own (a second voice through the same splitter does not hear the first one's), and with
HOS_AUDIO_EFFECTS=0 every sample is left as it was. No game, SDK or output device is used.
"""
import argparse
@@ -53,9 +54,19 @@ static void release_wb(Voice *voice, uint64_t buffer) { (void)voice; (void)buffe
actual.extend(helper.block(source, marker) for marker in (
"static void put_handle(", "static int get_handle(", "static float farg(", "static int mix_index(",
"static Mix *mix_of(", "static int splitter_index(", "static Splitter *splitter_of("))
actual.extend([queue, helper.block(source, "static void apply("), helper.block(source, "static void submit("),
helper.block(source, "static void commit("), effects,
# (the effects before the update queue, as in the file: apply names the Aux effects)
actual.extend([effects, queue, helper.block(source, "static void apply("), helper.block(source, "static void submit("),
helper.block(source, "static void commit("),
"static int next_source_frame(Voice *v); /* (the fixture's tone) */",
"""/* ((Triforce) the controller speaker (host/pad_speaker.c, host/audio_source.h), off: nothing classed, nothing sent */
enum { AUDIO_SOURCE_NONE, AUDIO_SOURCE_NAVI_VOICE, AUDIO_SOURCE_NAVI_SOUND, AUDIO_SOURCE_TARGET, AUDIO_SOURCE_OCARINA };
enum { HOS_PAD_SPEAKER_OFF = 0, HOS_PAD_SPEAKER_ONLY = 1, HOS_PAD_SPEAKER_BOTH = 2 };
static int hos_pad_speaker_active(void) { return 0; }
static int speaker_on, tv_delay;
static int hos_pad_speaker_mode(int cls) { (void)cls; return HOS_PAD_SPEAKER_OFF; }
static void hos_pad_speaker_ocarina_seen(void) {}
static void speaker_voice(const Voice *v, float out[][FRAME], const int *pad) { (void)v, (void)out, (void)pad; }
static float (*tv_stage(int mi))[FRAME] { (void)mi; return NULL; }""",
helper.block(source, "static void render_voice("),
helper.block(source, "static void set_split_biquad("),
helper.block(source, "HLE(" + SPLIT_BIQUAD + ")"), setters])

View File

@@ -0,0 +1,68 @@
"""The Audio tab's Output device row (host/audio_output_devices.c, host/nn_audio.c, gpu/vk/vk_menu.cpp).
The device module is compiled with made-up WinMM devices (tests/audio_output_devices_test.c: 80 devices, one name shared,
ids that stay when the list is reordered, the choice's mailbox, the options file's line) and run; the sound's thread's own
handling of the choice is tests/test_audio_output_errors.py's. Then the sources: the row saved by the device's id and not
its number, the devices listed when the menu opens and not each frame, the choice taken before a block is mixed, and the
host's table in the order of MkwVkHost's members.
python -I -B tests/test_audio_output_devices.py [--cc clang] [--source-only]
"""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cc", "clang"]
ROOT = Path(__file__).resolve().parents[1]
def code(text):
return re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", text, flags=re.S))
def sources():
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
audio = (ROOT / "host/nn_audio.c").read_text(encoding="utf-8")
api = (ROOT / "gpu/vk/vk_api.h").read_text(encoding="utf-8")
backend = (ROOT / "host/rx_backend.c").read_text(encoding="utf-8")
assert re.search(r'\{TAB_AUDIO, "Output device", &output_pick,', menu), "no Output device row"
assert re.search(r'\{TAB_AUDIO, "Audio output", &opts\.audio_output, 0, 3,', menu), "the Audio output row changed"
assert "&& r.value != &output_pick; }" in menu, "the Output device row's number is saved"
assert 'put("audio_output_device_id", output_want);' in menu and 'put("audio_output_device_name", output_saved_name);' in menu
tick = menu[menu.index("void menu_tick() {"):]
assert tick.count("refresh_outputs();") == 1 and "if (open_now.load()) refresh_outputs();" in tick, \
"the devices are listed again other than when the menu opens"
assert "if (r.value == &output_pick && output_forced()) return;" in menu, "HOS_AUDIO_DEVICE does not hold the row"
mixer = audio[audio.index("static DWORD WINAPI renderer_main"):]
assert mixer.index("output_route_update();") < mixer.index("render_frame(pcm, out_channels);") < mixer.index("output_frame(pcm);")
body = code(api.split("typedef struct MkwVkHost {", 1)[1].split("} MkwVkHost;", 1)[0])
fields = [d for d in body.split(";") if d.strip()]
table = [v.strip() for v in code(backend.split("static const MkwVkHost vk_host = {", 1)[1].split("};", 1)[0]).split(",") if v.strip()]
assert len(fields) == len(table), "MkwVkHost has %d members, host/rx_backend.c's table %d" % (len(fields), len(table))
names = ["audio_output_count", "audio_output_info", "audio_output_select", "audio_output_state"]
at = [i for i, d in enumerate(fields) if any("(*%s)" % n in d for n in names)]
assert len(at) == 4 and [table[i] for i in at] == ["hos_" + n for n in names], "the host's table has not the device functions in place"
assert re.search(r"#define MKWVK_API_VERSION (\d+)", api) and int(re.search(r"#define MKWVK_API_VERSION (\d+)", api).group(1)) >= 20
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc", default="clang")
parser.add_argument("--source-only", action="store_true")
args = parser.parse_args()
sources()
print("PASS: the Output device row's sources")
if args.source_only or os.name != "nt":
return
with tempfile.TemporaryDirectory(prefix="audio-output-devices-") as tmp:
exe = Path(tmp) / "devices.exe"
subprocess.run([args.cc, "-std=c11", "-Wall", "-Wno-unused-function", "-I" + str(ROOT / "host"),
str(ROOT / "tests/audio_output_devices_test.c"), "-o", str(exe), "-lwinmm", "-lole32"], check=True)
subprocess.run([str(exe)], check=True, cwd=tmp)
if __name__ == "__main__":
main()

View File

@@ -12,7 +12,10 @@ import tempfile
ROOT = Path(__file__).resolve().parents[1]
CASES = ("normal", "busy", "prepare", "write", "unprepare", "open", "bounded", "stall", "surround", "fallback",
"lost", "gone", "service", "default")
"lost", "gone", "service", "default", "selection", "named-missing", "named-override", "named-format", "named-default-change",
"layout-reopen", "upmix", "downmix", "retry", "same-layout-retry", "pre-mix",
"named-stall-budget", "named-backoff", "named-open-failure", "named-healthy-reset", "named-write-failure",
"named-retry-stereo")
def main():

201
tests/test_audio_source.py Normal file
View File

@@ -0,0 +1,201 @@
"""The controller speaker's sound classes (host/audio_source.h): which asset a wave buffer plays, and its class.
Compiles host/audio_source.h as it is over archives made up here (no game file): a BARS table with AMTA and BWAV
blocks in the layout the game's have, wave buffers at their channels' samples, and the names the classes go by.
py -3 -I -B tests/test_audio_source.py [--cc gcc]
"""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = r"""
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "audio_source.h"
static void put32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8), p[2] = (uint8_t)(v >> 16), p[3] = (uint8_t)(v >> 24); }
static void put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v, p[1] = (uint8_t)(v >> 8); }
/* A BWAV at b: its channels' samples follow the tables, 0x40-aligned, `each` bytes a channel. Its size. */
static size_t bwav(uint8_t *b, uint32_t crc, unsigned channels, size_t each) {
memcpy(b, "BWAV", 4), put16(b + 4, 0xfeff), put16(b + 6, 1), put32(b + 8, crc), put16(b + 0x0c, 1), put16(b + 0x0e, (uint16_t)channels);
size_t data = (0x10 + channels * 0x4c + 0x3f) & ~(size_t)0x3f;
for (unsigned ch = 0; ch < channels; ch++, data += each) {
uint8_t *info = b + 0x10 + ch * 0x4c;
put16(info, 1), put32(info + 4, 48000), put32(info + 0x30, (uint32_t)data), put32(info + 0x34, (uint32_t)data);
memset(b + data, 0x5a, each);
}
return data;
}
/* An AMTA at b with junk and the name inside. Its size. */
static size_t amta(uint8_t *b, const char *name, int junk) {
memcpy(b, "AMTA", 4), put16(b + 4, 0xfeff), put16(b + 6, 5);
size_t at = 0x34;
if (junk) memcpy(b + at, "8wRA", 4), at += 4; /* (bytes of the block that read as name characters, before the name) */
else b[at++] = 0;
memcpy(b + at, name, strlen(name) + 1), at += strlen(name) + 1;
at = (at + 3) & ~(size_t)3;
put32(b + 8, (uint32_t)at);
return at;
}
int main(void) {
/* ---- the classes, by the names of the game's archives and assets */
assert(audio_source_class("NV_USen_Custom_Navi", "NV_USen_Custom_Navi_Attention01") == AUDIO_SOURCE_NAVI_VOICE);
assert(audio_source_class("NV_JPja_Custom_Navi", "NV_JPja_Custom_Navi_LockOnEnemy02") == AUDIO_SOURCE_NAVI_VOICE);
assert(audio_source_class("NV_USen_Custom_Zelda", "NV_USen_Custom_Zelda_Laugh00") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Npc_Navi", "SE_Navi_LockOn") == AUDIO_SOURCE_TARGET);
assert(audio_source_class("Npc_Navi", "SE_Navi_LockOff00") == AUDIO_SOURCE_TARGET);
assert(audio_source_class("Npc_Navi", "SE_Navi_LockOnEnemy") == AUDIO_SOURCE_TARGET);
assert(audio_source_class("Npc_Navi", "SE_Navi_FlyApproach") == AUDIO_SOURCE_NAVI_SOUND);
assert(audio_source_class("Npc_Navi", "SE_Navi_Emote03") == AUDIO_SOURCE_NAVI_SOUND);
assert(audio_source_class("Npc_Navi", "SE_Dm_TimeTemple_0065_Navi_MV_01") == AUDIO_SOURCE_NONE); /* a cutscene's 5.1 bed */
assert(audio_source_class("Dm_Npc_Navi", "ASE_FDm_Kokiri_0060_Navi_MV_01") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Ocarina", "Ocarina_HighF") == AUDIO_SOURCE_OCARINA);
assert(audio_source_class("Ocarina", "PlayNote") == AUDIO_SOURCE_OCARINA);
assert(audio_source_class("Obj_Ocarina_Time_A_01", "x") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Armor_Child_AgonyStone", "SE_AgonyStone_Near00") == AUDIO_SOURCE_AGONY);
assert(audio_source_class("Fairy", "SE_Obj_Fairy_Flying02") == AUDIO_SOURCE_FAIRY);
assert(audio_source_class("RevivalFairy", "SE_Fairy_Fly00") == AUDIO_SOURCE_FAIRY);
assert(audio_source_class("Npc_Fairy_Saria", "x") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Obj_Rupee_Green", "SE_Obj_Rupee_Land00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("Obj_Heart_Piece", "SE_Heart_Piece_Land_01") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("DropItem", "SE_Obj_DropStart00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("Item_Bomb", "SE_Item_Bomb_Explosion_Water01") == AUDIO_SOURCE_ITEM);
assert(audio_source_class("Weapon_Range_SlingShot", "SE_Weapon_Range_SlingShot_Release_00") == AUDIO_SOURCE_ITEM);
assert(audio_source_class("Weapon_Sword_Master", "x") == AUDIO_SOURCE_NONE);
assert(audio_source_class("UI_Static.Product.111", "SE_UI_PickUp_Rupee00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("UI_Static.Product.111", "SE_Sys_KeySmallGet_00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("UI_Static.Product.111", "8wRASE_Sys_PeaceOfHeart_5") == AUDIO_SOURCE_PICKUP); /* metadata before the name */
assert(audio_source_class("UI_Static.Product.111", "SE_Sys_Cursor00") == AUDIO_SOURCE_UI);
assert(audio_source_class("UI_Static.Product.111", "SE_UI_EquipmentMenu_Decide_Armor") == AUDIO_SOURCE_UI);
assert(audio_source_class("UI_Static.Product.111", "NV_FrogTenor_Sad01") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Player", "SE_Player_Child_LeafTrack02") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Player", "SE_Sys_HeartAlert") == AUDIO_SOURCE_LOW_HEALTH);
assert(audio_source_class("Player_Adult", "SE_Sys_HeartAlert") == AUDIO_SOURCE_NONE);
assert(audio_source_class("Obj_Token_Gold", "SE_Obj_Token_Gold_Get00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("Obj_MagicJar_Small", "SE_Obj_MagicJar_Land00") == AUDIO_SOURCE_PICKUP);
assert(audio_source_class("Weapon_FishingRod", "SE_Weapon_FishingRod_ReelLoop_00") == AUDIO_SOURCE_FISHING);
assert(audio_source_class("Weapon_SinkingLure", "x") == AUDIO_SOURCE_FISHING);
assert(audio_source_class("Animal_Fish_Bass", "SE_Animal_Fish_Bass_Bite_Underwater_S_00") == AUDIO_SOURCE_FISHING);
assert(audio_source_class("Animal_Fish_Bass", "SE_Animal_Fish_Bass_Hooking_00") == AUDIO_SOURCE_FISHING);
assert(audio_source_class("Animal_Fish_Bass", "SE_Animal_Fish_Bass_WaterIn_00") == AUDIO_SOURCE_NONE); /* (its splashes: the world's) */
assert(audio_source_class("Weapon_Bottle_Bug", "x") == AUDIO_SOURCE_BOTTLE);
assert(audio_source_class("Obj_Bottle_Letter", "x") == AUDIO_SOURCE_NONE);
static const char *const archives[] = {"NV_USen_Custom_Navi", "Npc_Navi", "Dm_Npc_Navi", "Ocarina", "Armor_Child_AgonyStone", "Fairy",
"RevivalFairy", "Obj_Rupee_Green", "Obj_Heart_Piece", "DropItem", "Item_Bomb", "Weapon_Range_Hookshot", "UI_Static.Product.111",
"Player", "Obj_Token_Gold", "Obj_MagicJar_Large", "Weapon_FishingRod", "Weapon_Lure", "Animal_Fish_Bass", "Weapon_Bottle_Poe"};
for (size_t i = 0; i < sizeof archives / sizeof *archives; i++) assert(audio_source_wants(archives[i]));
assert(!audio_source_wants("Player_Adult") && !audio_source_wants("NV_USen_Custom_Zelda") && !audio_source_wants("BGM_Static"));
/* ---- an archive: four assets, one with no wave, as the game's are laid out */
enum { N = 0x20000 };
uint8_t *bars = calloc(1, N);
static const char *const names[] = {"SE_Navi_LockOn", "SE_Navi_FlyApproach", "SE_Dm_Kokiri_0060_Navi_02", "SE_Navi_Emote00"};
const uint32_t crcs[] = {0xb2db631e, 0x7da57872, 0xa4a6a6ef, 0x62e5b743};
const unsigned channels[] = {1, 2, 6, 0};
memcpy(bars, "BARS", 4), put16(bars + 8, 0xfeff), put16(bars + 0x0a, 0x102), put32(bars + 0x0c, 4);
size_t at = 0x10 + 4 * 4 + 4 * 8, wave[4], data[4][8];
uint32_t amtas[4];
for (int i = 0; i < 4; i++) amtas[i] = (uint32_t)at, at += amta(bars + at, names[i], i == 1);
for (int i = 0; i < 4; i++) {
put32(bars + 0x10 + 16 + 8 * i, amtas[i]);
if (!channels[i]) { put32(bars + 0x10 + 16 + 8 * i + 4, 0xffffffffu); continue; }
at = (at + 0x3f) & ~(size_t)0x3f;
wave[i] = at;
put32(bars + 0x10 + 16 + 8 * i + 4, (uint32_t)at);
const size_t first = (0x10 + channels[i] * 0x4c + 0x3f) & ~(size_t)0x3f;
for (unsigned ch = 0; ch < channels[i]; ch++) data[i][ch] = at + first + ch * 0x1c40;
at += bwav(bars + at, crcs[i], channels[i], 0x1c40);
}
assert(at <= N);
put32(bars + 4, (uint32_t)at);
assert(data[0][0] == wave[0] + 0x80 && data[1][0] == wave[1] + 0xc0 && data[2][0] == wave[2] + 0x200); /* the game's offsets */
char name[128];
audio_source_asset_name(bars + amtas[1], audio_source_u32(bars + amtas[1] + 8), name, sizeof name);
assert(strstr(name, "SE_Navi_FlyApproach"));
audio_source_asset_name(bars + amtas[0], audio_source_u32(bars + amtas[0] + 8), name, sizeof name);
assert(!strcmp(name, "SE_Navi_LockOn"));
audio_source_asset_name(bars + amtas[0], audio_source_u32(bars + amtas[0] + 8), name, 5);
assert(!strcmp(name, "SE_N"));
static AudioSourceTable table;
assert(audio_source_add_bars(&table, "Npc_Navi", bars, at) == 2); /* the cutscene's is not classed; one has no wave */
assert(table.count == 2 && !table.full);
assert(audio_source_get(&table, crcs[0]) == AUDIO_SOURCE_TARGET);
assert(audio_source_get(&table, crcs[1]) == AUDIO_SOURCE_NAVI_SOUND);
assert(audio_source_get(&table, crcs[2]) == AUDIO_SOURCE_NONE && audio_source_get(&table, crcs[3]) == AUDIO_SOURCE_NONE);
assert(audio_source_get(&table, 0) == AUDIO_SOURCE_NONE);
assert(audio_source_add_bars(&table, "Npc_Navi", bars, at) == 2 && table.count == 2); /* read twice: no second entry */
assert(audio_source_add_bars(&table, "Player", bars, at) == 0);
/* ---- a wave buffer -> its asset: every channel's start, and nothing else */
uint32_t crc = 0;
for (int i = 0; i < 3; i++)
for (unsigned ch = 0; ch < channels[i]; ch++) {
crc = 0;
assert(audio_source_find(bars + data[i][ch], data[i][ch], &crc) && crc == crcs[i]);
}
assert(!audio_source_find(bars + data[0][0] + 0x40, data[0][0] + 0x40, &crc)); /* the middle of the samples */
assert(!audio_source_find(bars + data[2][1] - 0x40, data[2][1] - 0x40, &crc));
assert(!audio_source_find(bars + data[0][0] + 1, data[0][0] + 1, &crc)); /* off the alignment */
assert(!audio_source_find(bars + data[0][0], 0x40, &crc)); /* the header may not be read */
assert(!audio_source_find(bars + data[0][0], 0, &crc));
uint8_t *stream = calloc(1, 0x20000); /* a streamed sound's buffer: no header at all */
assert(!audio_source_find(stream + 0x20000 - 0x100, 0x20000 - 0x100, &crc));
assert(audio_source_get(&table, crcs[0]) == AUDIO_SOURCE_TARGET);
/* ---- bytes that are not such an archive add nothing */
static AudioSourceTable none;
uint8_t *bad = malloc(at);
memcpy(bad, bars, at), bad[0] = 'X';
assert(audio_source_add_bars(&none, "Npc_Navi", bad, at) == -1);
memcpy(bad, bars, at), put32(bad + 0x0c, 0x7fffffff); /* a count past the file */
assert(audio_source_add_bars(&none, "Npc_Navi", bad, at) == -1);
memcpy(bad, bars, at), put32(bad + 0x10 + 16 + 4, (uint32_t)at + 0x1000); /* a wave past the file */
assert(audio_source_add_bars(&none, "Npc_Navi", bad, at) == -1);
memcpy(bad, bars, at), put32(bad + 0x10 + 16 + 8, 0x18); /* metadata that is not AMTA */
assert(audio_source_add_bars(&none, "Npc_Navi", bad, at) == -1);
memcpy(bad, bars, at), put16(bad + wave[1] + 0x0e, 200); /* a wave with 200 channels */
assert(audio_source_add_bars(&none, "Npc_Navi", bad, at) == -1);
assert(audio_source_add_bars(&none, "Npc_Navi", bars, 8) == -1);
assert(none.count == 0);
/* ---- a full table leaves assets out and says so; what is in stays found */
static AudioSourceTable full;
for (uint32_t i = 1; i <= AUDIO_SOURCE_MAX + 10; i++) audio_source_put(&full, i * 0x9e3779b1u, AUDIO_SOURCE_ITEM);
assert(full.count == AUDIO_SOURCE_MAX && full.full == 10);
for (uint32_t i = 1; i <= AUDIO_SOURCE_MAX; i++) assert(audio_source_get(&full, i * 0x9e3779b1u) == AUDIO_SOURCE_ITEM);
assert(audio_source_get(&full, (AUDIO_SOURCE_MAX + 1) * 0x9e3779b1u) == AUDIO_SOURCE_NONE);
audio_source_put(&full, 5, AUDIO_SOURCE_NONE), audio_source_put(&full, 5, AUDIO_SOURCE_CLASSES);
assert(full.full == 10);
free(bars), free(stream), free(bad);
puts("audio source: ok");
return 0;
}
"""
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default=os.environ.get("CC", "cc"))
args = parser.parse_args()
with tempfile.TemporaryDirectory() as tmp:
source = Path(tmp) / "audio_source_test.c"
source.write_text(FIXTURE, encoding="utf-8")
exe = Path(tmp) / ("audio_source_test.exe" if os.name == "nt" else "audio_source_test")
subprocess.run([args.cc, "-std=c11", "-Wall", "-Wextra", "-Werror", "-fsanitize=address,undefined" if os.name != "nt" else "-O1",
"-I", str(ROOT / "host"), str(source), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,249 @@
"""The controller speaker reads the player's sound archives at the start (host/audio_source.c), and a wave buffer in
the game's memory gets its asset's class.
Compiles host/audio_source.c as it is, with third_party/zstd's decoder, over a RomFS folder made up here (no game
file): Pack/ZsDic.pack.zs holding a dictionary in a SARC, and Sound/Resource/*.bars.zs as Zstandard frames of raw
blocks, written here with the standard library (the dictionary still loaded and handed to the decoder, as the game's). The "game's memory" is an array with one archive in it.
py -3 -I -B tests/test_audio_source_load.py [--cc gcc] (standard library only: the frames are written here)
"""
import argparse
import os
import shutil
import struct
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
ZSTD = ROOT / "third_party/zstd/lib"
ZSTD_SOURCES = ["common/entropy_common.c", "common/error_private.c", "common/fse_decompress.c", "common/xxhash.c", "common/zstd_common.c",
"decompress/huf_decompress.c", "decompress/zstd_ddict.c", "decompress/zstd_decompress.c", "decompress/zstd_decompress_block.c"]
HOS_H = r'''#pragma once
#include <stdint.h>
#include <stddef.h>
extern unsigned char guest[0x40000];
#define GUEST 0x1000000000ull
#define GP(a) ((void *)(guest + ((a) - GUEST)))
void hos_log(const char *fmt, ...);
void *hos_guest_range(uint64_t addr, uint64_t size);
'''
MAIN = r'''
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hos.h"
#include "audio_source.h"
unsigned char guest[0x40000];
const char *hos_romfs_dir;
static char logged[4096];
void hos_log(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
const size_t at = strlen(logged);
vsnprintf(logged + at, sizeof logged - at - 2, fmt, ap);
va_end(ap);
strcat(logged, "\n");
}
static uint64_t mapped_from = GUEST;
static uint64_t asked_most; /* (the most memory a search asked about) */
static int far_asks; /* (searches past where a first channel can start: as far as a later channel's header) */
void *hos_guest_range(uint64_t addr, uint64_t size) { /* (Triforce: the guest window, as host/hos.h's) */
if (size > asked_most) asked_most = size;
if (size > 0x280) far_asks++;
return addr >= mapped_from && addr + size <= GUEST + sizeof guest ? GP(addr) : NULL;
}
void hos_audio_source_load(void);
int hos_audio_source_of(uint64_t data, uint32_t *crc);
const char *hos_audio_source_name(int cls);
int main(int argc, char **argv) {
assert(argc == 4);
char romfs[1024];
if (!strcmp(argv[3], "full")) {
snprintf(romfs, sizeof romfs, "%s/romfs_\xe9\x9b\xaa", argv[1]);
hos_romfs_dir = romfs;
} else hos_romfs_dir = argv[1];
FILE *f = fopen(argv[2], "rb"); /* the archive as the game holds it, put at 0x10040 of its memory */
assert(f);
const size_t n = fread(guest + 0x10040, 1, sizeof guest - 0x10040, f);
fclose(f);
assert(n > 0x100);
const uint64_t bars = GUEST + 0x10040;
uint32_t crc = 0;
assert(hos_audio_source_of(bars + 0x200 + 0x80, &crc) == -1); /* before the archives are read: nothing is classed */
hos_audio_source_load();
fputs(logged, stdout);
if (!strcmp(argv[3], "none")) { /* a folder without the archives: no classes, and it says so once */
assert(strstr(logged, "audio: 0 sounds classed from 0 archives"));
assert(hos_audio_source_of(bars + 0x200 + 0x80, &crc) == AUDIO_SOURCE_NONE);
puts("audio source load (no archives): ok");
return 0;
}
assert(strstr(logged, "audio: 6 sounds classed from 4 archives"));
assert(strstr(logged, "Navi's voice 1") && strstr(logged, "Navi's sounds 1") && strstr(logged, "targeting 1") &&
strstr(logged, "ocarina 2") && strstr(logged, "pick-ups 0") && strstr(logged, "low health 1"));
assert(strstr(logged, "Item_Broken.bars.zs is not read as a sound archive"));
assert(!strstr(logged, "Player_Adult")); /* an archive nothing is classed from is not opened */
assert(hos_audio_source_of(GUEST + 0x30000, &crc) == -1); /* a streamed sound's buffer: searched far once */
asked_most = 0;
assert(hos_audio_source_of(GUEST + 0x30000, &crc) == -1); /* the ring come round to it again */
assert(asked_most <= 0x280); /* looked at only where a first channel can start, not 64 KB of memory a buffer */
/* Npc_Navi in the game's memory: SE_Navi_LockOn at 0x200, SE_Navi_FlyApproach (2 channels) at 0x2000, a cutscene's at 0x6000 */
const uint64_t lock_on = bars + 0x200 + 0x80, fly = bars + 0x2000 + 0xc0, fly2 = fly + 0x1c40;
/* a mono sound (a footstep's kind) played again and again: found right behind its header, never searched far */
far_asks = 0;
for (int i = 0; i < 100; i++) assert(hos_audio_source_of(lock_on, &crc) == AUDIO_SOURCE_TARGET && crc == 0xb2db631e);
assert(far_asks == 0);
/* a later channel queued before its wave's first: found as far as main looked, once; then by its address, every play */
for (int i = 0; i < 10; i++) assert(hos_audio_source_of(fly2, &crc) == AUDIO_SOURCE_NAVI_SOUND && crc == 0x7da57872);
assert(far_asks == 1);
assert(hos_audio_source_of(fly, &crc) == AUDIO_SOURCE_NAVI_SOUND); /* its first channel: from the same header */
assert(far_asks == 1);
/* a streamed sound's ring (no header in front of its buffers): each of its places searched far once, however often it
comes round (GUEST + 0x30000 was searched above) */
for (int round = 0; round < 100; round++)
for (int i = 0; i < 8; i++) assert(hos_audio_source_of(GUEST + 0x30000 + i * 0x1000, &crc) == -1);
assert(far_asks == 1 + 7);
/* what was kept pushed out by many other places: the later channel at its sound's start found again, searched once */
for (int i = 0; i < 2048; i++) (void)hos_audio_source_of(GUEST + 0x28000 + (uint64_t)i * 0x40, &crc);
const int before_evicted = far_asks;
for (int i = 0; i < 10; i++) assert(hos_audio_source_of(fly2, &crc) == AUDIO_SOURCE_NAVI_SOUND);
assert(far_asks <= before_evicted + 1);
assert(hos_audio_source_of(bars + 0x6000 + 0x80, &crc) == AUDIO_SOURCE_NONE && crc == 0xa4a6a6ef); /* found, not classed */
assert(hos_audio_source_of(lock_on + 0x40, &crc) == -1); /* the middle of a sound: no asset's start */
assert(hos_audio_source_of(0, &crc) == -1);
assert(hos_audio_source_of(GUEST + 0x40, &crc) == -1); /* too near the start of the mapped memory to have a header */
mapped_from = bars + 0x200; /* memory mapped from the header on: still found */
assert(hos_audio_source_of(lock_on, &crc) == AUDIO_SOURCE_TARGET);
mapped_from = bars + 0x200 + 0x40; /* the header itself not mapped: not read */
assert(hos_audio_source_of(lock_on, &crc) == -1);
assert(!strcmp(hos_audio_source_name(AUDIO_SOURCE_TARGET), "targeting") && !strcmp(hos_audio_source_name(99), "?"));
logged[0] = 0;
hos_audio_source_load(); /* read once */
assert(!logged[0]);
puts("audio source load: ok");
return 0;
}
'''
def bwav(crc, channels, each=0x1c40):
first = (0x10 + channels * 0x4c + 0x3f) & ~0x3f
head = b"BWAV" + struct.pack("<HHIHH", 0xfeff, 1, crc, 1, channels)
for ch in range(channels):
at = first + ch * each
head += struct.pack("<HHIII", 1, 0, 48000, 14336, 14336) + bytes(32) + struct.pack("<II", at, at) + bytes(0x4c - 0x38)
return head.ljust(first, b"\0") + bytes((i * 7) & 0xff for i in range(channels * each))
def amta(name):
body = bytes(0x28) + name.encode() + b"\0"
body = body.ljust((len(body) + 3) & ~3, b"\0")
return b"AMTA" + struct.pack("<HHI", 0xfeff, 5, 12 + len(body)) + body
def bars(assets, wave_at=None):
"""assets: (name, crc, channels or 0 for no wave); wave_at: fixed offsets for the waves"""
count = len(assets)
out = bytearray(b"BARS" + struct.pack("<IHHI", 0, 0xfeff, 0x102, count) + bytes(4 * count) + bytes(8 * count))
pairs = []
metas = []
for name, _, _ in assets:
metas.append(len(out))
out += amta(name)
for i, (_, crc, channels) in enumerate(assets):
if not channels:
pairs.append((metas[i], 0xffffffff))
continue
at = wave_at[i] if wave_at else (len(out) + 0x3f) & ~0x3f
assert at >= len(out)
out += bytes(at - len(out))
pairs.append((metas[i], at))
out += bwav(crc, channels)
for i, (a, w) in enumerate(pairs):
struct.pack_into("<II", out, 0x10 + 4 * count + 8 * i, a, w)
struct.pack_into("<I", out, 4, len(out))
return bytes(out)
def sarc(files):
names = b""
nodes = b""
data = b""
for name, content in files:
nodes += struct.pack("<IIII", 0, 0x01000000 | (len(names) // 4), len(data), len(data) + len(content))
names += (name.encode() + b"\0").ljust((len(name) + 4) & ~3, b"\0")
data += content.ljust((len(content) + 3) & ~3, b"\0")
head = 0x14 + 0x0c + len(nodes) + 8 + len(names)
return (b"SARC" + struct.pack("<HHIII", 0x14, 0xfeff, head + len(data), head, 0x100) + b"SFAT" + struct.pack("<HHI", 0x0c, len(files), 0x65)
+ nodes + b"SFNT" + struct.pack("<HH", 8, 0) + names + data)
def zstd_frame(content):
"""content as a Zstandard frame (RFC 8878) of raw blocks, written here with the standard library only: a single
segment, its size in the header, no dictionary id and no checksum. Any decoder reads it, with a dictionary or without."""
out = struct.pack("<IB", 0xFD2FB528, (2 << 6) | (1 << 5)) + struct.pack("<I", len(content))
step = 128 * 1024
for at in range(0, max(len(content), 1), step):
part = content[at:at + step]
last = at + step >= len(content)
out += struct.pack("<I", int(last) | (0 << 1) | (len(part) << 3))[:3] + part
return out
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default=os.environ.get("CC", "cc"))
args = parser.parse_args()
navi = bars([("SE_Navi_LockOn", 0xb2db631e, 1), ("SE_Navi_FlyApproach", 0x7da57872, 2), ("SE_Dm_Kokiri_0060_Navi_02", 0xa4a6a6ef, 1),
("SE_Navi_Emote00", 0x62e5b743, 0)], wave_at=[0x200, 0x2000, 0x6000, None])
archives = {
"Npc_Navi": navi,
"NV_USen_Custom_Navi": bars([("NV_USen_Custom_Navi_Attention01", 0x0c6a85b0, 1)]),
"Ocarina": bars([("Ocarina_G", 0xa96bbafa, 1), ("PlayNote", 0x0211f355, 3)]),
"Player_Adult": bars([("SE_Player_Child_LeafTrack02", 0xa03bfd8c, 1)]),
"Player": bars([("SE_Player_Child_LeafTrack03", 0xa03bfd8d, 1), ("SE_Sys_HeartAlert", 0x5eed1e55, 1)]),
}
samples = [navi[i:i + 0x400] for i in range(0, len(navi), 0x400)] * 4
dictionary = b"".join(samples)[:0x4000] # (a raw-content dictionary: its bytes as they are, as the game's)
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
romfs = tmp / "romfs_雪"
(romfs / "Pack").mkdir(parents=True)
(romfs / "Sound/Resource").mkdir(parents=True)
(romfs / "Pack/ZsDic.pack.zs").write_bytes(zstd_frame(sarc([("pack.zsdic", b"other"), ("zs.zsdic", dictionary)])))
for name, content in archives.items():
(romfs / "Sound/Resource" / (name + ".bars.zs")).write_bytes(zstd_frame(content))
(romfs / "Sound/Resource/Item_Broken.bars.zs").write_bytes(zstd_frame(b"not an archive at all"))
(romfs / "Sound/Resource/Item_Notes.txt").write_bytes(b"x")
empty = tmp / "empty"
empty.mkdir()
(tmp / "navi.bars").write_bytes(navi)
# (the source beside a hos.h of the test's: the real one brings the whole runtime)
inc = tmp / "host"
inc.mkdir()
(inc / "hos.h").write_text(HOS_H, encoding="utf-8")
for name in ("audio_source.c", "audio_source.h"):
shutil.copy(ROOT / "host" / name, inc / name)
(tmp / "main.c").write_text(MAIN, encoding="utf-8")
exe = tmp / ("audio_source_load.exe" if os.name == "nt" else "audio_source_load")
# (-I host after the test's own: audio_source.c's "../third_party/zstd/lib/zstd.h" from there)
command = [args.cc, "-std=gnu11", "-O1", "-w", "-I", str(inc), "-I", str(ROOT / "host"), "-I", str(ZSTD), "-DZSTD_DISABLE_ASM"]
sources = [str(tmp / "main.c"), str(inc / "audio_source.c")] + [str(ZSTD / s) for s in ZSTD_SOURCES]
if os.name != "nt":
command += ["-I", str(ROOT / "host/posix"), "-D_GNU_SOURCE"]
sources.append(str(ROOT / "host/posix/win32_posix.c"))
subprocess.run(command + sources + ["-o", str(exe)] + ([] if os.name == "nt" else ["-lpthread", "-lm", "-ldl"]), check=True)
env = {k: v for k, v in os.environ.items() if not k.startswith("HOS_AUDIO_SOURCE")}
subprocess.run([str(exe), str(tmp), str(tmp / "navi.bars"), "full"], check=True, env=env)
subprocess.run([str(exe), str(empty), str(tmp / "navi.bars"), "none"], check=True, env=env)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,90 @@
"""Auto's speakers follow the default output's speaker positions, not its channel count (host/nn_audio.c).
The real au_layout_channels from host/nn_audio.c is compiled with a small driver and asked about mix formats Windows
reports: a device with more channels than 5.1 speakers (an audio interface's 8 outputs with channel mask 0, quad, a
format with no mask) counts as stereo, so the game's centre and rear sounds are not sent to outputs nothing listens to.
No device is opened.
python -I -B tests/test_audio_speaker_layout.py [--cxx clang++] (--cxx cl: MSVC, from a developer prompt)
"""
import argparse
import os
from pathlib import Path
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = r"""
#include <cstdio>
#include <cstdlib>
HELPER
int main(int argc, char **argv) {
int failed = 0;
for (int i = 1; i + 3 < argc; i += 4) {
const int channels = atoi(argv[i]), extensible = atoi(argv[i + 1]), want = atoi(argv[i + 3]);
const unsigned long mask = strtoul(argv[i + 2], nullptr, 0);
const int got = au_layout_channels(channels, extensible, mask);
if (got != want) {
fprintf(stderr, "FAIL: %d channels, extensible %d, mask %#lx: %d (want %d)\n", channels, extensible, mask, got, want);
failed = 1;
}
}
return failed;
}
"""
# (channels, WAVE_FORMAT_EXTENSIBLE, channel mask, the channels Auto counts)
CASES = (
(2, 1, 0x3, 2), # stereo
(2, 0, 0x0, 2), # stereo, plain WAVEFORMATEX
(1, 1, 0x4, 2), # mono
(6, 1, 0x3F, 6), # 5.1 (back)
(6, 1, 0x60F, 6), # 5.1 (side)
(8, 1, 0x63F, 8), # 7.1
(8, 1, 0x0, 2), # an audio interface's 8 outputs, no speaker named (a Scarlett 18i8)
(18, 1, 0x0, 2), # a bigger interface
(4, 1, 0x33, 2), # quad: no centre
(4, 1, 0x107, 2), # FL FR FC BC: one channel behind
(6, 1, 0x3B, 2), # 5.1 without its centre
(6, 0, 0x0, 2), # more than two channels without a mask
(8, 1, 0xFF, 8), # 7.1 wide (front centres): has 5.1 in it
)
def between(text, start, end):
i = text.index(start)
return text[i:text.index(end, i)]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
audio = (ROOT / "host/nn_audio.c").read_text(encoding="utf-8")
helper = between(audio, "/* (Triforce) The channels of a mix format", "static int au_device_channels(void) {")
assert "static int au_layout_channels(" in helper, "host/nn_audio.c has no au_layout_channels"
# (the device's channels go through it: a mix format's count alone was the bug)
device = between(audio, "static int au_device_channels(void) {", "#else")
assert "au_layout_channels(mix->nChannels" in device, "au_device_channels does not ask au_layout_channels"
with tempfile.TemporaryDirectory(prefix="audio-speaker-layout-") as tmp:
work = Path(tmp)
source, exe = work / "fixture.cpp", work / "fixture.exe"
source.write_text(FIXTURE.replace("HELPER", helper), encoding="utf-8")
if os.path.splitext(os.path.basename(args.cxx))[0].lower() == "cl":
command = [args.cxx, "/nologo", "/std:c++17", "/W4", "/WX", "/EHsc", str(source), "/Fe:" + str(exe),
"/Fo:" + str(work) + os.sep]
else:
command = [args.cxx, "-std=c++17", "-Wall", "-Wextra", "-Werror", str(source), "-o", str(exe)]
subprocess.run(command, check=True, cwd=work)
cases = [arg for channels, extensible, mask, want in CASES
for arg in (str(channels), str(extensible), hex(mask), str(want))]
subprocess.run([str(exe)] + cases, check=True)
print("PASS: Auto counts 5.1 speakers, not channels: an audio interface's outputs, quad or no mask are stereo")
if __name__ == "__main__":
main()

View File

@@ -47,6 +47,12 @@ static void release_wb(Voice *voice, uint64_t buffer) { (void)voice; (void)buffe
"""]
actual.extend(helper.block(source, marker) for marker in (
"static void put_handle(", "static int get_handle(", "static int voice_index(", "static Voice *voice_of("))
# (the update queue's apply also owns the Aux effects' state: their declarations and reset, as the file has them)
aux_start = source.index("typedef struct {", source.index("/* ---- Aux: the game supplies the processing"))
aux = [next(line for line in source.splitlines() if line.startswith("#define MAX_EFFECTS")),
source[aux_start:source.index("static int aux_on(void) {", aux_start)],
helper.block(source, "static void aux_ring_reset("), helper.block(source, "static void aux_reset(")]
actual.extend(aux)
actual.extend([queue, helper.block(source, "static void apply("), helper.block(source, "static void submit("),
helper.block(source, "static void commit("), helper.block(runtime, "A64_WEAK void a64_unimplemented(")])
actual.append(helper.block(source, "HLE(" + LEGACY + ")"))

View File

@@ -51,7 +51,22 @@ static int16_t adpcm_sample(Voice *v, const WB *w, int64_t s) { (void)v; (void)w
"""]
actual.extend(helper.block(source, marker) for marker in (
"static void put_handle(", "static int get_handle(", "static int voice_index(", "static Voice *voice_of(",
"static WB read_wb(", "static void release_wb(", "static int next_source_frame("))
"static WB read_wb(", "static int wb_in_guest(", "static void release_wb(", "static int next_source_frame("))
# (the update queue's apply also owns the Aux effects' state: their declarations and reset, as the file has them)
aux_start = source.index("typedef struct {", source.index("/* ---- Aux: the game supplies the processing"))
aux = [next(line for line in source.splitlines() if line.startswith("#define MAX_EFFECTS")),
source[aux_start:source.index("static int aux_on(void) {", aux_start)],
helper.block(source, "static void aux_ring_reset("), helper.block(source, "static void aux_reset(")]
actual.extend(aux)
actual.append("""/* ((Triforce) the controller speaker (host/pad_speaker.c, host/audio_source.h), off: nothing classed, nothing sent */
enum { AUDIO_SOURCE_NONE, AUDIO_SOURCE_NAVI_VOICE, AUDIO_SOURCE_NAVI_SOUND, AUDIO_SOURCE_TARGET, AUDIO_SOURCE_OCARINA };
enum { HOS_PAD_SPEAKER_OFF = 0, HOS_PAD_SPEAKER_ONLY = 1, HOS_PAD_SPEAKER_BOTH = 2 };
static int hos_pad_speaker_active(void) { return 0; }
static void hos_audio_source_load_async(void) {}
static int hos_audio_source_ready(void) { return 0; }
static int hos_audio_source_of(uint64_t data, uint32_t *crc) { (void)data, (void)crc; return -1; }
static int hos_audio_source_trace(void) { return 0; }
static const char *hos_audio_source_name(int cls) { (void)cls; return "?"; }""")
actual.extend([queue, helper.block(source, "static void apply("), helper.block(source, "static void submit("),
helper.block(source, "static void commit(")])
actual.extend(helper.block(source, "HLE(" + name + ")") for name in (APPEND, RELEASED, COUNT, STATE))

134
tests/test_auto_settings.py Normal file
View File

@@ -0,0 +1,134 @@
"""Compile and run the Graphics tab's Auto (this PC) rules (gpu/vk/auto_settings.h; no game, no GPU), and check that the menu
still uses them: the row is Off by default, a row it sets changed by hand turns it Off, and the replay's windows reach its tuning.
python -I -B tests/test_auto_settings.py [--cxx g++]
"""
import argparse
import re
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cxx", "g++"]
ROOT = Path(__file__).resolve().parents[1]
C = r'''
#include "auto_settings.h"
#include "upscaler_rows.h"
#include <cstdio>
#include <cstdlib>
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL:%d %s\n", __LINE__, #x); std::exit(1); } } while (0)
using namespace auto_settings;
static Hardware card(int vendor, unsigned mb, bool dlss = false, bool fsr4 = false) {
Hardware h;
h.vendor = vendor, h.vram_mb = mb, h.dlss_runs = dlss, h.fsr4_runs = fsr4, h.ram_mb = 32768, h.threads = 16;
return h;
}
int main() {
namespace ur = mkwvk::upscaler_rows;
// (the menu's values, kept here so the rules compile on their own)
CHECK(GAME == ur::GAME && DLSS == ur::DLSS && FSR3 == ur::FSR3 && FSR4 == ur::FSR4);
CHECK(ur::percent(RES_FULL) == 100 && ur::percent(RES_75) == 75 && ur::percent(RES_QUALITY) == 67 &&
ur::percent(RES_PERFORMANCE) == 50 && ur::percent(RES_BALANCED) == 58 && ur::percent(RES_ULTRA_PERFORMANCE) == 33);
// the tiers by memory, and what holds a card at 1
CHECK(tier_of(card(NVIDIA, 4096)) == 1 && tier_of(card(NVIDIA, 6144)) == 2 && tier_of(card(NVIDIA, 8192)) == 3);
CHECK(tier_of(card(NVIDIA, 11264)) == 3 && tier_of(card(NVIDIA, 12282)) == 4 && tier_of(card(NVIDIA, 16376)) == 5);
Hardware igpu = card(INTEL, 16384);
igpu.integrated = true;
CHECK(tier_of(igpu) == 1);
Hardware nomesh = card(AMD, 8192);
nomesh.mesh_native = false;
CHECK(tier_of(nomesh) == 1);
Hardware lowram = card(NVIDIA, 16384);
lowram.ram_mb = 8192;
CHECK(tier_of(lowram) == 2);
// the upscaler by the card's maker, where it runs
Choice c = choose(card(NVIDIA, 12282, true));
CHECK(c.upscaler == DLSS && c.resolution == RES_QUALITY && c.shadow_res == 1 && c.grass == 1 && c.tex_detail == 0);
c = choose(card(NVIDIA, 8192, true));
CHECK(c.upscaler == DLSS && c.resolution == RES_BALANCED && c.shadow_res == 0 && c.grass == 0);
c = choose(card(NVIDIA, 8192, false));
CHECK(c.upscaler == GAME && c.resolution == RES_FULL);
c = choose(card(AMD, 16304, false, true));
CHECK(c.upscaler == FSR4 && c.resolution == RES_QUALITY && c.shadow_res == 2 && c.grass == 2);
c = choose(card(AMD, 6144, true, false)); // (DLSS is NVIDIA's: an AMD card never gets it)
CHECK(c.upscaler == GAME && c.resolution == RES_75);
c = choose(card(NVIDIA, 4096, true)); // (tier 1: the game's own at 50%)
CHECK(c.upscaler == GAME && c.resolution == RES_PERFORMANCE);
igpu.threads = 4;
c = choose(igpu);
CHECK(c.upscaler == GAME && c.resolution == RES_ULTRA_PERFORMANCE);
Hardware few = card(NVIDIA, 24576, true);
few.threads = 4;
c = choose(few); // (the recording threads draw the grass: the game's with 4 threads)
CHECK(c.grass == 0 && c.shadow_res == 2);
// the fingerprint: another card, another memory or another upscaler that runs chooses again
const Hardware a = card(NVIDIA, 12282, true);
CHECK(fingerprint(a, 0x10de, 0x2782) == fingerprint(a, 0x10de, 0x2782));
CHECK(fingerprint(a, 0x10de, 0x2782) != fingerprint(a, 0x10de, 0x2704));
CHECK(fingerprint(a, 0x10de, 0x2782) != fingerprint(card(NVIDIA, 12282, false), 0x10de, 0x2782));
CHECK(fingerprint(a, 0x10de, 0x2782) >= 0);
// the tuning: gathers kWindows of play, lighter only with frames missed and the GPU busy
Tuning t;
for (int i = 0; i < kWindows - 1; i++) CHECK(tune(t, 16.5f, 400, 50, 60, true, true) == WAIT);
CHECK(tune(t, 16.5f, 400, 50, 60, true, true) == LIGHTER && t.steps == 1 && t.went_down);
for (int i = 0; i < kWindows * 3; i++) CHECK(tune(t, 1, 20, 60, 60, true, true) == WAIT); // (menus: not play)
for (int i = 0; i < kWindows - 1; i++) tune(t, 5, 400, 60, 60, true, true);
CHECK(tune(t, 5, 400, 60, 60, true, true) == KEEP && t.done); // (no step up after a step down)
Tuning u;
for (int i = 0; i < kWindows - 1; i++) tune(u, 6, 400, 60, 60, true, true);
CHECK(tune(u, 6, 400, 60, 60, true, true) == HEAVIER && !u.went_down);
Tuning cpu;
for (int i = 0; i < kWindows - 1; i++) tune(cpu, 8, 400, 40, 60, true, true);
CHECK(tune(cpu, 8, 400, 40, 60, true, true) == CPU_BOUND && cpu.done && cpu.steps == 0);
// its state across a restart
Tuning s;
s.steps = 2, s.went_down = true;
Tuning back;
bool settled = false;
unpack(pack(s, true), back, settled);
CHECK(back.steps == 2 && back.went_down && settled && back.done);
CHECK(best_step(DLSS) == RES_QUALITY && best_step(FSR4) == RES_QUALITY && best_step(GAME) == RES_FULL);
std::printf("auto settings: tiers, upscalers by maker, detail rows, fingerprint, tuning and its saved state\n");
return 0;
}
'''
def need(where, text, needles):
for needle in needles:
if needle not in text:
raise SystemExit("FAIL: " + where + " no longer has: " + needle)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cxx", default="g++")
a = p.parse_args()
menu = (ROOT / "gpu/vk/vk_menu.cpp").read_text(encoding="utf-8")
header = (ROOT / "gpu/vk/vk_menu.h").read_text(encoding="utf-8")
replay = (ROOT / "gpu/vk/vk_replay.cpp").read_text(encoding="utf-8")
need("vk_menu.cpp", menu, ['{TAB_GRAPHICS, "Auto (this PC)", &opts.auto_pc, 0, 1, 1, tx_onoff,',
"auto_row_set(r.value);", "auto_start();", "auto_tick();",
"const auto_settings::Choice c = auto_settings::choose(hw);"])
need("vk_menu.h", header, ["int auto_pc = 0;"]) # (Off by default: nothing set, nothing tuned)
need("vk_replay.cpp", replay, ["menu_auto_tune(gpu_ms, draws,"])
# (a hand change of a row it sets turns it Off)
m = re.search(r"void auto_row_set\(const int\* value\) \{(.*?)\n\}", menu, re.S)
if not m or "opts.auto_pc = 0;" not in m.group(1):
raise SystemExit("FAIL: auto_row_set no longer turns Auto Off on a hand change")
with tempfile.TemporaryDirectory(prefix="auto-settings-") as tmp:
src = Path(tmp) / "t.cpp"
src.write_text(C, encoding="utf-8")
exe = Path(tmp) / ("t.exe" if sys.platform == "win32" else "t")
subprocess.run([a.cxx, "-std=c++20", "-O1", "-Wall", "-I", str(ROOT / "gpu/vk"), "-o", str(exe), str(src)], check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True)
sys.stdout.write(r.stdout)
if r.returncode:
raise SystemExit(r.stderr.strip())
if __name__ == "__main__":
main()

View File

@@ -67,16 +67,57 @@ class BcRawTargetTests(unittest.TestCase):
self.assertRegex(self.draw, r"default_list && cp->key == 0x53509044401d78d2ull && !at\.n")
def test_3d_bc_images_take_no_attachment_usage_on_nvidia_before_turing(self):
# (Pascal loses the device on a raw view of a 3D BC image, upstream #2327: no usage there, so no view, and
# the noise pass is left out by the rule above)
# (Pascal loses the device on a raw view of a 3D BC image: no usage there, so no raw view; its slices are drawn into
# through block attachments of their own instead, and the noise pass runs: bc3d_way)
raw = self.tex.index("Raw storage views address one compressed block per texel")
branch = self.tex[raw:self.tex.index("CUBE_COMPATIBLE_BIT", raw)]
self.assertIn("dev.props.vendorID == 0x10de && dev.props.deviceID < 0x1e00", branch)
guard = branch.index("if (x.type == VK_IMAGE_TYPE_3D && !bc3d_target)")
guard = branch.index("if (x.type == VK_IMAGE_TYPE_3D && bc3d_way() != 1) {")
usage = branch.index("x.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;")
self.assertLess(guard, usage)
self.assertIn("} else if (format_props(raw).optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)", branch)
self.assertIn('getenv("RX_VK_BC3D_TARGET")', branch)
way = block(self.tex, "int bc3d_way() {")
self.assertIn("dev.props.vendorID == 0x10de && dev.props.deviceID < 0x1e00", way)
self.assertIn('getenv("RX_VK_BC3D_TARGET")', way)
self.assertIn("old_nvidia ? 2 : 1", way)
def test_3d_bc_slices_are_drawn_through_block_attachments_where_raw_views_cannot_be(self):
attach = block(self.tex, "TextureAttachment texture_attachment(")
# (every other image, and every card whose raw views work: texture_view's, as before)
first = attach[:attach.index("// (the view's format")]
self.assertIn("tex->type != VK_IMAGE_TYPE_3D || !is_bc(tex->format) || tex->bc || bc3d_way() != 2", first)
self.assertIn("texture_view(tex, t, v, VK_IMAGE_VIEW_TYPE_2D, ViewUse::Attachment, &out.format)", first)
# (one texel a block: the level's extent in blocks, every slice, uncompressed, copied to and from)
self.assertIn("(std::max(1u, tex->width >> level) + 3) / 4, (std::max(1u, tex->height >> level) + 3) / 4, depth", attach)
self.assertIn("bytes != tex->bpb", attach)
self.assertIn("VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT", attach)
self.assertIn("InitRedirect redirect;", attach)
copy = block(self.tex, "void copy_block_attachment(")
self.assertIn("to_attachment ? VkExtent3D{width, height, 1} : VkExtent3D{(width + 3) / 4, (height + 3) / 4, 1}", copy)
# (the pass: loaded behind a full barrier before it begins, stored back behind one after it ends)
targets = block(self.draw, "Targets targets(NvnState& s)")
self.assertIn("const TextureAttachment ta = texture_attachment(tex, t, v);", targets)
begin = block(self.draw, "void begin_pass(VkCommandBuffer cmd, const Targets& at) {")
load = begin.index("copy_block_attachment(cmd, *at.color[i], at.block_image[i], at.color_level[i], at.color_layer[i], true);")
self.assertLess(begin.index('full_barrier(cmd, "barrier (before BC slice loads)");'), load)
self.assertLess(load, begin.index('full_barrier(cmd, "barrier (after BC slice loads)");'))
self.assertLess(load, begin.index("vkCmdBeginRendering(cmd, &ri);"))
end = block(self.draw, "void end_pass(VkCommandBuffer cmd) {")
store = end.index("copy_block_attachment(cmd, *ps.tex[i], ps.block_image[i], ps.level[i], ps.layer[i], false);")
self.assertLess(end.index("vkCmdEndRendering(cmd);"), store)
self.assertLess(end.index('full_barrier(cmd, "barrier (before BC slice stores)");'), store)
self.assertLess(store, end.index('full_barrier(cmd, "barrier (after BC slice stores)");'))
# (and they go with their texture)
gone = block(self.tex, "void destroy_later(Texture& tex) {")
self.assertIn("for (const auto& a : tex.block_attachments) dead.push_back(Dead{tex.last_value, a.image, a.allocation, {}, {}});", gone)
def test_a_bc_image_is_never_cleared_with_vkCmdClearColorImage(self):
clear = block(self.xfer, "void clear_tex(")
self.assertIn("if (whole && !volume && !raw) {", clear)
self.assertLess(clear.index("const bool raw ="), clear.index("vkCmdClearColorImage("))
self.assertIn("const uint32_t slices = volume ? s.d : s.layers;", clear)
self.assertIn("const TextureAttachment attachment = texture_attachment(s.tex, p.tex, &lv);", clear)
self.assertIn("copy_block_attachment(cmd, *s.tex, attachment.blocks, s.level, slice, true);", clear)
self.assertIn("copy_block_attachment(cmd, *s.tex, attachment.blocks, s.level, slice, false);", clear)
if __name__ == "__main__":

View File

@@ -99,13 +99,16 @@ def main():
check('bc_scratch::small_layers(getenv("RX_VK_BC_SMALL_LAYERS"), dev.props.vendorID)' in layers,
"the small scratch's layers are not the rule's of the switch and the card's vendor")
make = block(tex, "bool bc_scratch_make() {")
check("if (bc_small_layers() > 1 && texture_detail_level() == tex_detail::kFull) {" in make,
# ((Triforce) at reduced detail only with RX_VK_BC_LEVELS=1, and then kBcTinyDim a side, for the groups of levels alone)
check("const bool tiny = bc_levels_on() && texture_detail_level() != tex_detail::kFull;" in make and
"if (bc_small_layers() > 1 && (texture_detail_level() == tex_detail::kFull || tiny)) {" in make and
"bc_small_px = tiny ? kBcTinyDim : bc_scratch::kSmallDim;" in make,
"the small scratch is made with one layer asked, or at reduced texture detail")
check("si.extent = {bc_scratch::kSmallDim, bc_scratch::kSmallDim, 1};" in make and "si.arrayLayers = bc_small_layers();" in make and
check("si.extent = {bc_small_px, bc_small_px, 1};" in make and "si.arrayLayers = bc_small_layers();" in make and
"sv.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, bc_small_layers()};" in make,
"the small scratch or its view is not 1024 x 1024 with a run's layers")
check("const uint64_t out = std::max(bc_scratch::out_bytes(bc_scratch_layers()), small_out);" in make and
"bc_small ? bc_scratch::small_out_bytes(bc_small_layers()) : 0" in make,
"bc_small ? (uint64_t)(bc_small_px / 4) * (bc_small_px / 4) * bc_small_layers() * 16 : 0" in make,
"the output buffer does not hold a run of either scratch")
check("bc_small_fresh = bc_small != VK_NULL_HANDLE;" in make, "a new small scratch's layout is not marked to be set")
failed = make[make.index("!make_out()) {"):make.index("bc_scratch_fresh = true;")]
@@ -120,10 +123,20 @@ def main():
"bc_small = VK_NULL_HANDLE" in idle, "the small scratch is not given back with the first")
start = tex.index(" if (tex.bc) { // (decoded into the scratch a run of consecutive layers at a time, re-encoded, copied in)")
loop = tex[start:tex.index(" st_astc++;", start)]
check("const bool small = bc_scratch::small_level(g.w, g.h, bc_small != VK_NULL_HANDLE, tex.bc_resized);" in loop and
# ((Triforce) RX_VK_BC_LEVELS=1, off unless set: a group's levels finished before a level out of it, a second big one, a
# full output buffer or a new piece, and at the end; a failed upload's decoded group ordered before the next upload)
check('getenv("RX_VK_BC_LEVELS") && atoi(getenv("RX_VK_BC_LEVELS")) != 0' in tex, "RX_VK_BC_LEVELS is not off unless set")
check("const bool grouped = bc_levels_on() && !tex.bc_resized && !to_bc7 && bc_small && bc_small_layer[0] && tex.layers == 1 &&" in loop and
"chunk.cuts((uint64_t)g.w * g.h * n))\n group_flush(cmd);\n cmd = chunk.before(" in loop and
" group_flush(cmd); // ((Triforce, RX_VK_BC_LEVELS) the last group's levels)" in loop and
"if (!pending.empty()) full_barrier(c);" in loop,
"a group of levels is not finished where it must be")
check("const bool small_fits = bc_scratch::small_level(g.w, g.h, bc_small != VK_NULL_HANDLE, tex.bc_resized) &&" in loop and
"const bool small = small_fits && (bc_small_px == bc_scratch::kSmallDim || in_group);" in loop and
"const uint32_t run = small ? bc_small_layers() : bc_layers();" in loop,
"a level does not ask the rule which scratch it goes through, or does not take that scratch's run")
check("VkDescriptorImageInfo ii{VK_NULL_HANDLE, small ? bc_small_view : bc_scratch_view, VK_IMAGE_LAYOUT_GENERAL};" in loop and
check(": (small ? bc_small_view : bc_scratch_view);" in loop and
"VkDescriptorImageInfo ii{VK_NULL_HANDLE, into, VK_IMAGE_LAYOUT_GENERAL};" in loop and
"bc_encode_into(cmd, iw, ih, n, tex, level, layers[k0], 0, 0, small ? bc_small_view : VK_NULL_HANDLE);" in loop,
"a small level is not decoded into the small scratch and encoded from it")
check("bc_encode_resized(cmd, g.w, g.h, iw, ih, n, tex, level, layers[k0]);" in loop, "a resized texture's levels lost their own path")

View File

@@ -77,6 +77,7 @@ int64_t st_prefetch_dropped = 0;
uint64_t mem_rec_value = 7;
int freed = 0;
void vkDestroyBuffer(void*, VkBuffer, void*) {}
void destroy_import_buffer(VkBuffer) {} // (vk_memory.cpp's: an import's texel buffer views, then vkDestroyBuffer)
void vkFreeMemory(void*, VkDeviceMemory, void*) { freed++; }
void logf(const char*, ...) {}
void guest_pages_set(uint64_t, uint64_t, uint64_t) {}

View File

@@ -45,6 +45,7 @@ PRELUDE = r"""
#include <string.h>
#include <stdint.h>
#include "vk_api.h"
#include "../../host/hold_toggle.h" /* ((Triforce) 11-24: hold-to-toggle's latch, beside the bindings) */
typedef long LONG;
typedef unsigned long DWORD;
#define VK_LBUTTON 0x01
@@ -99,13 +100,29 @@ int main(int argc, char **argv) {
CHECK(bound_down(HOS_KEY_CAM_LEFT, 0));
/* the mouse's left button: held when the capture begins, it counts only after it was let go */
release(), held[VK_LBUTTON] = 1;
mouse_buttons_arm(1);
mouse_buttons_arm(1, 0);
CHECK(!bound_down(HOS_SW_Y, 1));
release(), mouse_buttons_arm(1), held[VK_LBUTTON] = 1, mouse_buttons_arm(1);
release(), mouse_buttons_arm(1, 0), held[VK_LBUTTON] = 1, mouse_buttons_arm(1, 0);
CHECK(bound_down(HOS_SW_Y, 1));
CHECK(!bound_down(HOS_SW_Y, 0)); /* not while the mouse is not captured */
mouse_buttons_arm(0);
mouse_buttons_arm(0, 0);
CHECK(!bound_down(HOS_SW_Y, 1)); /* a new capture arms again */
/* one of the game's menus has the mouse: the side buttons stay their controls', the other three are its clicks */
hos_bind(HOS_BIND_KEY, HOS_SW_B, 1, VK_XBUTTON1), hos_bind(HOS_BIND_KEY, HOS_SW_X, 1, VK_XBUTTON2);
hos_bind(HOS_BIND_KEY, HOS_SW_R, 1, VK_MBUTTON);
release(), mouse_buttons_arm(0, 1);
held[VK_LBUTTON] = held[VK_RBUTTON] = held[VK_MBUTTON] = held[VK_XBUTTON1] = held[VK_XBUTTON2] = 1;
mouse_buttons_arm(0, 1);
CHECK(bound_down(HOS_SW_B, 1) && bound_down(HOS_SW_X, 1));
CHECK(!bound_down(HOS_SW_Y, 1) && !bound_down(HOS_SW_ZL, 1) && !bound_down(HOS_SW_R, 1));
mouse_buttons_arm(0, 0); /* the menu closed and the mouse is free: no longer */
CHECK(!bound_down(HOS_SW_B, 1));
mouse_buttons_arm(0, 1); /* held as the next menu opens: only after it was let go */
CHECK(!bound_down(HOS_SW_B, 1));
release(), mouse_buttons_arm(0, 1), held[VK_XBUTTON1] = 1, mouse_buttons_arm(1, 0), mouse_buttons_arm(0, 1);
CHECK(bound_down(HOS_SW_B, 1)); /* from the menu into play and back, held: one press */
hos_bind(HOS_BIND_KEY, HOS_SW_B, 1, 0), hos_bind(HOS_BIND_KEY, HOS_SW_X, 1, 0), hos_bind(HOS_BIND_KEY, HOS_SW_R, 1, 0);
release(), mouse_buttons_arm(0, 0);
/* a key bound to a keys-only control is taken from the button that had it */
hos_bind(HOS_BIND_KEY, HOS_KEY_CAM_UP, 0, 'E');
CHECK(hos_binding(HOS_BIND_KEY, HOS_SW_A, 0) == 0 && hos_binding(HOS_BIND_KEY, HOS_KEY_CAM_UP, 0) == 'E');
@@ -121,16 +138,59 @@ int main(int argc, char **argv) {
walk_vk = VK_SHIFT;
CHECK(!bound_down(HOS_SW_B, 0) && bound_down(HOS_SW_X, 0));
CHECK(hos_binding(HOS_BIND_KEY, HOS_SW_B, 0) == VK_SHIFT);
walk_vk = VK_TAB; /* (one of a control's two keys: the other still presses it) */
release(), held[VK_TAB] = 1;
CHECK(!bound_down(HOS_SW_PLUS, 0));
release(), held[VK_RETURN] = 1;
CHECK(bound_down(HOS_SW_PLUS, 0));
walk_vk = 'X'; /* (one of a control's two keys: the other still presses it) */
release(), held['X'] = 1;
CHECK(!bound_down(HOS_SW_ZR, 0));
release(), held['F'] = 1;
CHECK(bound_down(HOS_SW_ZR, 0));
walk_vk = 0;
/* (Plus is Tab alone: Enter, which controller software sends for a pad's A, presses nothing) */
release(), held[VK_RETURN] = 1;
for (int i = 0; i < HOS_KEY_N; i++) CHECK(!bound_down(i, 0));
CHECK(hos_binding(HOS_BIND_KEY, HOS_SW_PLUS, 0) == VK_TAB && hos_binding(HOS_BIND_KEY, HOS_SW_PLUS, 1) == 0);
release(), held[VK_SHIFT] = held[VK_TAB] = 1;
CHECK(bound_down(HOS_SW_B, 0) && bound_down(HOS_SW_PLUS, 0));
/* ((Triforce) 11-24) a Switch button's two gamepad inputs, Input 1 and Input 2: the file's pad_a=1,26 (the east face
button and a rear paddle), an old single one (pad_b), a second that is no input (pad_x); either presses the button */
const uint64_t face = 1ULL << HOS_PAD_EAST, paddle = 1ULL << HOS_PAD_RPADDLE1, a = 1ULL << HOS_SW_A;
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 0) == HOS_PAD_EAST && hos_binding(HOS_BIND_PAD, HOS_SW_A, 1) == HOS_PAD_RPADDLE1);
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_B, 1) == -1 && hos_binding(HOS_BIND_PAD, HOS_SW_X, 1) == -1);
CHECK(bound_pad_buttons(face) == a && bound_pad_buttons(paddle) == a && bound_pad_buttons(face | paddle) == a);
CHECK(bound_pad_buttons(1ULL << HOS_PAD_TOUCHPAD) == 0 && bound_pad_buttons(1ULL << HOS_PAD_LS_UP) == 0);
hos_bind(HOS_BIND_PAD, HOS_SW_B, 1, HOS_PAD_RPADDLE1); /* (taken from A's Input 2: A keeps its Input 1) */
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 1) == -1 && bound_pad_buttons(paddle) == 1ULL << HOS_SW_B && bound_pad_buttons(face) == a);
hos_bind(HOS_BIND_PAD, HOS_SW_B, 1, -1);
CHECK(bound_pad_buttons(paddle) == 0 && bound_pad_buttons(face) == a);
hos_bind(HOS_BIND_PAD, HOS_SW_A, 1, HOS_PAD_RPADDLE1);
const int y0 = hos_binding(HOS_BIND_PAD, HOS_SW_Y, 0); /* (another button's only input into an empty Input 2: refused) */
hos_bind(HOS_BIND_PAD, HOS_SW_B, 1, y0);
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_B, 1) == -1 && hos_binding(HOS_BIND_PAD, HOS_SW_Y, 0) == y0);
hos_bind(HOS_BIND_PAD, HOS_SW_B, 1, HOS_PAD_EAST); /* (from a button with an Input 2: taken, its Input 2 moves up) */
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_B, 1) == HOS_PAD_EAST);
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 0) == HOS_PAD_RPADDLE1 && hos_binding(HOS_BIND_PAD, HOS_SW_A, 1) == -1);
hos_bind(HOS_BIND_KEY, -1, 0, 0);
CHECK(hos_binding(HOS_BIND_KEY, HOS_KEY_MOVE_UP, 0) == 'W' && hos_binding(HOS_BIND_KEY, HOS_SW_A, 0) == 'E');
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 1) == -1 && hos_binding(HOS_BIND_PAD, HOS_SW_B, 1) == -1);
/* ((Triforce) the Controls page's per-control reset and confirmed rebinds: a key another control has, asked about (nothing
changed), then taken; a reset refused while another control has a default, made once it does not; a gamepad input
another button has, asked about, then traded as hos_bind trades it */
uint64_t conflicts = 0;
CHECK(hos_binding_is_default(HOS_SW_A) && hos_binding_is_default(HOS_KEY_MOVE_UP));
CHECK(!hos_rebind_control(HOS_BIND_KEY, HOS_SW_A, 0, 'W', 0, &conflicts) && conflicts == 1ULL << HOS_KEY_MOVE_UP);
CHECK(hos_binding(HOS_BIND_KEY, HOS_SW_A, 0) == 'E' && hos_binding(HOS_BIND_KEY, HOS_KEY_MOVE_UP, 0) == 'W');
CHECK(hos_rebind_control(HOS_BIND_KEY, HOS_SW_A, 0, 'W', conflicts, &conflicts));
CHECK(hos_binding(HOS_BIND_KEY, HOS_SW_A, 0) == 'W' && hos_binding(HOS_BIND_KEY, HOS_KEY_MOVE_UP, 0) == 0);
CHECK(!hos_binding_is_default(HOS_SW_A) && !hos_binding_is_default(HOS_KEY_MOVE_UP));
CHECK(!hos_reset_binding(HOS_KEY_MOVE_UP) && hos_binding(HOS_BIND_KEY, HOS_KEY_MOVE_UP, 0) == 0);
CHECK(hos_reset_binding(HOS_SW_A) && hos_binding(HOS_BIND_KEY, HOS_SW_A, 0) == 'E' && hos_binding_is_default(HOS_SW_A));
CHECK(hos_reset_binding(HOS_KEY_MOVE_UP) && hos_binding_is_default(HOS_KEY_MOVE_UP));
CHECK(!hos_rebind_control(HOS_BIND_PAD, HOS_SW_A, 0, HOS_PAD_SOUTH, 0, &conflicts) && conflicts == 1ULL << HOS_SW_B);
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 0) == HOS_PAD_EAST);
CHECK(hos_rebind_control(HOS_BIND_PAD, HOS_SW_A, 0, HOS_PAD_SOUTH, conflicts, &conflicts));
CHECK(hos_binding(HOS_BIND_PAD, HOS_SW_A, 0) == HOS_PAD_SOUTH && hos_binding(HOS_BIND_PAD, HOS_SW_B, 0) == HOS_PAD_EAST);
CHECK(!hos_binding_is_default(HOS_SW_B) && !hos_reset_binding(HOS_SW_B) && !hos_reset_binding(HOS_SW_A)); /* (each has the other's) */
hos_bind(HOS_BIND_PAD, HOS_SW_A, 0, -1); /* (cleared: B's default is free) */
CHECK(hos_reset_binding(HOS_SW_B) && hos_reset_binding(HOS_SW_A) && hos_binding_is_default(HOS_SW_A) && hos_binding_is_default(HOS_SW_B));
if (!fails) printf("PASS\n");
return fails != 0;
}
@@ -144,8 +204,10 @@ class BoundKeysTests(unittest.TestCase):
self.skipTest("no C compiler")
hid = (ROOT / "host" / "nn_hid.c").read_text(encoding="utf-8")
code = [block(hid, "static int kmap_down("),
between(hid, "static const char *const bind_names[HOS_KEY_N]", "void hos_bind("),
between(hid, "static int mouse_vk_slot(", "static int bound_down(")]
between(hid, "static const char *const bind_names[HOS_KEY_N]", "\nvoid hos_bind("), # (its definition: the live input declares it)
block(hid, "static uint64_t bound_pad_buttons("),
between(hid, "static int mouse_vk_slot(", "static int bound_down("),
between(hid, "int hos_binding_is_default(", "int hos_rebind_control(")] # ((Triforce) the per-control reset)
code = "\n".join(code).replace("GetModuleFileNameA(NULL,", "GetModuleFileNameA(0,")
read = block(hid, "static void read_input(")
for needle in ("bound_down(HOS_KEY_MOVE_UP,", "bound_down(HOS_KEY_CAM_RIGHT,", "mouse_buttons_arm(", "bound_down(i, 1)"):
@@ -154,7 +216,8 @@ class BoundKeysTests(unittest.TestCase):
with tempfile.TemporaryDirectory(prefix="hookshot-bound-keys-") as tmp:
tmp = Path(tmp)
# (the options file by its name now: as hookshot_options.ini, the name before, nothing read it)
(tmp / "triforce_options.ini").write_text("key_move_up=90,0\npad_move_up=0\n", encoding="utf-8")
(tmp / "triforce_options.ini").write_text("key_move_up=90,0\npad_move_up=0\npad_a=1,26\npad_b=0\npad_x=2,99\n",
encoding="utf-8")
(tmp / "t.c").write_text(PRELUDE + code + MAIN, encoding="utf-8")
binary = tmp / ("t.exe" if sys.platform == "win32" else "t")
build = subprocess.run([compiler, "-std=gnu11", "-Wall", "-Wno-unused-function", "-I", str(ROOT / "gpu" / "vk"),

View File

@@ -129,8 +129,18 @@ def check_sources():
check("!(host && host->take_key_press) && (GetAsyncKeyState(VK_F8) & 0x8000) != 0" in tick and "share_ask.store(HOS_SHARE_CAPTURE_KEY" in tick,
"where the window has no key handler of the host's (Linux) F8 is not read")
check("share_notice_new.exchange(false" in tick and "share_lines[HOS_SHARE_NOTICE].c_str()" in tick, "the host's line for the foot of the screen is not shown")
for needle in ("| Bug capture (F8) |", "**F8**", "captures", "capture.txt", "frame.png", "log-tail.txt"):
for needle in ("| Bug capture (F8) |", "**F8**", "captures", "capture.txt", "frame.png", "log-tail.txt", "triforce_log.1.txt"):
check(needle in readme, "readme.md does not say %r of the bug capture" % needle)
# ((Triforce) 11-24) the options changed from the defaults: the menu's rows, from the capture's thread, a byte a question
check("enum { HOS_OPT_BUG_SETTINGS = 286 };" in api, "HOS_OPT_BUG_SETTINGS is not 286, the bug capture's own id")
check("if (id == HOS_OPT_BUG_SETTINGS) return menu_take_bug_settings();" in option, "the host cannot read the options changed")
check("if (id == HOS_OPT_BUG_SETTINGS) {" in sets and "menu_bug_settings_begin();" in sets, "the host cannot ask for the options changed")
rows = block(menu, "std::string changed_rows_text() {")
check("static const Options defaults{};" in rows and "restart_inert(r)" in rows and '"a microphone by its name"' in rows,
"the options changed are not compared with the built-in defaults, show the Custom size's inert sides, or name a microphone")
# nothing is sent anywhere and nothing is opened: no address, no browser, no network
for word in ("http", "ShellExecute", "xdg-open", "socket(", "WinHttp", "InternetOpen", "curl"):
check(word not in capture, "host/bug_capture.c names %r: a capture is written on this PC only" % word)
def run_pixels(cxx, tmp):
@@ -147,10 +157,10 @@ def folders(g):
return sorted(p for p in d.iterdir() if p.is_dir()) if d.is_dir() else []
def read_capture(g, folder, out, save_tag, picture, place=True, trigger="F8"):
def read_capture(g, folder, out, save_tag, picture, place=True, trigger="F8", settings=True):
"""one capture's folder, whole: its files and what capture.txt says"""
check(re.fullmatch(r"\d{8}-\d{6}(-\d+)?", folder.name), "the capture's folder is named " + folder.name)
want = {"capture.txt", "triforce_options.ini", "log-tail.txt"} | ({"frame.png"} if picture else set())
want = {"capture.txt", "triforce_options.ini", "log-tail.txt", "triforce_log.1.txt"} | ({"frame.png"} if picture else set())
names = {p.name for p in folder.iterdir()}
zips = [n for n in names if n.endswith(".zip")]
check(names - set(zips) == want and len(zips) == 1 and re.fullmatch(r"Triforce-save-\d{8}-\d{6}\.zip", zips[0]), "%s holds %r" % (folder.name, sorted(names)))
@@ -189,6 +199,23 @@ def read_capture(g, folder, out, save_tag, picture, place=True, trigger="F8"):
else:
check("place = not known" in text, "capture.txt names a place nobody said:\n" + text)
check(("picture = frame.png" in text) == picture and ("picture = none" in text) != picture, "capture.txt on its picture:\n" + text)
# ((Triforce) 11-24) the PC, the run before's log, the first sign of trouble, the options changed, the switches set
check(re.search(r"\ncpu = .+ \(\d+ threads\), \d+ GB\n", text) and re.search(r"\nsystem = Windows", text), "capture.txt on the CPU, RAM and system:\n" + text)
check((folder / "triforce_log.1.txt").read_bytes() == (g.dir / "triforce_log.1.txt").read_bytes(), "the run before's log is not copied as it is")
check(re.search(r"\nlog before = triforce_log\.1\.txt \(the run before's log: triforce v0\.3\.9-test \(source 89abcdef\), last written "
r"\d{4}-\d\d-\d\d \d\d:\d\d, 0\.0 MB\)\n", text), "capture.txt on the run before's log:\n" + text)
check("\ntrouble = none in this run's log" in text and "\ntrouble before = CRASH: exception 0xc0000005 (write 0x8, guest 0x8)\n" in text,
"capture.txt on the first sign of trouble:\n" + text)
if settings:
check("\noptions changed from the defaults (as the Insert menu shows them; triforce_options.ini has them all):\n"
" Field of view: 110% (default: 100%)\n Text size: 125% (default: Off)\n" in text, "capture.txt on the options changed:\n" + text)
else:
check("\noptions changed from the defaults = not known" in text, "capture.txt names options changed a renderer did not say:\n" + text)
switches = re.search(r"\nswitches set = (\d+) \(the environment[^\n]*\n((?: [^\n]*\n)*)", text)
check(switches and int(switches.group(1)) == switches.group(2).count("\n"), "capture.txt on the switches:\n" + text)
lines = switches.group(2).splitlines()
check(" HOS_LOG_REDACT=0" in lines and " HOS_SAVE_EXPORT_DIR=(value left out)" in lines and lines == sorted(lines),
"capture.txt's switches: a number not written, a folder written, or not in order: %r" % lines)
return text
@@ -198,6 +225,14 @@ def main():
p.add_argument("--cxx", default="g++")
a = p.parse_args()
check_sources()
# ((Triforce) 11-24: log-tail.txt is written without the player's home folder and user name (host/log_redact.h), and this
# check's game folders are in the temporary folder, under the home folder: the copy is compared with the log as it is,
# so the redaction is off for these runs. tests/test_log_redact.py has the redaction itself, and that the capture calls it)
plain_run = share.Game.run # (its runs take no HOS_ variable from here: handed over with each)
def run_as_it_is(self, *args, env=None, ok=True):
return plain_run(self, *args, env=dict({"HOS_LOG_REDACT": "0"}, **(env or {})), ok=ok)
share.Game.run = run_as_it_is
cc, cxx = shutil.which(a.cc) or shutil.which("gcc") or shutil.which("clang"), shutil.which(a.cxx) or shutil.which("g++") or shutil.which("clang++")
if not cxx:
print("skip: no C++ compiler; the sources were checked")
@@ -217,12 +252,23 @@ def main():
"[hos host] vk: vendor fixes for NVIDIA (621.01): out-of-bounds texel fetches 0 0, NaN tests by bits 0, gather offset 0",
"[hos host] vk: Some GPU 9000, Vulkan 1.4, driver 0x9b404000; mesh shaders yes, host memory import yes, pipeline libraries yes"]
(g.dir / "triforce_log.txt").write_bytes(("\n".join(head + ["[hos host] line %d of the run" % i for i in range(1000)]) + "\n").encode())
# ((Triforce) 11-24) the run before's, which crashed
(g.dir / "triforce_log.1.txt").write_bytes(b"[hos host] triforce v0.3.9-test (source 89abcdef)\r\n[hos host] a line of the run before\r\n"
b"[hos Main] CRASH: exception 0xc0000005 (write 0x8, guest 0x8)\r\n[hos Main] CRASH: thread Main\r\n")
g.run("play", "v1")
check(share.tag_of(g.save) == "v1", "the fixture's save")
# F8 in play
out = g.run("capture", "picture")
# F8 in play; the switches' values: what is written and what is left out
out = g.run("capture", "picture", env={"RX_TEST_SIZE": "1920x1080", "RX_TEST_RATE": "-1.5", "RX_TEST_WORD": "Yes", "RX_TEST_TOKEN": "5",
"RX_TEST_LONG": "1234567890123", "RX_TEST_NAME": "C:\\Users\\Ann", "RX_TEST_MINUS_SIZE": "-1x2",
"VK_INSTANCE_LAYERS": "VK_LAYER_x", "NOT_A_SWITCH": "1"})
made = folders(g)
text = (made[0] / "capture.txt").read_text(encoding="utf-8") if made else ""
for line, shown in ((" RX_TEST_SIZE=1920x1080", True), (" RX_TEST_RATE=-1.5", True), (" RX_TEST_WORD=Yes", True),
(" RX_TEST_TOKEN=(value left out)", True), (" RX_TEST_LONG=(value left out)", True),
(" RX_TEST_NAME=(value left out)", True), (" RX_TEST_MINUS_SIZE=(value left out)", True),
(" VK_INSTANCE_LAYERS=(value left out)", True), ("NOT_A_SWITCH", False), ("C:\\Users\\Ann", False)):
check((line in text) == shown, "capture.txt's switches on %r:\n%s" % (line, text))
check(len(made) == 1, "F8 made %d capture folders:\n%s" % (len(made), out))
check("where asked 1" in out and out.splitlines().count("shot asked") == 1 and "log: capture: F8 again: skipped" in out, "the press:\n" + out)
row = g.said(out, share_capture_row())
@@ -237,7 +283,7 @@ def main():
out = g.run("capture", "nopicture")
made = folders(g)
check(len(made) == 2 and "without a picture" in g.said(out, share_capture_row()), "a capture without a picture:\n" + out)
text = read_capture(g, made[1], out, "v1", picture=False)
text = read_capture(g, made[1], out, "v1", picture=False, settings=False)
check("the renderer could not read the window's picture" in text, "capture.txt on a picture the renderer could not take:\n" + text)
out = g.run("capture", "noframes")
made = folders(g)

View File

@@ -0,0 +1,177 @@
"""nx2/build.py's record of what each source's object key was (HASHES, hash_cache.json; HASH_CACHE): a source
whose size, modification time and file id are the ones recorded is not read again to name its object, and its key is the one
object_key gives; anything else about it, or a file written too near the record, is read and hashed as before.
Nothing here runs a compiler or needs the game.
python -I -B tests/test_build_hash_cache.py
"""
import builtins
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import sys
import tempfile
import time
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path[:0] = [str(ROOT / "nx2"), str(ROOT / "third_party" / "a64-kit" / "tools")]
spec = importlib.util.spec_from_file_location("build_hash_cache", ROOT / "nx2" / "build.py")
build = importlib.util.module_from_spec(spec)
spec.loader.exec_module(build)
FLAGS, DEPS = ["-O1", "-DA64_POLLING"], b"/* the headers */"
MINUTE_AGO = time.time() - 60
class HashCacheTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="triforce-hash-cache-")
self.addCleanup(self.temporary.cleanup)
self.dir = Path(self.temporary.name)
self.src = self.dir / "code_001.c"
self.write("void f_80000000(void) {}\n")
build.load_hashes(str(self.dir))
def write(self, text, when=MINUTE_AGO):
self.src.write_bytes(text.encode("utf-8")) # (bytes: Windows' text mode would make the newlines CRLF)
os.utime(self.src, (when, when))
def next_build(self):
"""the record saved, then read as the next build starts"""
build.save_hashes(str(self.dir))
build.load_hashes(str(self.dir))
def unread(self):
"""open() refusing the source: a key that comes back was not read from it"""
real = builtins.open
src = str(self.src)
def guarded(path, *a, **k):
if str(path) == src:
raise AssertionError("the source was read")
return real(path, *a, **k)
return mock.patch("builtins.open", guarded)
def test_the_key_is_object_keys_and_the_next_build_does_not_read_the_source(self):
key = build.key_of(str(self.src), FLAGS, DEPS)
self.assertEqual(key, build.object_key(str(self.src), FLAGS, DEPS))
self.next_build()
with self.unread():
self.assertEqual(build.key_of(str(self.src), FLAGS, DEPS), key)
self.assertEqual(build.content_sha1(str(self.src)),
hashlib.sha1(b"void f_80000000(void) {}\n", usedforsecurity=False).hexdigest())
def test_a_changed_file_is_read_again(self):
build.key_of(str(self.src), FLAGS, DEPS)
self.next_build()
for text, when in (("void f_80000000(void) { }\n", MINUTE_AGO), # (another size)
("void f_80000004(void) {}\n", MINUTE_AGO - 30)): # (the same size, another time)
with self.subTest(text=text):
self.write(text, when)
self.assertEqual(build.key_of(str(self.src), FLAGS, DEPS), build.object_key(str(self.src), FLAGS, DEPS))
self.next_build()
def test_other_flags_or_headers_are_another_key_and_both_are_kept(self):
first = build.key_of(str(self.src), FLAGS, DEPS)
hot = build.key_of(str(self.src), FLAGS + ["-O2"], DEPS)
other = build.key_of(str(self.src), FLAGS, DEPS + b"/* a new header */")
self.assertEqual(len({first, hot, other}), 3)
self.next_build()
with self.unread():
self.assertEqual([build.key_of(str(self.src), FLAGS, DEPS), build.key_of(str(self.src), FLAGS + ["-O2"], DEPS)],
[first, hot])
def test_a_file_written_near_the_record_is_not_trusted(self):
self.write("void f_80000000(void) {}\n", when=time.time()) # (within RACY_NS of the record written next)
build.key_of(str(self.src), FLAGS, DEPS)
self.next_build()
with self.unread(), self.assertRaises(AssertionError):
build.key_of(str(self.src), FLAGS, DEPS)
def test_an_untrusted_record_of_other_content_loses_its_keys(self):
"""(a file changed within RACY_NS of the record, its size and time the same: the record's keys are of the old content)"""
st = build.file_stat(str(self.src))
part = build.kept_part(FLAGS, DEPS)
build.HASHES[str(self.src)] = {"stat": st, "sha1": "0" * 40, "keys": {part: "stale", "other": "stale too"}}
build.HASHES_AT[0] = st[1] # (the record written as the file was: not trusted)
self.assertEqual(build.key_of(str(self.src), FLAGS, DEPS), build.object_key(str(self.src), FLAGS, DEPS))
self.assertNotIn("stale", build.HASHES[str(self.src)]["keys"].values())
self.assertNotIn("stale too", build.HASHES[str(self.src)]["keys"].values())
def test_a_record_that_cannot_be_read_is_no_record(self):
build.key_of(str(self.src), FLAGS, DEPS)
self.next_build()
record = self.dir / build.HASH_CACHE
for text in ("{not json", json.dumps({"scheme": build.HASH_SCHEME + 1, "written_ns": 0, "files": {}}),
json.dumps({"scheme": build.HASH_SCHEME, "written_ns": time.time_ns(),
"files": {str(self.src): {"stat": "no", "sha1": 1, "keys": []}}})):
with self.subTest(text=text[:20]):
record.write_text(text, encoding="utf-8")
build.load_hashes(str(self.dir))
self.assertEqual(build.HASHES, {})
self.assertEqual(build.key_of(str(self.src), FLAGS, DEPS), build.object_key(str(self.src), FLAGS, DEPS))
def test_the_record_is_written_under_the_time_its_build_started(self):
"""the 2 s rule is about when each source was stat'd: the build's start, not the save after the plan"""
with mock.patch.object(build.time, "time_ns", return_value=1000):
build.load_hashes(str(self.dir))
build.key_of(str(self.src), FLAGS, DEPS)
with mock.patch.object(build.time, "time_ns", return_value=9 * 10 ** 18):
build.save_hashes(str(self.dir))
data = json.loads((self.dir / build.HASH_CACHE).read_text(encoding="utf-8"))
self.assertEqual(data["written_ns"], 1000)
def test_a_source_this_build_looked_at_keeps_only_the_keys_it_asked_for(self):
other = self.dir / "code_002.c"
other.write_bytes(b"void f_80000010(void) {}\n")
os.utime(other, (MINUTE_AGO, MINUTE_AGO))
build.key_of(str(self.src), FLAGS, DEPS)
build.key_of(str(self.src), FLAGS, DEPS + b"/* an old header */")
build.key_of(str(other), FLAGS, DEPS)
build.key_of(str(other), FLAGS, DEPS + b"/* an old header */")
self.next_build()
build.key_of(str(self.src), FLAGS, DEPS) # (this build: the source and one key; the other source not at all)
self.next_build()
self.assertEqual(list(build.HASHES[str(self.src)]["keys"]), [build.kept_part(FLAGS, DEPS)])
self.assertEqual(len(build.HASHES[str(other)]["keys"]), 2)
def test_a_file_gone_is_not_kept_in_the_record(self):
build.key_of(str(self.src), FLAGS, DEPS)
self.src.unlink()
build.save_hashes(str(self.dir))
data = json.loads((self.dir / build.HASH_CACHE).read_text(encoding="utf-8"))
self.assertEqual(data["files"], {})
def test_migrate_stamps_reads_nothing_stamped_with_todays_kind_of_key(self):
gen, obj_dir, cache = self.dir / "gen", self.dir / "obj", self.dir / "objcache"
for d in (gen, obj_dir, cache):
d.mkdir()
self.src = gen / "code_002.c"
self.write("void f_80000008(void) {}\n")
key = build.object_key(str(self.src), FLAGS, DEPS)
(obj_dir / "code_002.o").write_bytes(b"object")
(obj_dir / "code_002.o.sha1").write_text(key)
(cache / (key + ".o")).write_bytes(b"object")
with mock.patch.object(build, "OBJ_CACHE", str(cache)), self.unread():
build.migrate_stamps(str(gen), str(obj_dir), FLAGS, DEPS)
self.assertEqual((obj_dir / "code_002.o.sha1").read_text(), key)
def test_the_build_uses_the_record(self):
"""main loads it before the stamps and saves it after the plan and the compile; the plan and the fingerprint use it.
compile_one keeps object_key: and uses key_of too, as a build without a countdown plans nothing"""
src = (ROOT / "nx2" / "build.py").read_text(encoding="utf-8")
main = src[src.index("\ndef main("):]
self.assertLess(main.index("load_hashes(out)"), main.index("migrate_stamps("))
self.assertLess(main.index("plan_jobs(jobs)"), main.index("save_hashes(out)"))
plan = src[src.index("\ndef plan_jobs("):src.index("\ndef migrate_stamps(")]
self.assertIn("key_of(src, fl, deps)", plan)
self.assertIn("content_sha1(code_src)", main)
if __name__ == "__main__":
raise SystemExit(unittest.main(verbosity=1))

147
tests/test_build_jobs.py Normal file
View File

@@ -0,0 +1,147 @@
"""The workers a build is asked for reach every step that runs work side by side, not only the compile (nx2/build_jobs.py).
The launcher's build workers give make_game.py --jobs or HOOKSHOT_JOBS. Only nx2/build.py took it: the lift's processes and
the shader preparation's sized themselves from the CPU count, so an update filled every thread whatever the player chose.
Checked here, with no game:
- build_jobs.requested and cap: 1 or more is a ceiling, None, "" and 0 are automatic, anything else is refused;
- make_game.main puts a count it was given (--jobs, or HOOKSHOT_JOBS already set) in HOOKSHOT_JOBS for its steps, and none
when it was given none (each step keeps its own count, as before);
- the lift's emit processes (nx2/chunks.py emit_jobs) are at most that many;
- children_on_cpus starts a process on that many CPUs and gives this one its CPUs back; make_game.prepare_shaders starts
the game in it (a stand-in that prints the CPUs it may use), on Linux, where the affinity mask can be read from Python.
python -I -B tests/test_build_jobs.py
"""
import io
import os
from pathlib import Path
import sys
import tempfile
import time
import types
import unittest
from contextlib import redirect_stdout
from unittest import mock
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "nx2"))
import kit # noqa: E402,F401 (a64-kit on the path)
import build_jobs # noqa: E402
import chunks # noqa: E402
import make_game # noqa: E402
AFFINITY = hasattr(os, "sched_setaffinity")
def worker_id(_):
time.sleep(0.02) # (long enough that the pool starts every worker it may)
return os.getpid()
class Clean(unittest.TestCase):
def setUp(self):
env = mock.patch.dict(os.environ)
env.start()
self.addCleanup(env.stop)
for k in ("HOOKSHOT_JOBS", "HOOKSHOT_LIFT_JOBS", "HOOKSHOT_LIFT_NO_FORK"):
os.environ.pop(k, None)
class Count(Clean):
def test_requested(self):
self.assertEqual(build_jobs.requested("4"), 4)
self.assertEqual(build_jobs.requested(4), 4)
for automatic in (None, "", " ", "0", 0):
self.assertIsNone(build_jobs.requested(automatic), repr(automatic))
for bad in ("-1", "four", "1.5"):
with self.assertRaises(ValueError):
build_jobs.requested(bad)
def test_cap(self):
self.assertEqual(build_jobs.cap(12), 12) # (nothing asked: the step's own count)
self.assertEqual(build_jobs.cap(12, {"HOOKSHOT_JOBS": "4"}), 4)
self.assertEqual(build_jobs.cap(3, {"HOOKSHOT_JOBS": "4"}), 3) # (a ceiling, never a floor)
self.assertEqual(build_jobs.cap(12, {"HOOKSHOT_JOBS": "0"}), 12)
self.assertEqual(build_jobs.cap(12, {"HOOKSHOT_JOBS": "x"}), 12) # (make_game.py refuses it at its start)
os.environ["HOOKSHOT_JOBS"] = "2"
self.assertEqual(build_jobs.cap(12), 2)
def test_make_game_keeps_its_parsing(self):
self.assertEqual(make_game.requested_jobs("6"), 6)
self.assertIsNone(make_game.requested_jobs("0"))
with self.assertRaises(ValueError):
make_game.requested_jobs("-2")
class MainExports(Clean):
def main(self, jobs):
with tempfile.TemporaryDirectory() as work, mock.patch.object(make_game, "check", return_value=0), \
redirect_stdout(io.StringIO()):
make_game.main(types.SimpleNamespace(jobs=jobs, work=work, check=True))
return os.environ.get("HOOKSHOT_JOBS")
def test_a_given_count_reaches_the_steps(self):
self.assertEqual(self.main(3), "3")
def test_one_in_the_environment_stays(self):
os.environ["HOOKSHOT_JOBS"] = "5"
self.assertEqual(self.main(None), "5")
os.environ["HOOKSHOT_JOBS"] = "5"
self.assertEqual(self.main(2), "2") # (--jobs over the environment, as chosen_jobs takes it)
def test_none_given_sets_none(self):
self.assertIsNone(self.main(None))
self.assertIsNone(self.main(0)) # (0: automatic)
class LiftPool(Clean):
"""(Triforce) the lift's emit processes (nx2/chunks.py emit_jobs) take at most the count"""
def jobs(self):
with mock.patch.object(chunks, "_available_gb", return_value=64.0), \
mock.patch.object(chunks.os, "sched_getaffinity", create=True, return_value=set(range(16))):
return chunks.emit_jobs()
def test_at_most_the_count(self):
os.environ["HOOKSHOT_JOBS"] = "4"
self.assertLessEqual(self.jobs(), 4)
def test_nothing_asked_the_cores(self):
self.assertGreater(self.jobs(), 4 if chunks.FORK else 0)
CPUS_SCRIPT = "import os; print('cpus %d' % len(os.sched_getaffinity(0)), flush=True)"
@unittest.skipUnless(AFFINITY and len(os.sched_getaffinity(0)) >= 3,
"the affinity mask from Python, on 3 CPUs or more: Linux")
class PrepareCpus(Clean):
def child_cpus(self, n):
import subprocess
with build_jobs.children_on_cpus(n):
out = subprocess.run([sys.executable, "-I", "-c", CPUS_SCRIPT], capture_output=True, text=True, check=True).stdout
return int(out.split()[1])
def test_the_child_gets_n_and_this_one_its_own_back(self):
mine = os.sched_getaffinity(0)
self.assertEqual(self.child_cpus(2), 2)
self.assertEqual(os.sched_getaffinity(0), mine)
self.assertEqual(self.child_cpus(None), len(mine))
self.assertEqual(self.child_cpus(len(mine) + 4), len(mine))
def prepare(self):
out = io.StringIO()
with redirect_stdout(out):
code = make_game.prepare_shaders([sys.executable, "-I", "-c", CPUS_SCRIPT], str(ROOT))
self.assertEqual(code, 0, out.getvalue())
return int(next(l for l in out.getvalue().splitlines() if l.startswith("cpus ")).split()[1])
def test_the_preparation_on_the_count(self):
mine = len(os.sched_getaffinity(0))
os.environ["HOOKSHOT_JOBS"] = "2"
self.assertEqual(self.prepare(), 2)
os.environ.pop("HOOKSHOT_JOBS")
self.assertEqual(self.prepare(), mine) # (nothing asked: every CPU, as before)
if __name__ == "__main__":
unittest.main()

View File

@@ -481,7 +481,7 @@ def check_source():
steps = (VK / "cache_set_files.h").read_text(encoding="utf-8")
# (once the device is made, before anything opens a cache: mkwvk_init, right after create_device)
init = function(main, "const MkwVkRenderer* mkwvk_init(const MkwVkHost* h) {")
init = function(main, "static const MkwVkRenderer* init_body(const MkwVkHost* h) {") # (mkwvk_init's work, behind its catch: cxx_escape.h)
made = "if (!create_instance() || !pick_device() || !create_device()) return nullptr;"
check(made in init and "cache_set_init();" in init, "mkwvk_init does not decide the caches' kept set")
check(init.index(made) < init.index("cache_set_init();") < init.index("table.version"),

View File

@@ -184,7 +184,7 @@ def fixture(mem):
if "test_thread(" not in code:
raise ValueError("destroy_buffer_later starts no thread")
return (FIXTURE.replace("@FREEBUF@", block(mem, "struct FreeBuf {", ";"))
.replace("@ENVOFF@", block(mem, "bool env_value_off(const char* v) {"))
.replace("@ENVOFF@", block(mem, "bool env_value_off(const char* v) {") + "\n" + block(mem, "bool env_on(const char* name) {"))
.replace("@BLOCK@", code).replace("@EXIT@", block(mem, "void cap_exit_note() {")))

View File

@@ -355,7 +355,10 @@ int main(int argc, char** argv) {
def check_source(mem, replay, texture, dev):
# (every read of a capture buffer's bytes makes its page ready first)
read = block(mem, "bool memory_read_as_submitted(")
before(read, "behind_read(*b, page0, page1)", "std::lock_guard lk(pools_mu)",
before(read, "behind_read(*behind_b, page0, page1)", "std::lock_guard lk(pools_mu)",
"memory_read_as_submitted: the pages of a capture behind are not made ready before the pools' lock")
# ((Triforce) and those of a read through a virtual GPU address over a page's end, each page where it maps)
before(read, "if (behind_b) behind_read(*behind_b, p, p);", "std::lock_guard lk(pools_mu)",
"memory_read_as_submitted: the pages of a capture behind are not made ready before the pools' lock")
before(read, "behind_ready(bc, e.slot);", "std::memcpy((uint8_t*)dst",
"memory_read_as_submitted: a capture's bytes read before the page is ready")
@@ -424,8 +427,27 @@ def check_source(mem, replay, texture, dev):
s = replay.index(seg_submit, at)
check(w < s, "a parallel replay's segment (one of the two paths) is submitted before it is done")
at = s + 1
check(replay.count("vkQueueSubmit2(") == 5, "vk_replay.cpp submits in a place this test does not know: check that the copies "
# (five submits, and submit_again's: one of them made again where the driver refused it for want of memory, the same
# submit at the same place, submit_retry.h)
# ((Triforce) and submit_alone_locked's: an upload command buffer and the pieces it went on in, each a submission of its
# own, sent by the same three places right before their own submit: after texture_uploads_recorded, as that one is)
alone = block(replay, "void submit_alone_locked(")
# ((Triforce) and part_submit's: Threaded rendering's recorder makes a part's submit as submit_recording decided it, posted after
# submit_recording's texture_uploads_recorded (vk_replay.cpp post_part_submit)
before(sub, "texture_uploads_recorded();", "post_part_submit(", "submit_recording: a part handed to the recorder before the copies are done")
check(block(replay, "void part_submit(const PartSubmit& s) {").count("vkQueueSubmit2(") == 1, "part_submit submits more than once")
check(replay.count("vkQueueSubmit2(") == 8 and block(replay, "VkResult submit_again(").count("vkQueueSubmit2(") == 1 and
alone.count("vkQueueSubmit2(") == 1, "vk_replay.cpp submits in a place this test does not know: check that the copies "
"behind are done before it")
before(sub, "texture_uploads_recorded();", "submit_alone_locked(", "submit_recording: an upload's pieces submitted before the copies are done")
check(replay.count("submit_alone_locked(alone.data(), alone.size());") == 3, "the pieces are submitted somewhere this test does not know")
at = 0
for _ in range(2): # (the two segment paths: after the job's wait, right before the segment's own submit)
w = replay.index(seg_wait, at)
s = replay.index(seg_submit, at)
a = replay.index("if (!alone.empty()) submit_alone_locked(alone.data(), alone.size());", w)
check(w < a < s, "a parallel replay's segment's upload pieces are not submitted between its job's end and its own submit")
at = s + 1
# (the submitting thread: the synchronous replay leaves copies behind, and it finishes them before it returns)
q = block(replay, "void submit_q(")
sync = q[:q.index("std::lock_guard lk(submit_order_mu);")]

View File

@@ -70,6 +70,7 @@ HEAD = r"""
#include <cstdlib>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <vector>
#include "cap_spare.h"
@@ -418,6 +419,9 @@ def main():
check("`RX_VK_CAP_SPARE_FIT=0`" in dev and "`RX_VK_CAP_STEP_MB=<n>`" in dev, "docs/development.md: the two switches are not in the switches table")
cut = "\n".join([
# (the switches' rule the capture's own switches are read by: RX_VK_CAPTURE_KEEP_OLD, RX_VK_CAP_BLOCKS)
block(mem, "bool env_value_off(const char* v) {"),
block(mem, "bool env_on(const char* name) {"),
free,
block(mem, "uint64_t cap_buf_size(uint64_t need) {"),
line(mem, "int cap_prewarm_index(uint64_t size) {"),

View File

@@ -174,7 +174,7 @@ def main():
"const bool old_ok = history && s.captured_frame && s.captured_frame == to.last;",
"if (c.k.depth == cam.depth) s.captured_before.put(c.key, c);",
"if (caps.empty() || !make_capture_pipeline()) return 0;",
"const State::Captured* const was = old_ok ? s.captured_before.before(c.key) : nullptr;",
"const State::Captured* const was = old_ok && has[i] ? s.captured_before.before(look[i]) : nullptr;",
"const State::Captured& o = *was;")]
check(at == sorted(at), "capture_motion does not turn the table, fill it with this frame's draws and then look up the frame before's")
check("old.find(" not in motion and "std::unordered_map<uint64_t, State::Captured> old" not in motion,

87
tests/test_chain.py Normal file
View File

@@ -0,0 +1,87 @@
"""scripts/chain.py walks a frame back from its present through waits, signals and virtual-core grants (HOS_CHAIN,
host/hos_chain.c). A made-up recording of three threads, written in the recorder's own format, must come out with the
path's time where it was spent: the presenting thread's run after its wake-up, the main thread's run, the worker's run
before its signal, and a wait for a virtual core inside an event wait kept on the waiting thread (with the thread that
gave the core up).
The recorder's record layout and kinds must match the script's.
python -I -B tests/test_chain.py
"""
import os
import re
import struct
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import chain # noqa: E402
def check_layout():
hdr = (ROOT / "host" / "hos.h").read_text(encoding="utf-8")
m = re.search(r"enum \{ HOS_CHAIN_WAIT = 1, HOS_CHAIN_WOKE, HOS_CHAIN_SIGNAL, HOS_CHAIN_SLEEP, HOS_CHAIN_AWAKE, "
r"HOS_CHAIN_PRESENT \};", hdr)
assert m, "host/hos.h: the HOS_CHAIN kinds changed: update scripts/chain.py and this test"
assert (chain.WAIT, chain.WOKE, chain.SIGNAL, chain.SLEEP, chain.AWAKE, chain.PRESENT) == (1, 2, 3, 4, 5, 6)
src = (ROOT / "host" / "hos_chain.c").read_text(encoding="utf-8")
assert '"%s"' % chain.REC.format in src, "host/hos_chain.c: the record's layout and scripts/chain.py's differ"
assert chain.REC.size == 32 and "} ChainRec;" in src
vc = (ROOT / "host" / "hos_thread.c").read_text(encoding="utf-8")
assert "return 1ULL << 63 | (uint64_t)(uintptr_t)t;" in vc and chain.VCORE == 1 << 63
def write(path, names, recs):
with open(path, "wb") as f:
f.write(b"HOSCHAIN1\n")
for i, n in enumerate(names):
f.write(("thread %d %s\n" % (i, n)).encode())
f.write(("records %d\n" % len(recs)).encode())
for t, kind, th, key, lr in recs:
f.write(chain.REC.pack(t, key, lr, th, kind))
def main():
check_layout()
P, M, W = 0, 1, 2
Q, E, VC = 0x100, 0x200, chain.VCORE | 0x7000
W_, K, S = chain.WAIT, chain.WOKE, chain.SIGNAL
recs = [
(0, chain.PRESENT, P, 0, 0),
(1000, W_, P, Q, 0x10), (5000, S, M, Q, 0x20), (5100, K, P, Q, 0x10), # present thread waits for main
(1000, W_, M, E, 0x30), (4000, S, W, E, 0x40), # main waits for the worker
(4060, W_, M, VC, 0x30), (4150, S, W, VC, 0x50), (4200, K, M, VC, 0x30), # then for a core, granted by it
(4250, K, M, E, 0x30),
(2000, chain.SLEEP, W, 500, 0x60), (2500, chain.AWAKE, W, 500, 0x60), # the worker sleeps 0.5 us
(9000, chain.PRESENT, P, 1, 0),
]
recs.sort()
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "chain.bin")
write(path, ["Presentation", "Main", "Worker"], recs)
names, loaded = chain.load(path)
assert names == {0: "Presentation", 1: "Main", 2: "Worker"}, names
blocks, signals, presents = chain.build(loaded)
acc = chain.Acc()
chain.walk(P, presents[P][1], presents[P][0], blocks, signals, acc)
got = {k: v for k, v in acc.by.items()}
# (the wait for a core is the main thread's own time: contention, not work it waited for; the event's signal before
# it is what the path follows)
want = {(P, "running"): 9000 - 5100, (P, "signal to running"): 100, (M, "running"): 5000 - 4200,
(M, "waiting for a virtual core"): 4200 - 4060, (M, "signal to running"): 4060 - 4000,
(W, "running"): 4000 - 2500 + 2000, (W, "sleep"): 500}
if got != want:
raise SystemExit("FAIL: the path's time\n got %s\n want %s" % (sorted(got.items()), sorted(want.items())))
assert sum(got.values()) == 9000, "the path does not add up to the frame"
assert acc.cores == {(M, W): 140}, acc.cores
want = {(P, "woken at lr 0x10", "the present"): 3900, (M, "woken at lr 0x30", "signal at lr 0x20"): 940,
(W, "the frame before's present", "signal at lr 0x40"): 4000}
assert dict(acc.stretches) == want, "the stretches: %s" % sorted(acc.stretches.items())
assert acc.handn == {(P, 0x10, M, 0x20): 1, (M, 0x30, W, 0x40): 1}, acc.handn
print("PASS: the frame's path through a queue wait, an event wait with a core wait inside it, and a sleep adds up to "
"the frame, each part on its thread")
if __name__ == "__main__":
main()

99
tests/test_chain_input.py Normal file
View File

@@ -0,0 +1,99 @@
"""Game-free HOSCHAIN1 input contract checks: python -I -B tests/test_chain_input.py."""
import contextlib
import io
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import chain
class CaptureInput(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.addCleanup(self.directory.cleanup)
self.path = Path(self.directory.name) / "synthetic.chain"
def capture(self, data):
self.path.write_bytes(data)
return self.path
def main_capture(self, records):
path = self.capture(b"HOSCHAIN1\nthread 0 Presenter\nrecords %d\n" % len(records) + b"".join(records))
old_argv = sys.argv
self.addCleanup(setattr, sys, "argv", old_argv)
sys.argv = ["chain.py", str(path)]
with contextlib.redirect_stdout(io.StringIO()) as output:
chain.main()
return output.getvalue()
def test_single_present_has_no_frame(self):
with self.assertRaisesRegex(SystemExit, "at least two presents"):
self.main_capture([chain.REC.pack(100, 0, 0, 0, chain.PRESENT)])
def test_invalid_header_has_diagnostic(self):
for header in (b"", b"\n", b"thread\n", b"thread nope Name\n", b"thread 0\n",
b"records\n", b"records nope\n", b"records -1\n"):
with self.subTest(header=header):
path = self.capture(b"HOSCHAIN1\n" + header)
with self.assertRaisesRegex(SystemExit, "invalid HOS_CHAIN header"):
chain.load(path)
def test_payload_missing_whole_record(self):
record = chain.REC.pack(100, 0, 0, 0, chain.PRESENT)
for payload in (b"", record):
with self.subTest(size=len(payload)):
path = self.capture(b"HOSCHAIN1\nrecords 2\n" + payload)
with self.assertRaisesRegex(SystemExit, "truncated.*records"):
chain.load(path)
def test_zero_presents_keeps_existing_diagnostic(self):
with self.assertRaisesRegex(SystemExit, "no presents recorded"):
self.main_capture([])
def test_one_present_per_thread_has_no_frame(self):
records = [chain.REC.pack(t, 0, 0, th, chain.PRESENT) for t, th in ((100, 0), (200, 1))]
with self.assertRaisesRegex(SystemExit, "at least two presents"):
self.main_capture(records)
def test_valid_frames_keep_report(self):
for count in (2, 3):
with self.subTest(count=count):
records = [chain.REC.pack(t * 1000000, 0, 0, 0, chain.PRESENT) for t in range(count)]
output = self.main_capture(records)
self.assertIn("%d frames presented by Presenter, 1.00 ms a frame (1000.0 fps)" % (count - 1), output)
self.assertIn("-- the path, a frame (ms): 1.00 in all", output)
def test_valid_records_keep_values_and_stable_time_order(self):
records = [(30, 21, 31, 1, chain.WAIT), (10, 22, 32, 0, chain.PRESENT),
(30, 23, 33, 1, chain.WOKE), (20, 24, 34, 1, chain.SIGNAL),
(40, 25, 35, 0, chain.SLEEP), (50, 26, 36, 0, chain.AWAKE)]
payload = b"".join(chain.REC.pack(*record) for record in records)
path = self.capture(b"HOSCHAIN1\nthread 0 Presenter\nthread 1 Worker\nrecords 6\n" + payload)
names, loaded = chain.load(path)
self.assertEqual(names, {0: "Presenter", 1: "Worker"})
self.assertEqual(loaded, sorted(records, key=lambda record: record[0]))
def test_trailing_bytes_keep_declared_record_boundary(self):
record = chain.REC.pack(100, 0, 0, 0, chain.PRESENT)
path = self.capture(b"HOSCHAIN1\nrecords 1\n" + record + b"unused trailing bytes")
self.assertEqual(chain.load(path), ({}, [chain.REC.unpack(record)]))
def test_bad_magic_keeps_existing_diagnostic(self):
for magic in (b"", b"HOSCHAIN2\n"):
with self.subTest(magic=magic):
with self.assertRaisesRegex(SystemExit, "not a HOS_CHAIN recording"):
chain.load(self.capture(magic))
def test_truncated_declared_payload(self):
record = chain.REC.pack(100, 0, 0, 0, chain.PRESENT)
path = self.capture(b"HOSCHAIN1\nthread 0 Presenter\nrecords 2\n" + record + record[:-1])
with self.assertRaisesRegex(SystemExit, "truncated.*records"):
chain.load(path)
if __name__ == "__main__":
unittest.main()

View File

@@ -107,7 +107,9 @@ def check_source():
check("barrier_rules::part_draws_default(dev.props.vendorID, radv);" in part, "the default is not asked of the rule with the driver")
check(part.rstrip().endswith('return barrier_rules::part_draws(env != nullptr, env_value, lab_ab::value_of("chunk", by_driver));'),
"part_draws does not ask the knob at each call, behind the variable")
check(replay.count('getenv("RX_VK_CHUNK")') == 1, "RX_VK_CHUNK is read somewhere else")
# ((Triforce) and once by Threaded rendering's parts, only to step aside when it is set: pass_end_parts)
ends = function(replay, "PassEndParts& pass_end_parts() {")
check(replay.count('getenv("RX_VK_CHUNK")') == 2 and ends.count('getenv("RX_VK_CHUNK")') == 1, "RX_VK_CHUNK is read somewhere else")
dev = (ROOT / "docs/development.md").read_text(encoding="utf-8")
row = [line for line in dev.splitlines() if line.startswith("| `RX_VK_CHUNK=<n>` |")]
check(len(row) == 1 and "**120 on every driver**" in row[0] and "`chunk:<n>`" in row[0], "docs/development.md: no row for RX_VK_CHUNK with its default")

View File

@@ -283,11 +283,11 @@ def check_compile(tmp, cc, preamble, fns, text):
def check_sources():
with open(os.path.join(ROOT, "nx2", "build.py"), encoding="utf-8") as f:
build = f.read()
for line in (' srcs, cold = cold_parts.expand(srcs, os.path.join(out, "split"), os.environ, stats=cold_stats)\n',
for line in (' srcs, cold = (srcs, set()) if KEPT else cold_parts.expand(srcs, os.path.join(out, "split"), os.environ, stats=cold_stats)\n',
" cold_fl = cold_parts.cold_flags(fl, a.opt, os.environ) if cold else fl",
' hot_fl if os.path.basename(s).startswith("code_hot") else cold_fl if s in cold else fl,\n'):
' hot_fl if os.path.basename(s).startswith("code_hot") else cold_fl if s in cold else\n'):
check("nx2/build.py no longer has the line %r" % line.strip(), build.count(line) == 1)
at = [build.find(p) for p in (" srcs, cold = cold_parts.expand(", " srcs.sort(key=lambda s: -compile_cost(s, costs))",
at = [build.find(p) for p in (" srcs, cold = (srcs, set()) if KEPT else cold_parts.expand("," srcs.sort(key=lambda s: -compile_cost(s, costs))",
" cold_fl = cold_parts.cold_flags(", " jobs = [(cc, s, os.path.join(obj_dir,")]
check("nx2/build.py expands its sources before it orders them and makes the jobs", min(at) >= 0 and at == sorted(at))
with open(os.path.join(ROOT, "nx2", "make_game.py"), encoding="utf-8") as f:

View File

@@ -58,7 +58,44 @@ def main():
costs = dict(l.split() for l in Path(d, chunks.COSTS).read_text().splitlines())
check("every chunk and part has a cost", set(costs) == {os.path.basename(p) for p in [files[0]] + parts})
check("a part's cost is its estimate", all(int(costs[os.path.basename(p)]) == chunks.text_cost(t) for p, t in zip(parts, texts)))
print("ok: %d parts, the functions as they were" % len(parts))
stopped_part_way(budget)
print("ok: %d parts, the functions as they were, and again after a split stopped part way" % len(parts))
def stopped_part_way(budget):
"""A split that stops after its first file (its process ended) leaves the chunk whole: the next split cuts it again"""
with tempfile.TemporaryDirectory(prefix="hookshot-chunk-stop-") as d:
big = [function(0x81000000 + 16 * i, 2000) for i in range(40)] + [function(0x81100000, 300000)] + [
function(0x81200000 + 16 * i, 2000) for i in range(200)]
path = os.path.join(d, "code_001.c")
Path(path).write_text(PREAMBLE + "".join(big), newline=chr(10))
class Stopped(Exception):
pass
real = chunks.whole_write.write_whole
writes = []
def stop_after_one(out, text, *a, **k):
if writes:
raise Stopped()
writes.append(out)
return real(out, text, *a, **k)
chunks.whole_write.write_whole = stop_after_one
try:
chunks.split_one(d, path, budget)
check("the chunk is cut into parts, so a split can stop between two of them", False)
except Stopped:
pass
finally:
chunks.whole_write.write_whole = real
made = chunks.split_big(d, [path], budget=budget)
parts = [path] + sorted(made, key=lambda p: int(re.search(r"_(\d+)\.c$", p).group(1)))
texts = []
for p in parts:
with open(p, newline="") as f:
texts.append(f.read())
check("after a stopped split the chunk is cut again", len(parts) >= 2)
check("after a stopped split every function is still there", "".join(t[len(PREAMBLE):] for t in texts) == "".join(big))
if __name__ == "__main__":

View File

@@ -0,0 +1,44 @@
"""A damaged chunks.txt is ignored, and chunks.save replaces it whole (nx2/chunks.py, issue ).
<work>/image/chunks.txt (the lift's chunk boundaries) outlives the lift, and the launcher's completely cold build keeps image/.
On Windows a PC that went down while the file was being written left it full of null bytes, and every later lift stopped in
chunks.write with `ValueError: invalid literal for int() with base 16: '\\x00\\x00...'` until the player deleted the work
folder. load() now answers no boundaries for a file it cannot read (the lift then takes them from the sizes, as without the
file), and save() writes beside the file and moves it over, so a stopped write leaves the old file whole.
python -I -B tests/test_chunks_corrupt.py
"""
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "nx2"))
import kit # noqa: E402,F401 (a64-kit on the path)
import chunks # noqa: E402
def main():
with tempfile.TemporaryDirectory(prefix="triforce-chunks-corrupt-") as temp:
image = Path(temp) / "image"
image.mkdir()
path = image / chunks.FILE
# (the reported file: 688 null bytes, no newline, what NTFS shows of a file whose data never reached the disk)
path.write_bytes(b"\x00" * 688)
got = chunks.load(str(image))
assert got == [], "a chunks.txt of null bytes gave boundaries: %r" % got[:4]
# (bytes that are not text at all, and a line that is not an address)
for bad in (b"\xff\xfe\x80\x81\n", b"# first guest address\n80001000\nnot hex\n"):
path.write_bytes(bad)
got = chunks.load(str(image))
assert got == [], "a damaged chunks.txt (%r) gave boundaries: %r" % (bad, got)
# (the lift saves new boundaries over the damaged file: they are read back, and no staged file is left beside them)
chunks.save(str(image), [0x80002000, 0x80001000])
assert chunks.load(str(image)) == [0x80001000, 0x80002000], chunks.load(str(image))
left = sorted(p.name for p in image.iterdir() if p.name != chunks.FILE)
assert not left, "chunks.save left files beside chunks.txt: %s" % left
print("a damaged chunks.txt is ignored and replaced whole: ok")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,37 @@
"""chunks.save makes the folder it records the boundaries in (nx2/chunks.py).
`python -I nx2/lift.py --standalone --write` writes the boundaries to <work>/image/chunks.txt, while the image goes
to <work>/sa/image; on a fresh work folder nothing had made <work>/image, and the lift stopped after its translation
with FileNotFoundError, at the last step (make_game.py prepares the folder, the documented command did not).
python -I -B tests/test_chunks_save_folder.py
"""
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "nx2"))
import kit # noqa: E402,F401 (a64-kit on the path)
import chunks # noqa: E402
def main():
with tempfile.TemporaryDirectory(prefix="triforce-chunks-save-") as temp:
# (a standalone lift's folder: <work>/image, with <work> existing and image/ not)
work = Path(temp) / "work"
work.mkdir()
image = work / "image"
assert not image.exists(), "the fixture must start without the folder"
chunks.save(str(image), [0x80002000, 0x80001000])
path = image / chunks.FILE
assert path.is_file(), "chunks.save did not make its folder: %s" % path
assert chunks.load(str(image)) == [0x80001000, 0x80002000], chunks.load(str(image))
# (as lift.py does on a later lift: the folder is there and the file is replaced, not appended)
chunks.save(str(image), [0x80003000])
assert chunks.load(str(image)) == [0x80003000], chunks.load(str(image))
print("chunks.save makes <work>/image and writes the boundaries: ok")
if __name__ == "__main__":
main()

201
tests/test_cmpflags.py Normal file
View File

@@ -0,0 +1,201 @@
"""(Triforce) nx2/cmpflags.py (A64_SUB_V): a subtraction's V written as N xor (a < b, signed), game-free.
Python, no compiler:
- rewrite() replaces SetFlags' subtraction V at both widths and nothing else; A64_SUB_V=0 leaves translate as it was.
C (skipped without a compiler or on a host that is not x86-64), with a64emit built here as tests/test_fpx_sticky.py builds it:
- the guest words below go through a64emit.translate twice, as the lift has it now (cmpflags on) and as before (the
translate it wraps). The subtraction forms (SUBS and CMP immediate, shifted and extended register, 32 and 64 bits, and
CCMP register and immediate) must differ only in V's text; the others (ADDS, CMN, ADCS, SBCS, ANDS, CCMN) must be the
same text;
- tests/cmpflags_test.c runs both from one Ctx and compares the whole Ctx after (every register, N, Z, C, V): every pair
of 40 edge values (0, 1, -1, the signed and unsigned extremes at 32 and 64 bits and their neighbours) in the two source
registers, under every NZCV the instruction may read (CCMP), then 2,000,000 random states a word; built at -O1 (the
lifted code's level) and -O2 (the hot pieces').
It has teeth: with NEW's compare unsigned, or its sign bit taken from _fa, the C check fails (by hand, 2026-11-20).
python -I -B tests/test_cmpflags.py [--cc clang] [--cxx clang++] [--random 2000000]
"""
import argparse
import os
import platform
import sys
import tempfile
import time
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(ROOT, "tests"))
sys.path.insert(0, os.path.join(ROOT, "nx2"))
# ((Triforce) the form under test: A64_SUB_V=1 or ovf. install() runs once a process and reads it then, so main() runs this
# file again for each form; the lift's default here is off)
FORM = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--form=")), None)
os.environ.pop("A64_SUB_V", None)
if FORM:
os.environ["A64_SUB_V"] = FORM
import test_fpx_sticky as fs # noqa: E402 (its compiler, target, build and run helpers; its paths on sys.path)
SEED = 20261120
# (assembly, word, a subtraction whose V is rewritten)
WORDS = (
("cmp x1, x2", 0xEB02003F, 1), ("cmp w1, w2", 0x6B02003F, 1), ("subs x3, x1, x2", 0xEB020023, 1),
("subs w3, w1, w2, lsl #3", 0x6B020C23, 1), ("cmp x1, #5", 0xF100143F, 1), ("cmp w1, #4095", 0x713FFC3F, 1),
("subs x3, x1, #1, lsl #12", 0xF1400423, 1), ("cmp x1, w2, sxtw", 0xEB22C03F, 1), ("subs w3, w1, w2, uxtb #2", 0x6B220823, 1),
("ccmp x1, x2, #0, lt", 0xFA42B020, 1), ("ccmp w1, #3, #5, ne", 0x7A431825, 1),
("adds x3, x1, x2", 0xAB020023, 0), ("cmn w1, #7", 0x31001C3F, 0), ("adcs x3, x1, x2", 0xBA020023, 0),
("sbcs w3, w1, w2", 0x7A020023, 0), ("ands x3, x1, x2", 0xEA020023, 0), ("ccmn x1, x2, #2, ge", 0xBA42A022, 0),
)
def fail(msg):
raise SystemExit("cmpflags: FAIL: " + msg)
def check_python():
import cmpflags
t64 = "{ uint64_t _fa=(_a),_fb=(_b),_fr=(_r); c->z=(_fr==0); c->n=(int)((_fr>>63)&1); c->c=(_fa>=_fb); " + cmpflags.OLD[64] + " }"
t32 = t64.replace("uint64_t", "uint32_t").replace("(_a)", "(uint32_t)(_a)").replace(">>63", ">>31").replace(cmpflags.OLD[64], cmpflags.OLD[32])
add = "c->v=(int)((((uint64_t)~(_fa^_fb)&(_fa^_fr))>>63)&1); }"
if cmpflags.NEW[64] not in cmpflags.rewrite(t64) or cmpflags.OLD[64] in cmpflags.rewrite(t64):
fail("the 64-bit subtraction's V not rewritten")
if cmpflags.NEW[32] not in cmpflags.rewrite(t32) or cmpflags.OLD[32] in cmpflags.rewrite(t32):
fail("the 32-bit subtraction's V not rewritten")
if cmpflags.rewrite(add) != add:
fail("an addition's V rewritten")
for new in [v for form in cmpflags.FORMS.values() for v in form.values()]:
if "c->n" in new.split("=", 1)[1] or ";" in new[:-1]:
fail("NEW reads N from the context, or holds a ';' (dead_flags cuts a store at its first one): " + new)
print("cmpflags: python checks passed")
def lifted_cases(a64emit, cmpflags):
words = [(0x1000 + 4 * i, w) for i, (_, w, _) in enumerate(WORDS)]
now, fl = a64emit.translate(words)
if any(fl):
fail("a64emit did not translate the guest words: %s" % fl)
old, _ = cmpflags._base[0](words)
out = ["/* Generated by tests/test_cmpflags.py: each word as the lift translates it now and as before. */"]
for i, ((asm, w, sub), n, o) in enumerate(zip(WORDS, now, old)):
if sub:
if n == o or any(x in n for x in cmpflags.OLD.values()) or not any(x in n for x in cmpflags.NEW.values()):
fail("%s: V not rewritten: %s" % (asm, n[:400]))
if n.replace(cmpflags.NEW[64], cmpflags.OLD[64]).replace(cmpflags.NEW[32], cmpflags.OLD[32]) != o:
fail("%s: more than V's text changed" % asm)
elif n != o:
fail("%s: not a subtraction's V, but its text changed:\n before %s\n now %s" % (asm, o[:300], n[:300]))
out.append("static void g_now%d(Ctx *__restrict c) { %s }" % (i, n))
out.append("static void g_old%d(Ctx *__restrict c) { %s }" % (i, o))
out.append("static const struct { const char *name; int sub; void (*now)(Ctx *), (*old)(Ctx *); } CASES[] = {%s};"
% ", ".join('{"%s", %d, g_now%d, g_old%d}' % (asm, sub, i, i) for i, (asm, _, sub) in enumerate(WORDS)))
return "\n".join(out) + "\n"
def generate(cxx, tmp, flags):
dll = os.path.join(tmp, "a64emit.dll" if os.name == "nt" else "liba64emit.so")
fs.build([cxx, "-std=c++20", "-O0", "-shared", "-Wno-everything", "-o", dll, os.path.join(fs.KIT, "lift", "a64emit.cpp")]
+ flags + ([] if os.name == "nt" else ["-fPIC"]), "a64emit")
import build_emit
build_emit.build = lambda force=False: dll
import a64_rtgen
import a64emit
# The lift imports these for discovery, not for translating these words.
import importlib
import types
class Stub(types.ModuleType):
def __getattr__(self, name):
if name.startswith("__"):
raise AttributeError(name)
return 0
for name in ("capstone", "lz4", "lz4.block", "numpy"):
try:
importlib.import_module(name)
except ImportError:
sys.modules[name] = Stub(name)
import lift # noqa: F401 (installs the actual lift's translate wrappers)
import cmpflags
if not cmpflags._base:
fail("lift did not install cmpflags")
try:
# A batch without the old expression must bypass the per-instruction rewrite.
words = [(0x1000, 0xEA020023)] # ANDS x3, x1, x2
expected = cmpflags._base[0](words)
rewrite = cmpflags.rewrite
try:
def unexpected_rewrite(text):
fail("rewrite called for a batch without subtraction V")
cmpflags.rewrite = unexpected_rewrite
if a64emit.translate(words) != expected:
fail("batch without subtraction V changed")
finally:
cmpflags.rewrite = rewrite
a64_rtgen.write(tmp)
lifted = lifted_cases(a64emit, cmpflags)
finally:
if a64emit._lib is not None:
import _ctypes
(_ctypes.FreeLibrary if os.name == "nt" else _ctypes.dlclose)(a64emit._lib._handle)
a64emit._lib = None
with open(os.path.join(tmp, "cmpflags_lifted.h"), "w", newline="\n") as f:
f.write(lifted)
import a64_lift
with open(os.path.join(tmp, "a64_fpx.h"), "w", newline="\n") as f: # (a64.h includes it; no float op here)
f.write(a64_lift.fpx_header(set()))
def check_off():
"""A64_SUB_V=0: install() leaves translate alone (a new interpreter: install runs once a process)"""
import subprocess
for off in ("0", None): # ((Triforce) unset is off too: the default)
code = ("import os, sys; sys.path.insert(0, sys.argv[1]); os.environ.pop('A64_SUB_V', None)\n"
+ ("os.environ['A64_SUB_V'] = '0'\n" if off else "") +
"import kit, a64emit, cmpflags\nt = a64emit.translate\ncmpflags.install()\n"
"print('same' if a64emit.translate is t and not cmpflags._base else 'wrapped')\n")
r = subprocess.run([sys.executable, "-I", "-B", "-c", code, os.path.join(ROOT, "nx2")], capture_output=True, text=True)
if r.stdout.strip() != "same":
fail("A64_SUB_V %s still wraps translate: %s %s" % ("=0" if off else "unset", r.stdout, r.stderr[-500:]))
print("cmpflags: A64_SUB_V=0 and unset leave translate as it was")
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--cc")
p.add_argument("--cxx")
p.add_argument("--random", type=int, default=2000000)
p.add_argument("--form", help="1 or ovf: the form to check (without it: both, each in a process of its own)")
a = p.parse_args()
if not a.form:
import subprocess
check_off()
for form in ("1", "ovf"):
r = subprocess.run([sys.executable, "-I", "-B", os.path.abspath(__file__), "--form=" + form] + sys.argv[1:])
if r.returncode:
fail("A64_SUB_V=%s (exit %d)" % (form, r.returncode))
print("cmpflags: both forms pass")
return
check_python()
if platform.machine().lower() not in ("x86_64", "amd64"):
fs.skip("not an x86-64 host: %s" % platform.machine())
cc = fs.compiler(a.cc, "CC", ("clang", "gcc", "cc"), "clang")
cxx = fs.compiler(a.cxx, "CXX", ("clang++", "g++", "c++"), "clang++")
if not cc or not cxx:
fs.skip("no C compiler" if not cc else "no C++ compiler")
t0 = time.time()
failed = []
with tempfile.TemporaryDirectory(prefix="triforce-cmpflags-") as tmp:
generate(cxx, tmp, fs.target_flags(cxx, tmp))
for opt in ("-O1", "-O2"):
exe = os.path.join(tmp, "cmpflags_test%s.exe" % opt)
fs.build([cc] + fs.target_flags(cc, tmp) + ["-march=x86-64", "-ffp-contract=off", "-fno-strict-aliasing", opt,
"-D_CRT_SECURE_NO_WARNINGS", "-I" + os.path.join(fs.KIT, "rt"), "-I" + tmp,
os.path.join(ROOT, "tests", "cmpflags_test.c"), os.path.join(tmp, "a64_suyu.c"), "-o", exe],
"the driver at " + opt)
for args in (["sweep"], ["random", str(a.random), str(SEED)]):
r = fs.run([exe] + args, timeout=1800)
print("%-4s %s" % (opt, r.stdout.rstrip()))
if r.returncode:
failed.append("%s %s (exit %d)" % (opt, args[0], r.returncode))
if failed:
fail("%s in %.1f s" % (", ".join(failed), time.time() - t0))
print("cmpflags: pass in %.1f s" % (time.time() - t0))
if __name__ == "__main__":
main()

View File

@@ -298,7 +298,7 @@ def read_sources():
fail("gpu/vk/%s:%d: a nothrow new outside a NoWait scope: at the commit limit it waits 5 s for a null it has "
"its own answer to" % (path.name, i + 1))
main = (VK / "vk_main.cpp").read_text(encoding="utf-8")
init = block(main, "const MkwVkRenderer* mkwvk_init(const MkwVkHost* h) {")
init = block(main, "static const MkwVkRenderer* init_body(const MkwVkHost* h) {") # (mkwvk_init's work, behind its catch: cxx_escape.h)
if "std::set_new_handler(new_refused);" not in init:
fail("vk_main.cpp mkwvk_init does not set the renderer's new handler")
refused = block(main, "void new_refused() {")

125
tests/test_compile_level.py Normal file
View File

@@ -0,0 +1,125 @@
"""Compile shaders, All or Most: how much of the driver's work the shader preparation does before the title.
What must hold: gpu/vk/compile_level.h's rules (compiled and run here, no game or GPU): All unless RX_VK_COMPILE_SHADERS says
most or the options file's compile_shaders= is 1 (the switch over the file; anything else as not set); the prediction runs
before the title on All after a preparation that translated, or where a preparation on Most left it owed, never on Most; the
mark is left on Most only where All would have run it; the compute switches' own values win, and on Most an unset one is
"listed". And the sources: every caller of predict_run asks predict_before_title, which keeps and clears the mark; prepare_run's
compute warm and the precompile's compute programs take the switches through compile_level::computes; the Debug tab's row
and its default (All); the switch in docs/development.md.
python -I -B tests/test_compile_level.py [--cxx g++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
PROGRAM = r"""
#include "compile_level.h"
#include <cstdio>
#include <cstring>
using namespace compile_level;
static int failed = 0;
#define CHECK(x) do { if (!(x)) { std::printf("FAIL line %d: %s\n", __LINE__, #x); failed++; } } while (0)
int main() {
const char* from = nullptr;
CHECK(level(nullptr, -1, &from) == kAll && !std::strcmp(from, "the default"));
CHECK(level(nullptr, 0) == kAll);
CHECK(level(nullptr, 1, &from) == kMost && !std::strcmp(from, "the Compile shaders row"));
CHECK(level(nullptr, 7) == kAll);
CHECK(level("most", 0, &from) == kMost && !std::strcmp(from, "RX_VK_COMPILE_SHADERS"));
CHECK(level("all", 1) == kAll);
CHECK(level("", 1) == kMost); // (empty: not set, the file decides)
CHECK(level("bogus", -1) == kAll); // (not a level: not set)
CHECK(level("bogus", 1) == kMost);
// (the prediction before the title)
CHECK(predict_now(kAll, true, false));
CHECK(predict_now(kAll, false, true)); // (owed by a preparation on Most)
CHECK(!predict_now(kAll, false, false)); // (nothing translated, nothing owed: as before)
CHECK(!predict_now(kMost, true, false));
CHECK(!predict_now(kMost, true, true));
CHECK(mark_owed(kMost, true));
CHECK(!mark_owed(kMost, false));
CHECK(!mark_owed(kAll, true));
// (the compute switches)
CHECK(computes(kAll, nullptr) == nullptr);
CHECK(!std::strcmp(computes(kMost, nullptr), "listed"));
CHECK(!std::strcmp(computes(kMost, ""), "listed"));
CHECK(!std::strcmp(computes(kMost, "all"), "all"));
CHECK(!std::strcmp(computes(kAll, "listed"), "listed"));
CHECK(!std::strcmp(computes(kAll, "none"), "none"));
if (failed) return 1;
std::printf("compile_level: all checks passed\n");
return 0;
}
"""
def need(where, text, needles):
for needle in needles:
if needle not in text:
raise SystemExit(where + " no longer has: " + needle)
def body(text, head):
start = text.index(head)
return text[start:text.index("\n}\n", start)]
def check_source():
vk = ROOT / "gpu/vk"
draw = (vk / "vk_draw.cpp").read_text(encoding="utf-8")
main = (vk / "vk_main.cpp").read_text(encoding="utf-8")
menu = (vk / "vk_menu.cpp").read_text(encoding="utf-8")
menu_h = (vk / "vk_menu.h").read_text(encoding="utf-8")
need("vk_draw.cpp", draw, ['#include "compile_level.h"'])
level = body(draw, "compile_level::Level compile_level_now() {")
need("vk_draw.cpp: compile_level_now()", level,
['"triforce_options.ini"', '"compile_shaders="', 'compile_level::level(getenv("RX_VK_COMPILE_SHADERS"), ini, &from)'])
before = body(draw, "bool predict_before_title(bool prepared) {")
need("vk_draw.cpp: predict_before_title()", before,
["compile_level::mark_owed(level, prepared)", "compile_level::predict_now(level, prepared, owed)",
"!predicted_read(pstamp).count(kPredictedAll)", "remove(mark.c_str())", "warmed_stamp(gpl_wanted())"])
run = body(draw, "void predict_run(void (*progress)(size_t done, size_t total)) {")
need("vk_draw.cpp: predict_run()", run, ["remove(predict_most_path().c_str());"])
# (every caller of predict_run asks first)
lines = main.split("\n")
calls = [i for i, line in enumerate(lines) if "predict_run(" in line and "void predict_run" not in line]
asked = [i for i in calls if any("predict_before_title(" in lines[j] for j in range(max(0, i - 4), i + 1))]
if len(calls) != 3 or asked != calls:
raise SystemExit("vk_main.cpp: a predict_run call that does not ask predict_before_title: %r" %
[lines[i] for i in calls if i not in asked])
prepare = body(draw, "bool prepare_run(void (*progress)(size_t done, size_t total), bool background) {")
need("vk_draw.cpp: prepare_run()", prepare,
['compile_level::computes(compile_level_now(), getenv("RX_VK_WARM_COMPUTES"))', "computes_named(true)"])
need("vk_draw.cpp: precompile_run()", body(draw, "void precompile_run(void (*progress)(size_t done, size_t total)) {"),
['compile_level::computes(compile_level_now(), getenv("RX_VK_PRECOMPILE_COMPUTES"))'])
need("vk_menu.cpp", menu, ['{TAB_DEBUG, "Compile shaders", &opts.compile_shaders, 0, 1, 1, tx_compile_shaders,'])
need("vk_menu.h", menu_h, ["int compile_shaders = 0;"])
need("docs/development.md", (ROOT / "docs/development.md").read_text(encoding="utf-8"),
["`RX_VK_COMPILE_SHADERS=all` or `most`"])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
check_source()
with tempfile.TemporaryDirectory(prefix="compile-level-") as tmp:
src = Path(tmp) / "compile_level_test.cpp"
src.write_text(PROGRAM, encoding="utf-8")
exe = Path(tmp) / "compile-level"
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-I" + str(ROOT / "gpu/vk"), str(src), "-o",
str(exe)], check=True)
subprocess.run([str(exe)], check=True)
print("PASS: Compile shaders: All by default, Most from the row or RX_VK_COMPILE_SHADERS; the prediction before the title "
"only on All (and once owed after Most); the compute switches listed on Most where unset")
if __name__ == "__main__":
main()

View File

@@ -35,7 +35,9 @@ def actual_coordinator(source):
wrapper = ast.parse('def run_compile_jobs():\n return 0\n').body[0]
wrapper.body = main.body[start:end + 1] + wrapper.body
module = ast.fix_missing_locations(ast.Module(body=[compile_one, wrapper], type_ignores=[]))
scope = dict(os=os, time=time, concurrent=concurrent, GATE=None, no_throttle=lambda handle: None, MEM_LOG=False)
# (DEPFILE_DEPS, DEPFILE_PENDING: compile_one leaves an object keyed by a depfile to rekey_depfiles; these jobs have none)
scope = dict(os=os, time=time, concurrent=concurrent, GATE=None, no_throttle=lambda handle: None, MEM_LOG=False,
DEPFILE_DEPS=b"depfile:", DEPFILE_PENDING="depfile-pending")
exec(compile(module, str(source), 'exec'), scope)
return scope
@@ -95,7 +97,7 @@ class CompileRetryJobsTests(unittest.TestCase):
OBJ_CACHE=str(self.cache), PLANNED={(job[1], job[2]): keys[job[2]] for job in jobs},
cache_put=lambda obj, key: cached.append((obj, key)), counted=counted,
expected={str(self.source): [11, 22]}, pending=[11, 22], eta_jobs=2,
eta_left=lambda pending, jobs: sum(pending) / jobs)
eta_left=lambda pending, jobs: sum(pending) / jobs, src_size=os.path.getsize)
log = io.StringIO()
with redirect_stdout(log):
result = self.scope['run_compile_jobs']()

View File

@@ -20,6 +20,10 @@ class CompilerFailureTests(unittest.TestCase):
functions = [node for node in source.body if isinstance(node, ast.FunctionDef)
and node.name in ('compile_one', 'cache_put')]
self.assertEqual(len(functions), 2)
constants = [node for node in source.body if isinstance(node, ast.Assign) # (what compile_one tells a depfile key by)
and any(isinstance(t, ast.Name) and t.id in ('DEPFILE_DEPS', 'DEPFILE_PENDING') for t in node.targets)]
self.assertEqual(len(constants), 2)
functions[:0] = constants
with tempfile.TemporaryDirectory(prefix='hookshot-compiler-failure-') as temporary:
folder = Path(temporary)
compiler = folder / 'compiler.py'

View File

@@ -0,0 +1,50 @@
"""How many of the GPU driver's compute compiles run at once (gpu/vk/compute_gate.h, used by gpu/vk/vk_draw.cpp ComputeTurn).
Compile and run the rule and the gate (tests/compute_gate_test.cpp): the budget the available memory gives, one compile always
starting when none runs, the weights, the cgroup's room, and the gate under threads. And the wiring: every guarded compute
creation takes a turn first (guarded_compute), and the gate is set by the memory only on Mesa's Intel driver and on RADV with
an integrated GPU on a PC with under 13 GB of RAM (compute_gate_radv); RX_VK_COMPUTE_AT_ONCE says otherwise on any GPU.
No Vulkan, GPU or game. python -I -B tests/test_compute_gate.py [--cxx g++]
"""
import argparse
import subprocess
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cxx", "{cxx}"]
ROOT = Path(__file__).resolve().parents[1]
def check_source():
draw = (ROOT / "gpu/vk/vk_draw.cpp").read_text(encoding="utf-8")
at = draw.index("VkResult guarded_compute(VkPipelineCache cache")
body = draw[at:draw.index("\n}\n", at)]
if body.find("const ComputeTurn turn(*ci);") < 0 or body.find("const ComputeTurn turn(*ci);") > body.find("guarded_compute_once("):
raise SystemExit("guarded_compute no longer takes the memory gate's turn before it compiles")
gate = draw[draw.index("compute_gate::Gate& compute_compiles() {"):draw.index("bool compute_pinned(")]
if "} else if (intel || compute_gate_radv()) {" not in gate:
raise SystemExit("the gate's default is no longer Mesa's Intel driver's and RADV's on a small integrated PC alone")
if gate.count("gate.set(") != 2:
raise SystemExit("the gate is set somewhere else: any other GPU must keep no limit unless RX_VK_COMPUTE_AT_ONCE asks")
shader = (ROOT / "gpu/vk/vk_shader.cpp").read_text(encoding="utf-8")
if "return compute_gate::radv_by_memory(true, ram_mb);" not in shader:
raise SystemExit("compute_gate_radv no longer asks compute_gate.h's rule")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cxx", default="g++")
args = parser.parse_args()
check_source()
with tempfile.TemporaryDirectory(prefix="compute-gate-") as tmp:
exe = Path(tmp) / "compute-gate"
subprocess.run([args.cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-D_CRT_SECURE_NO_WARNINGS", "-pthread",
str(ROOT / "tests/compute_gate_test.cpp"), "-o", str(exe)], check=True)
subprocess.run([str(exe)], check=True, timeout=120)
print("ok")
if __name__ == "__main__":
main()

View File

@@ -142,7 +142,7 @@ def check_source():
if at < 0:
raise SystemExit("vk_draw.cpp has no pin_compute")
pin = draw[at:draw.index("\n}\n", at)]
first = "if (mode == compute_pin::Mode::All) return pin_subgroup(st, p.workgroup[0]);"
first = "if (mode == compute_pin::Mode::All) return pin_subgroup(st, p.workgroup[0], invocations);"
if first not in pin or min(pin.find(n) for n in ("compute_pin::Facts f;", "st_pin_free++", "st_pin_pinned++")) < pin.index(first):
raise SystemExit("pin_compute: with RX_VK_COMPUTE_PIN=all it is not pin_subgroup as it was, before anything is asked or counted")
for needle in ("f.vote = i.uses_subgroup_vote", "f.mask = i.uses_subgroup_mask", "f.lane_index = i.uses_subgroup_invocation_id",
@@ -152,7 +152,7 @@ def check_source():
"if (!compute_pin::needed(mode, f)) {"):
if needle not in pin:
raise SystemExit("pin_compute does not fill the rule's facts: " + needle)
if pin.index("if (!compute_pin::needed(mode, f)) {") > pin.rindex("pin_subgroup(st, p.workgroup[0]);"):
if pin.index("if (!compute_pin::needed(mode, f)) {") > pin.rindex("pin_subgroup(st, p.workgroup[0], invocations);"):
raise SystemExit("pin_compute pins before it asks the rule")
# the four makers of a compute program's pipeline, and the two that are not asked
makers = (("bool prepare_compute_pipeline(Program& p) {", "pin_compute(ci.stage, p);"),

View File

@@ -0,0 +1,38 @@
"""A compute program's pipeline is read and published atomically in vk_draw.cpp.
The dispatch's build worker, the dispatch itself and the precompile's threads write Program::compute_pipeline while other
recording threads read it (dispatch() reads it before taking ParLock). Plain reads and writes of it there were a data
race. Every use of it in vk_draw.cpp now goes through std::atomic_ref (release stores, acquire loads), and the
synchronous build makes the pipeline into a local and publishes it only once made.
python -I -B tests/test_compute_pipeline_atomic.py
"""
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def main():
src = (ROOT / "gpu" / "vk" / "vk_draw.cpp").read_text(encoding="utf-8")
uses = 0
plain = []
for n, line in enumerate(src.splitlines(), 1):
code = line.split("//", 1)[0]
for m in re.finditer(r"\bcompute_pipeline\b", code):
if code[m.end():m.end() + 1] == "_":
continue
uses += 1
if "std::atomic_ref<VkPipeline>(" not in code[max(0, m.start() - 40):m.start()]:
plain.append(f"{n}: {line.strip()}")
if uses < 5:
raise SystemExit("compute_pipeline is barely used in vk_draw.cpp now: this test needs updating")
if plain:
raise SystemExit("compute_pipeline used without std::atomic_ref:\n" + "\n".join(plain))
if "cached_compute(&ci, &p.compute_pipeline)" in src:
raise SystemExit("the synchronous build writes compute_pipeline in place, before it is made")
print(f"compute_pipeline: {uses} uses in vk_draw.cpp, all atomic")
if __name__ == "__main__":
main()

60
tests/test_control.py Normal file
View File

@@ -0,0 +1,60 @@
"""The control bridge (host/control.c) against a fake game, over its real transport: tests/control_test.c is built with
host/control.c (HOS_CONTROL_NO_GAME: no game behind it) and drives it as a client. Valid commands, malformed JSON, unknown
commands, oversized lines, clients that disconnect mid-command or never read, too many clients, the socket's mode, a file
in the way (Linux) or the pipe's name and DACL (Windows), quit, relaunch (refused by a game that cannot, and the
socket let go of before the game's relaunch runs), and guest memory at each HOS_CONTROL_MEM level. Linux
drives the Unix socket, Windows the named pipe.
python -I -B tests/test_control.py [--cc gcc] [--source-root OTHER_CHECKOUT]
"""
import argparse
import os
import subprocess
import sys
import tempfile
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--cc", default="gcc")
p.add_argument("--source-root", type=Path, default=ROOT, help="compile the bridge and its header from this checkout")
a = p.parse_args()
windows = os.name == "nt"
# (Linux: a short folder, a Unix socket's path is at most 107 bytes: the temporary folder ($TMPDIR) when it is short
# enough, else /tmp. Windows: the pipes are named after the process)
short = windows or len(tempfile.gettempdir()) <= 48 or not os.path.isdir("/tmp")
with tempfile.TemporaryDirectory(prefix="ctl-", dir=None if short else "/tmp") as tmp:
exe = os.path.join(tmp, "control_test.exe" if windows else "control_test")
libs = ["-ladvapi32"] if windows else ["-lpthread", "-lm"]
warnings = ["-Wno-format-truncation"] if "clang" not in Path(a.cc).name else []
subprocess.run([a.cc, "-std=c11", "-O1", "-g", "-Wall", "-Wextra", "-Werror", "-Wno-missing-field-initializers",
"-D_GNU_SOURCE", "-D_CRT_SECURE_NO_WARNINGS", "-DHOS_CONTROL_NO_GAME", "-I", str(a.source_root / "host"),
str(ROOT / "tests" / "control_test.c"), str(a.source_root / "host" / "control.c"), "-o", exe]
+ warnings + libs, check=True)
# (the general cases, quit, relaunch, the level unit, and the memory cases at each HOS_CONTROL_MEM level)
runs = [([], None), (["quit"], None), (["relaunch"], None), (["level"], None),
(["mem"], None), (["mem"], "ro"), (["mem"], "rw"), (["mem"], "bogus")]
for case, mem in runs:
folder = tempfile.mkdtemp(dir=tmp)
env = dict(os.environ)
env.pop("HOS_CONTROL_MEM", None)
if mem is not None:
env["HOS_CONTROL_MEM"] = mem
r = subprocess.run([exe, folder] + case, capture_output=True, text=True, timeout=180, env=env)
print(r.stdout, end="")
print(r.stderr, end="", file=sys.stderr)
if r.returncode:
label = " ".join(case) or "(the cases)"
print("FAIL: control_test %s%s exited %d" % (label, " HOS_CONTROL_MEM=%s" % mem if mem else "", r.returncode),
file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())

View File

@@ -0,0 +1,75 @@
"""The control bridge (host/control.c) stays local, this user's alone, and off unless asked for: read from its source, as
other checks here read theirs, so a change that would open it up fails here and not in someone's hands.
- off by default: hos_control_start returns at once without HOS_CONTROL; guest memory only with HOS_CONTROL_MEM (ro, rw),
anything else leaving it off; the hooks in the game (nn_hid.c, hos_thread.c) return on hos_control_on;
- no network: no TCP or UDP socket, no address of another PC (AF_INET, AF_INET6, getaddrinfo, WSAStartup, connect to a
host), only a Unix socket (Linux) or a named pipe (Windows);
- Windows: PIPE_REJECT_REMOTE_CLIENTS and FILE_FLAG_FIRST_PIPE_INSTANCE on every instance, a protected DACL that grants
the current user (and the game's own AppContainer) and no one else;
- Linux: the socket made 0600 with the umask around bind, its folder this user's and writable by no one else, and a
client of another user turned away (SO_PEERCRED).
python -I -B tests/test_control_local_only.py
"""
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FAILS = []
def check(ok, what):
if not ok:
FAILS.append(what)
print("FAIL: " + what)
def body(src, start):
"""the text of the C function whose definition starts with start, to its closing brace at column 0"""
i = src.index(start)
return src[i:src.index("\n}\n", i) + 2]
def main():
src = (ROOT / "host" / "control.c").read_text(encoding="utf-8")
code = re.sub(r"/\*.*?\*/", "", src, flags=re.S) # (the code alone: a comment may name what the code must not do)
start = body(src, "void hos_control_start(const char *version) {")
check('const char *path = getenv("HOS_CONTROL");\n if (!path || !*path) return;' in start,
"hos_control_start does not return at once without HOS_CONTROL")
check(code.count("hos_control_on = 1") == 1 and "hos_control_on = 1;\n return 1;\n}" in code,
"hos_control_on is set elsewhere than at the end of a served hos_control_serve")
check("if (!hos_control_on) return 0;" in body(src, "int hos_control_input(uint64_t *buttons, int32_t stick[4]) {"),
"the controller's read hook does not return at once with the bridge off")
check("if (!hos_control_on || !G.log_wanted) return;" in body(src, "void hos_control_log(const char *line) {"),
"the log hook does not return at once with the bridge off")
level = body(src, "int hos_control_mem_level(const char *v) {")
check("if (!v || !*v) return 0;" in level and level.count("return 1;") == 1 and level.count("return 2;") == 1,
"HOS_CONTROL_MEM: unset is not off, or more than ro and rw turn memory on")
check('if (!G.mem_level)\n return reply_error(c, id, "forbidden"' in body(src, "static void cmd_mem(") and
"if (write && G.mem_level < 2)" in body(src, "static void cmd_mem("), "guest memory is served without HOS_CONTROL_MEM")
for word in ("AF_INET", "AF_INET6", "getaddrinfo", "gethostbyname", "WSAStartup", "winsock", "SOCK_DGRAM", "inet_",
"htons", "InternetOpen", "WinHttp", "curl", "PEER_SID", "GRGW"):
check(word not in code, "host/control.c names %s: the bridge must stay local and this user's" % word)
check(code.count("socket(AF_UNIX") == 2, "a socket other than the Unix socket and its liveness probe")
pipe = body(src, "static int pipe_listen(void) {")
check("PIPE_REJECT_REMOTE_CLIENTS" in pipe and "FILE_FLAG_FIRST_PIPE_INSTANCE" in pipe and "&pipe_sa" in pipe,
"a pipe instance without PIPE_REJECT_REMOTE_CLIENTS, the first-instance flag or the DACL")
sec = body(src, "static int pipe_security(void) {")
grants = re.findall(r'"(?:D:P)?\(A;;([A-Z]+);;;%s\)"', sec)
check('"D:P(A;;GA;;;%s)", user' in sec and grants == ["GA", "GA"] and '"(A;;GA;;;%s)", ac' in sec and "getenv" not in sec,
"the pipe's DACL grants someone other than this user and the game's own AppContainer")
check("CreateNamedPipeA(" in code and code.count("CreateNamedPipe") == 1, "a pipe made outside pipe_listen")
lin = body(src, "static int transport_open(const char *path) {")
check("umask(077)" in lin and "chmod(path, 0600)" in lin and "folder_private(path)" in lin,
"the Unix socket is not made 0600 in a private folder")
check("SO_PEERCRED" in code and "cred.uid != getuid()" in code, "a client of another user is not turned away")
return 1 if FAILS else 0
if __name__ == "__main__":
rc = main()
print("PASS: the control bridge is local, this user's alone, and off unless HOS_CONTROL is set" if not rc else
"%d failed" % len(FAILS))
sys.exit(rc)

View File

@@ -66,6 +66,24 @@ class HostMarch(unittest.TestCase):
with mock.patch.object(host_cpu.os, "name", "nt"), mock.patch.dict(sys.modules, {"ctypes": ctypes}):
self.assertEqual(host_cpu.host_march(), want, present)
def test_steamdeck_mtune(self):
real_open = builtins.open
def fake_deck(path, *args, **kwargs):
if path == "/proc/cpuinfo":
return io.StringIO("model name\t: AMD Custom APU 0405\nflags\t\t: fpu\n")
return real_open(path, *args, **kwargs)
with mock.patch.object(host_cpu.os, "name", "posix"), mock.patch.object(builtins, "open", fake_deck), \
mock.patch.dict(os.environ, {}, clear=True):
self.assertEqual(host_cpu.host_mtune(), "znver2")
with mock.patch.dict(os.environ, {"RX_STEAMDECK": "1"}, clear=True):
self.assertEqual(host_cpu.host_mtune(), "znver2")
with mock.patch.object(host_cpu.os, "name", "nt"), mock.patch.dict(os.environ, {}, clear=True):
self.assertEqual(host_cpu.host_mtune(), "") # (no guess on Windows: RX_MTUNE or RX_STEAMDECK say so)
def test_build_and_appimage_use_it(self):
build = (ROOT / "nx2" / "build.py").read_text(encoding="utf-8")
self.assertIn("from host_cpu import host_march", build)
@@ -116,5 +134,60 @@ class AppImageCheck(unittest.TestCase):
self.assertLess(check.index("check_cpu()"), check.index("if a.nup:"))
def clang_says(cpu, feats, tune=None):
"""What `clang -march=native -###` writes to stderr, cut to the cc1 line's parts that matter"""
words = ['"/usr/bin/clang-23"', '"-cc1"', '"-triple"', '"x86_64-unknown-linux-gnu"']
if cpu:
words += ['"-target-cpu"', '"%s"' % cpu]
for f in feats:
words += ['"-target-feature"', '"%s"' % f]
if tune:
words += ['"-tune-cpu"', '"%s"' % tune]
return "clang version 23.1.5\nTarget: x86_64-unknown-linux-gnu\n " + " ".join(words) + "\n"
class NativeCpu(unittest.TestCase):
"""((Triforce) HOOKSHOT_NATIVE_CPU) -march=native is keyed by the CPU clang resolves it to: another CPU, another key"""
def native(self, stderr=None, raises=None):
run = mock.MagicMock(side_effect=raises) if raises else \
mock.MagicMock(return_value=mock.MagicMock(stderr=stderr, stdout=""))
with mock.patch("subprocess.run", run):
return host_cpu.native_cpu("clang", ["-march=native"]), run
def test_cpu_tune_and_features_name_it(self):
zen4, run = self.native(clang_says("znver4", ["+avx512f", "+avx2", "-amx-tile"], "znver4"))
self.assertTrue(zen4.startswith("znver4_znver4_"), zen4)
self.assertIn("-###", run.call_args[0][0])
self.assertIn("-march=native", run.call_args[0][0])
# (the feature list's order is not a change)
self.assertEqual(self.native(clang_says("znver4", ["-amx-tile", "+avx2", "+avx512f"], "znver4"))[0], zen4)
def test_another_cpu_another_name(self):
zen4 = self.native(clang_says("znver4", ["+avx512f", "+avx2"]))[0]
# (the same model with AVX-512 off, as some BIOSes and VMs do: the name alone would not tell them apart)
no512 = self.native(clang_says("znver4", ["-avx512f", "+avx2"]))[0]
zen3 = self.native(clang_says("znver3", ["+avx2"]))[0]
self.assertEqual(len({zen4, no512, zen3}), 3)
self.assertTrue(zen3.startswith("znver3_znver3_"), zen3) # (no -tune-cpu: tuned for the CPU itself)
def test_no_answer_is_none(self):
self.assertIsNone(self.native(clang_says(None, ["+avx2"]))[0])
self.assertIsNone(self.native(clang_says("native", []))[0])
self.assertIsNone(self.native("")[0])
self.assertIsNone(self.native(raises=OSError("no clang"))[0])
def test_build_keys_it_and_leaves_it_off(self):
build = (ROOT / "nx2" / "build.py").read_text(encoding="utf-8")
start = build.index('_CLANG = toolchain.find("clang")')
block = build[start:build.index("MTUNE = ", start)]
# (off unless asked; native only where the CPU chose v3, never over an RX_MARCH; its name is in the flags, so in every key)
self.assertIn('os.environ.get("HOOKSHOT_NATIVE_CPU") == "1" and not os.environ.get("RX_MARCH") and MARCH == "x86-64-v3"',
block)
self.assertIn('CPU += ["-DHOOKSHOT_NATIVE_CPU=" + _native]', block)
self.assertIn("sys.exit(", block)
if __name__ == "__main__":
unittest.main()

375
tests/test_crash_dialog.py Normal file
View File

@@ -0,0 +1,375 @@
"""(Triforce) The window after a crash (host/hos_crash_dialog.c, host/hos_crash_dialog.h).
python -I -B tests/test_crash_dialog.py [--cc gcc]
- Everywhere: the source is read: the helper is handed its command line before anything of the game starts (both mains),
the watch starts after the run's id is logged, HOS_CRASH_TEST is the environment's only, the quit the player asked for is
noted first, and nothing in the window's code opens a web page or sends anything (Report copies and saves; its box opens
a folder, only a folder).
- Everywhere: the deciding parts (the header) in a small C program: the command line, the record's name, Triforce's log
lines (its version line, the device chosen, the driver, a map line), the verdict (a crash, a start that failed, an
unclean end, a quit, Triforce's own "could not start its renderer" box), the cause, the stage, and the texts.
- On Windows: the real helper (-DHOS_CRASH_DIALOG_TEST: the box, the clipboard and the folder stood in for) against a game
folder: a crash shown with Report, the report saved and copied with the home folder taken out, no window for a quit,
the ledger of records shown.
"""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
HOST = ROOT / "host"
LF = chr(10) # (records and logs as the game writes them: no CR)
def read(rel):
return (ROOT / rel).read_text(encoding="utf-8")
def block(text, marker):
assert text.count(marker) == 1, marker
start = text.index(marker)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def source_checks():
dialog, header = read("host/hos_crash_dialog.c"), read("host/hos_crash_dialog.h")
for text, name in ((dialog, "hos_crash_dialog.c"), (header, "hos_crash_dialog.h")):
for word in ("http:", "https:", "issues/new", "curl", "WinHttp", "InternetOpen", 'L"open"'):
assert word not in text, (name, word)
# (the folder opener opens folders only)
win = dialog[dialog.index("static int open_folder(const char *folder) {"):]
win = win[:win.index("\n}\n")]
assert "FILE_ATTRIBUTE_DIRECTORY" in win and 'L"explore"' in win, win
lin = dialog[dialog.rindex("static int open_folder(const char *folder) {"):]
lin = lin[:lin.index("\n}\n")]
assert "S_ISDIR(st.st_mode)" in lin and "folder[0] != '/'" in lin, lin
assert dialog.count("open_folder(") >= 5 and "open_thing(" not in dialog
main = read("host/hos_main.c")
win_main = main.index("int main(int argc, char **argv) {\n#else\nstatic int game_main(")
assert main.index("hos_crash_helper_main(argc, argv);", win_main) < main.index("narrow_paths_ok(argc, argv)", win_main)
linux_main = main.rindex("int main(int argc, char **argv) {")
assert main.index("hos_crash_helper_main(argc, argv);", linux_main) < main.index("load_hookshot_env();", linux_main)
run_id = main.index('hos_log("run_id: %s", hos_report_run_id());')
assert main.index("hos_log_flush();", run_id) < main.index("hos_crash_record_log_notes();", run_id) # (the boundary on disk)
assert run_id < main.index("hos_crash_watch_start(argc, argv);") < main.index("if (!reserve_guest()) {")
assert main.index("if (!reserve_guest()) {") < main.index("hos_crash_test_arm();")
assert 'names_file |= !strcmp(name, "HOS_CRASH_TEST");' in main
assert 'hos_log("map: %s", line)' in main
# (Triforce's own renderer box: its line is the one the header reads as said already)
told = '] display: the renderer did not start: the game ends'
assert told in header
assert 'hos_log("display: the renderer did not start: the game ends");' in read("host/display.c")
assert 'hos_log("display: the renderer did not start: the game ends");' in read("host/posix/display_sdl.c")
assert 'hos_log("triforce %s", HOOKSHOT_VERSION);' in main and '"] triforce "' in header
print("PASS: the helper starts nothing of the game, nothing opens a web page, a box opens a folder only")
LOGIC = r'''
#include "hos_crash_dialog.h"
#include <assert.h>
#ifdef _WIN32
#include <windows.h>
#include <shellapi.h>
#endif
static HosCrashLog facts(const char *const *lines) {
HosCrashLog f;
memset(&f, 0, sizeof f);
for (; *lines; lines++) hos_crash_log_line(&f, *lines);
return f;
}
static HosCrashRecord record(const char *text) { HosCrashRecord r; hos_crash_record_parse(text, &r); return r; }
int main(void) {
HosCrashArgs a;
char *watch[] = {"Triforce.exe", "--crash-watch", "1234", "0123456789abcdef0123456789abcdef", "C:\\Games\\T", "-"};
assert(hos_crash_args(6, watch, &a) == 1 && a.pid == 1234 && !a.log && !strcmp(a.dir, "C:\\Games\\T"));
char *bad_id[] = {"x", "--crash-watch", "1234", "0123", "d", "l"};
assert(hos_crash_args(6, bad_id, &a) == -1);
char *show[] = {"x", "--crash-show", "crash-20261124T101500Z.txt", "d", "d/triforce_log.txt"};
assert(hos_crash_args(5, show, &a) == 2 && !strcmp(a.log, "d/triforce_log.txt"));
char *path_record[] = {"x", "--crash-show", "../crash-20261124T101500Z.txt", "d", "l"};
assert(hos_crash_args(5, path_record, &a) == -1);
char *game[] = {"x", "image.bin"};
assert(hos_crash_args(2, game, &a) == 0);
char when[17];
assert(hos_crash_record_name("crash-20261124T101500Z-77-2.txt", when) == 1 && !strcmp(when, "20261124T101500Z"));
assert(hos_crash_record_name("unclean-20261124T101500Z.txt", NULL) == 2);
assert(!hos_crash_record_name("report-20261124T101500Z.txt", NULL));
char *prep[] = {"x", "--prepare-shaders"};
const char *id = "0123456789abcdef0123456789abcdef";
assert(hos_crash_watch_wanted(1, prep, 0, 0, 0, 0, id) && !hos_crash_watch_wanted(2, prep, 0, 0, 0, 0, id));
assert(!hos_crash_watch_wanted(1, prep, 1, 0, 0, 0, id) && !hos_crash_watch_wanted(1, prep, 0, 1, 0, 0, id));
assert(!hos_crash_watch_wanted(1, prep, 0, 0, 0, 0, "unknown"));
assert(hos_crash_under_gamescope(NULL, "KDE:gamescope") && !hos_crash_under_gamescope("", "KDE"));
#ifdef _WIN32
{ /* (the quoting, read back as Windows reads a command line) */
const char *args[] = {"C:\\Program Files\\T\\", "a \"b\" c", "x\\\\\"y", ""};
char line[1024] = "x.exe";
for (int i = 0; i < 4; i++) {
char q[256];
assert(hos_crash_quote_arg(q, sizeof q, args[i]));
strcat(line, " "), strcat(line, q);
}
wchar_t w[1024];
MultiByteToWideChar(CP_UTF8, 0, line, -1, w, 1024);
int n = 0;
wchar_t **back = CommandLineToArgvW(w, &n);
assert(back && n == 5);
for (int i = 0; i < 4; i++) {
char got[256];
WideCharToMultiByte(CP_UTF8, 0, back[i + 1], -1, got, sizeof got, NULL, NULL);
assert(!strcmp(got, args[i]));
}
LocalFree(back);
}
#endif
/* (Triforce's own lines) */
const char *play[] = {"[hos host] triforce v0.7.1-12-gabc (Sage Of Courage)\n", "[hos host] run_id: x\n",
"[hos render] vk: device 0: NVIDIA GeForce RTX 3080, Vulkan 1.4, driver 0x91c0c000, type 2\n",
"[hos render] vk: vendor fixes for NVIDIA (581.57): out-of-bounds texel fetches 0 0, NaN tests by bits 0, gather offset 0\n",
"[hos render] vk: NVIDIA GeForce RTX 3080, Vulkan 1.4, driver 0x91c0c000; mesh shaders yes, host memory import yes, pipeline libraries yes\n",
"[hos render] vk: start-up: the shaders took 3.1 s\n", "[hos MainThread] map: Field (child)\n", NULL};
HosCrashLog f = facts(play);
assert(!strcmp(f.version, "v0.7.1-12-gabc (Sage Of Courage)"));
assert(!strcmp(f.gpu, "NVIDIA GeForce RTX 3080") && !strcmp(f.driver, "NVIDIA (581.57)"));
assert(!strcmp(f.devices, "NVIDIA GeForce RTX 3080"));
{ /* (the card with its driver; the renderer of a start-up crash) */
char gpu[400];
hos_crash_gpu(gpu, sizeof gpu, &f);
assert(!strcmp(gpu, "NVIDIA GeForce RTX 3080, NVIDIA (581.57)"));
assert(!strcmp(hos_crash_renderer(&f), "Vulkan (it was starting)"));
const char *started[] = {"[hos host] rx: renderer: Vulkan (triforce_vk.dll)\n", NULL};
HosCrashLog s = facts(started);
assert(!strcmp(hos_crash_renderer(&s), "Vulkan (triforce_vk.dll)"));
HosCrashLog early;
memset(&early, 0, sizeof early);
assert(!strcmp(hos_crash_renderer(&early), "none started yet"));
hos_crash_gpu(gpu, sizeof gpu, &early);
assert(!gpu[0]);
}
assert(f.map && hos_crash_stage(&f) == HOS_STAGE_PLAY && !hos_crash_start_failed(&f));
const char *driver_only[] = {"[hos render] vk: AMD Radeon RX 7800 XT, Vulkan 1.3, driver 0x8000123; mesh shaders yes\n", NULL};
f = facts(driver_only);
assert(!strcmp(f.gpu, "AMD Radeon RX 7800 XT") && !strcmp(f.driver, "driver 0x8000123"));
const char *preparing[] = {"[hos render] vk: start-up: 120 pipelines to make\n", NULL};
f = facts(preparing);
assert(hos_crash_stage(&f) == HOS_STAGE_PREPARING);
/* (was it a crash) */
HosCrashLog none;
memset(&none, 0, sizeof none);
const HosCrashRecord crash = record("Triforce crash record 1\nversion: v1\nrun_id: x\nreason: unhandled exception\n"
"module_offset: nvoglv64.dll+0x12\nexception: 0xc0000005\n");
const HosCrashRecord unclean = record("Triforce unclean record 1\nreason: ended without a clean exit\n");
const HosCrashRecord quit = record("Triforce unclean record 1\nquit_asked: yes\n");
const HosCrashRecord nothing = record("");
assert(crash.kind == 1 && crash.code == 0xc0000005u && unclean.kind == 2 && quit.quit && !nothing.kind);
assert(hos_crash_verdict(&crash, &none, 1, 0xc0000005ul, 0) == HOS_CRASH_SHOW_CRASH);
assert(hos_crash_verdict(&crash, &none, 1, 0, 1) == HOS_CRASH_QUIET); /* (replaced) */
assert(hos_crash_cause(HOS_CRASH_SHOW_CRASH, &crash, &none, 0, 0) == HOS_CAUSE_GPU_DRIVER);
assert(hos_crash_verdict(&unclean, &none, 1, 1, 0) == HOS_CRASH_SHOW_UNCLEAN);
assert(hos_crash_verdict(&unclean, &none, 1, 0, 0) == HOS_CRASH_QUIET); /* (exit code 0) */
assert(hos_crash_verdict(&quit, &none, 1, 1, 0) == HOS_CRASH_QUIET); /* (a quit never counts) */
assert(hos_crash_cause(HOS_CRASH_SHOW_UNCLEAN, &unclean, &none, 1, 1) == HOS_CAUSE_ENDED);
assert(hos_crash_verdict(&nothing, &none, 1, 1, 0) == HOS_CRASH_QUIET); /* (a clean end: the marker removed) */
const char *no_gpu[] = {"[hos render] vk: no Vulkan 1.3 GPU\n", "[hos host] rx: RX_BACKEND=vulkan, but x did not load (126): WebGPU\n", NULL};
f = facts(no_gpu);
assert(hos_crash_verdict(&nothing, &f, 1, 1, 0) == HOS_CRASH_SHOW_START);
assert(hos_crash_cause(HOS_CRASH_SHOW_START, &nothing, &f, 1, 1) == HOS_CAUSE_VULKAN);
const char *told[] = {"[hos render] vk: no Vulkan 1.3 GPU\n", "[hos host] display: the renderer did not start: the game ends\n", NULL};
f = facts(told);
assert(f.told && hos_crash_verdict(&nothing, &f, 1, 1, 0) == HOS_CRASH_QUIET); /* (its own box said it) */
assert(hos_crash_verdict(&crash, &f, 1, 1, 0) == HOS_CRASH_SHOW_CRASH); /* (a crash still counts) */
const char *window[] = {"[hos host] display: CreateWindowExW failed (error 5)\n", NULL};
f = facts(window);
assert(hos_crash_cause(hos_crash_verdict(&nothing, &f, 1, 1, 0), &nothing, &f, 1, 1) == HOS_CAUSE_WINDOW);
const char *reserve[] = {"cannot reserve the guest window\n", NULL};
f = facts(reserve);
assert(hos_crash_verdict(&nothing, &f, 1, 1, 0) == HOS_CRASH_SHOW_START);
assert(hos_crash_cause(HOS_CRASH_SHOW_START, &nothing, &f, 1, 1) == HOS_CAUSE_MEMORY);
/* (the texts) */
char text[2048];
hos_crash_message(text, sizeof text, HOS_CRASH_SHOW_CRASH, HOS_STAGE_PLAY, HOS_CAUSE_GPU_DRIVER);
assert(strstr(text, "Triforce closed unexpectedly while you were playing.") == text);
assert(strstr(text, "Triforce itself sends nothing.") && !strstr(text, "browser") && !strstr(text, "http"));
hos_crash_ready_text(text, sizeof text, 0, NULL);
assert(strstr(text, "could not be put on the clipboard, nor saved") && !strstr(text, "is on your clipboard"));
hos_crash_ready_text(text, sizeof text, 1, "C:\\T\\crash-reports\\pending\\report-x.txt");
assert(strstr(text, "is on your clipboard") && strstr(text, "It is saved as C:\\T\\crash-reports\\pending\\report-x.txt."));
hos_crash_ready_text(text, sizeof text, 2, "/t/r.txt");
assert(strstr(text, "Keep this window open"));
/* (what a setting's value shows) */
assert(hos_crash_value_shown("HOS_X", "1") && hos_crash_value_shown(NULL, "1920x1080") && hos_crash_value_shown(NULL, "Off"));
assert(!hos_crash_value_shown("HOS_DISCORD_TOKEN", "1") && !hos_crash_value_shown(NULL, "C:\\Users\\me") &&
!hos_crash_value_shown(NULL, "-1x2"));
/* (a start shows a crash record no helper showed, a day old at most; never an unclean end) */
const int64_t now = hos_crash_epoch("20261124T120000Z");
assert(hos_crash_epoch("19700102T000000Z") == 86400);
assert(hos_crash_show_at_start("crash-20261124T110000Z.txt", "", now));
assert(!hos_crash_show_at_start("crash-20261124T110000Z.txt", "crash-20261124T110000Z.txt\n", now));
assert(!hos_crash_show_at_start("unclean-20261124T110000Z.txt", "", now));
assert(!hos_crash_show_at_start("crash-20261122T110000Z.txt", "", now));
puts("logic ok");
return 0;
}
'''
FIXTURE = r'''
#define HOS_CRASH_DIALOG_TEST 1
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void hos_log(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); }
void hos_log_flush(void) {}
const char *hos_version(void) { return "fixture"; }
static int next_button(void) {
static int at;
const char *list = getenv("CRASH_BUTTONS");
int k = 0;
for (const char *p = list ? list : ""; *p; p++) {
if (k == at) { at++; return atoi(p); }
if (*p == ',') k++;
}
at++;
return -1;
}
int hos_crash_test_box(const char *title, const char *text, const char *const *buttons, int n) {
printf("BOX %s |", title);
for (int i = 0; i < n; i++) printf(" [%s]", buttons[i]);
printf("\n");
FILE *f = fopen(getenv("CRASH_BOXES"), "ab");
if (f) fprintf(f, "=== %s\n%s\n", title, text), fclose(f);
return next_button();
}
int hos_crash_test_clipboard(const char *text) {
FILE *f = fopen(getenv("CRASH_CLIP"), "wb");
if (f) fputs(text, f), fclose(f);
return 1;
}
int hos_crash_test_open(const char *folder) { printf("OPEN %s\n", folder); return 1; }
int hos_crash_helper_main(int argc, char **argv);
int main(int argc, char **argv) { return hos_crash_helper_main(argc, argv); }
'''
def logic(cc, tmp):
src, exe = Path(tmp) / "logic.c", Path(tmp) / "logic.exe"
src.write_text(LOGIC, encoding="utf-8")
subprocess.run([cc, "-std=gnu11", "-O1", "-Wall", "-Wno-unused-function", "-Wno-incompatible-pointer-types-discards-qualifiers",
"-Wno-write-strings", "-I", str(HOST), str(src), "-o", str(exe)] + (["-lshell32"] if os.name == "nt" else []),
check=True)
r = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60)
assert r.returncode == 0 and "logic ok" in r.stdout, (r.returncode, r.stdout, r.stderr)
print("PASS: the command line, Triforce's log lines, the verdicts, the causes and the texts")
def behaviour(cc, tmp):
src, exe = Path(tmp) / "helper.c", Path(tmp) / "helper.exe"
src.write_text(FIXTURE, encoding="utf-8")
subprocess.run([cc, "-std=gnu11", "-O1", "-DHOS_CRASH_DIALOG_TEST", "-I", str(HOST), str(src),
str(HOST / "hos_crash_dialog.c"), str(HOST / "hos_crash_record.c"), str(HOST / "hos_report_run.c"),
str(HOST / "log_redact.c"), "-o", str(exe), "-ldbghelp", "-lshell32", "-lole32", "-ladvapi32", "-luser32"],
check=True)
home = os.environ["USERPROFILE"]
run_id = "0123456789abcdef0123456789abcdef"
game = Path(tmp) / "game"
pending = game / "crash-reports" / "pending"
pending.mkdir(parents=True)
log = game / "triforce_log.txt"
log.write_text("[hos host] triforce v0.7.1\n[hos host] run_id: %s\n[hos host] loading %s\\Saved Games\\x\n"
"[hos MainThread] map: Kakariko Village (adult)\n" % (run_id, home), encoding="utf-8", newline=LF)
record = pending / "crash-20261124T101500Z.txt"
record.write_text("Triforce crash record 1\nversion: v0.7.1\nrun_id: %s\nwhen: 20261124T101500Z\nuptime_s: 42\n"
"reason: unhandled exception\nmodule_offset: Triforce.exe+0x1234\nexception: 0xc0000005\n"
"record_complete: yes\n" % run_id, encoding="utf-8", newline=LF)
boxes, clip = Path(tmp) / "boxes.txt", Path(tmp) / "clip.txt"
def helper(*args, buttons=""):
env = dict(os.environ, CRASH_BUTTONS=buttons, CRASH_BOXES=str(boxes), CRASH_CLIP=str(clip))
for p in (boxes, clip):
if p.exists():
p.unlink()
r = subprocess.run([str(exe), *map(str, args)], capture_output=True, text=True, timeout=60, env=env)
assert r.returncode == 0, (args, r.returncode, r.stdout, r.stderr)
return r.stdout
# (a game process long gone: the watch reads its run's crash record, and Open the log folder, then Report, then Open the
# folder, then Done)
out = helper("--crash-watch", 4000000000, run_id, str(game) + os.sep, log, buttons="1,0,0,1")
lines = out.splitlines()
assert lines[0].startswith("BOX Triforce closed unexpectedly | [Report] [Open the log folder] [Close]"), out
assert lines[1] == "OPEN " + str(game), out
assert lines[3].startswith("BOX Triforce: report ready | [Open the folder] [Done]"), out
assert lines[4] == "OPEN " + str(pending), out
shown = boxes.read_text(encoding="utf-8")
assert "Triforce closed unexpectedly while you were playing." in shown and "is on your clipboard" in shown, shown
report = clip.read_text(encoding="utf-8")
assert "### Triforce version\n\nv0.7.1" in report and "Kakariko Village" in report, report
assert home not in report and "%USERPROFILE%\\Saved Games\\x" in report, report
assert "Triforce.exe+0x1234" in report and "http" not in report
assert "Renderer: none started yet" in report, report # (the log names no renderer line here)
saved = [p.name for p in pending.iterdir() if p.name.startswith("report-")]
assert len(saved) == 1 and (pending / saved[0]).read_text(encoding="utf-8") == report
assert "crash-20261124T101500Z.txt" in (game / "crash-reports" / "shown.txt").read_text(encoding="utf-8")
# (a quit, then an end with no crash handler: nothing said)
record.unlink()
(pending / "unclean-20261124T111500Z.txt").write_text(
"Triforce unclean record 1\nrun_id: %s\nquit_asked: yes\nrecord_complete: yes\n" % run_id, encoding="utf-8", newline=LF)
assert helper("--crash-watch", 4000000000, run_id, game, log) == ""
# (the game's own "could not start its renderer" box said it: nothing more)
(pending / "unclean-20261124T111500Z.txt").unlink()
log.write_text("[hos host] triforce v0.7.1\n[hos host] run_id: %s\n[hos render] vk: no Vulkan 1.3 GPU\n"
"[hos host] display: the renderer did not start: the game ends\n" % run_id, encoding="utf-8", newline=LF)
assert helper("--crash-watch", 4000000000, run_id, game, log) == ""
# (a start that could not reserve its memory says so, Close)
log.write_text("[hos host] triforce v0.7.1\n[hos host] run_id: %s\ncannot reserve the guest window\n" % run_id,
encoding="utf-8", newline=LF)
(pending / "unclean-20261124T121500Z.txt").write_text(
"Triforce unclean record 1\nrun_id: %s\nrecord_complete: yes\n" % run_id, encoding="utf-8", newline=LF)
out = helper("--crash-watch", 4000000000, run_id, game, log, buttons="2")
assert out.startswith("BOX Triforce couldn't start |"), out
assert "Your PC ran out of memory" in boxes.read_text(encoding="utf-8")
# (a log a restarted run appends to (Linux's Restart now): found past its first 8 KB, its facts from its own banner on)
other = "f" * 32
log.write_text("[hos host] triforce v0.7.0\n[hos host] run_id: %s\n[hos MainThread] map: Hyrule Field (child)\n" % other
+ "[hos host] filler line of the run before\n" * 400
+ "[hos host] triforce v0.7.1\n[hos host] run_id: %s\n[hos render] vk: start-up: the shaders took 1.0 s\n"
% run_id, encoding="utf-8", newline=LF)
(pending / "unclean-20261124T121500Z.txt").unlink()
record.write_text("Triforce crash record 1\nversion: v0.7.1\nrun_id: %s\nwhen: 20261124T131500Z\nreason: unhandled exception\n"
"record_complete: yes\n" % run_id, encoding="utf-8", newline=LF)
out = helper("--crash-watch", 4000000000, run_id, game, log, buttons="0,1")
said = boxes.read_text(encoding="utf-8")
assert "Triforce closed unexpectedly during the start." in said, said
report = clip.read_text(encoding="utf-8")
assert "### Triforce version\n\nv0.7.1" in report and "triforce_log.txt\n\nNot found" not in report, report
# (a bad command line does nothing)
assert helper("--crash-show", "../x.txt", game, log) == ""
print("PASS (Windows): the window, Report (copied, saved, the home folder out, no web page), quiet for a quit and for "
"Triforce's own box")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default="gcc")
args = parser.parse_args()
source_checks()
with tempfile.TemporaryDirectory() as tmp:
logic(args.cc, tmp)
if os.name == "nt":
behaviour(args.cc, tmp)
else:
print("SKIP: the helper's run is checked on Windows (its Linux paths are read above)")
if __name__ == "__main__":
main()

224
tests/test_crash_record.py Normal file
View File

@@ -0,0 +1,224 @@
"""(Triforce) The local crash and unclean-end records (host/hos_crash_record.c), beside the crash report in triforce_log.txt.
python -I -B tests/test_crash_record.py [--cc gcc]
Everywhere: the source is read for where the record is written and where a run's marker is removed (every clean end), and
that Triforce's own crash report (host/mkw_glue.c report_crash, host/hos_thread.c hos_fatal) is still whole and still runs
after the record. On Windows a fixture (tests/crash_record_test.c) runs the real writer: a crash through an exception
filter, a fatal end, a device lost, a run killed with no clean end (an unclean-end record at the next start, with the quit
the player asked for), a clean end and a return (nothing left), the 15 records kept, the labels' privacy, and the
minidump off unless asked for. Nothing is sent anywhere.
"""
import argparse
import os
from pathlib import Path
import re
import subprocess
import tempfile
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
HOST = ROOT / "host"
def block(text, marker):
assert text.count(marker) == 1, marker
start = text.index(marker)
end = text.index("{", start) + 1
depth = 1
while depth:
depth += (text[end] == "{") - (text[end] == "}")
end += 1
return text[start:end]
def read(rel):
return (ROOT / rel).read_text(encoding="utf-8")
def source_contract():
glue = read("host/mkw_glue.c")
report = block(glue, "static LONG WINAPI report_crash(")
# (Triforce's order: one ending, the other threads' state first, then the record, then the CRASH lines as before)
assert report.index("hos_ending_enter()") < report.index("hos_crash_threads_begin();") < report.index(
"record_exception(info);") < report.index("GetModuleHandleExA(")
for line in ('CRASH: exception %#lx (%s %#llx, guest %#llx) at %s+%#llx', 'CRASH: host backtrace:',
'CRASH: thread %s, sp %#llx', 'CRASH: guest backtrace: lr %#llx', 'hos_crash_threads_end();'):
assert line in report, line
assert "if (code == 0xC0000374 || code == 0xC0000409) report_crash(info);" in glue
assert "SetUnhandledExceptionFilter(report_crash);" in glue
threads = read("host/hos_thread.c")
fatal = block(threads, "void hos_fatal(")
assert fatal.index("hos_ending_enter()") < fatal.index("hos_crash_threads_begin();") < fatal.index(
'hos_crash_record_fatal(c ? c->x : NULL, "hos_fatal");') < fatal.index("fprintf(stderr,")
log = block(threads, "static void hos_vlog(int level, const char *fmt, va_list ap) {")
assert log.index("HOS_REPORT_DEVICE_LOST_PREFIX") < log.index("hos_log_redact(")
assert 'strstr(buf, "VK_ERROR_DEVICE_LOST") ? "device lost" : "Vulkan fatal"' in log
# (the renderer's lines the prefixes stand for)
assert 'logf("vk: device lost: reading %s"' in read("gpu/vk/vk_draw.cpp")
assert 'logf("vk: FATAL: %s", why);' in read("gpu/vk/vk_replay.cpp")
writer = block(read("host/hos_crash_record.c"), "int hos_crash_record_write(")
assert "hos_log(" not in writer and "malloc" not in writer and "printf" not in writer
main = read("host/hos_main.c")
# (the run before's marker read before its log moves to .1; the run's id right after the version line)
prepare = main.index("hos_crash_record_prepare(path);")
rotate = main.index('memcpy(to, path, n), snprintf(to + n, 32, "triforce_log.%d.txt", k);')
assert prepare < rotate
assert "} else hos_crash_record_prepare(NULL);" in main
banner = main.index('hos_log("triforce %s", HOOKSHOT_VERSION);')
assert banner < main.index('hos_log("run_id: %s", hos_report_run_id());') < banner + 600
# (every clean end removes the marker: ExitProcess and quick_exit run no atexit)
for rel, before in (("host/hos_relaunch.c", "if (again) relaunch();"), ("host/hos_svc.c", "ExitProcess(0);"),
("host/hos_update.c", "ExitProcess(0);"), ("host/display.c", "ExitProcess(1);"),
("host/posix/display_sdl.c", "ExitProcess(1);")):
text = read(rel)
at = text.index("hos_crash_clean_end();")
assert 0 < text.index(before, at) - at < 200, rel
assert main.count("hos_crash_clean_end();") >= 2 # (nnMain's return, Linux's game thread)
assert "hos_crash_quit_asked();" in block(read("host/rx_backend.c"), "void rx_close_asked(void)")
posix = read("host/posix/win32_posix.c")
assert "rec.ExceptionInformation[13] = (ULONG_PTR)sig;" in posix and "SIGABRT};" in posix
record = read("host/hos_crash_record.c")
assert 'getenv("HOS_CRASH_MINIDUMP")' in record # (off unless asked for)
for word in ("http", "curl", "WinHttp", "InternetOpen", "connect("):
assert word not in record, word
print("PASS: the record is written first, Triforce's crash report stays whole, and every clean end removes the marker")
def fixture_source():
glue = read("host/mkw_glue.c")
cut = block(glue, "static void record_exception(") + "\n" + block(glue, "void hos_crash_record_fatal(")
return read("tests/crash_record_test.c").replace("/* RECORD_EXCEPTION */", cut)
def pending(game):
p = Path(game) / "crash-reports" / "pending"
return sorted(x.name for x in p.iterdir()) if p.is_dir() else []
def running(game):
p = Path(game) / "crash-reports" / "running"
return sorted(x.name for x in p.iterdir()) if p.is_dir() else []
def text_of(game, name):
return (Path(game) / "crash-reports" / "pending" / name).read_text(encoding="utf-8")
def run_fixture(cc):
flags = subprocess.CREATE_NO_WINDOW
with tempfile.TemporaryDirectory() as tmp:
src, exe = Path(tmp) / "fixture.c", Path(tmp) / "fixture.exe"
src.write_text(fixture_source(), encoding="utf-8")
subprocess.run([cc, "-std=gnu11", "-O0", "-g0", "-I", str(HOST), str(src), str(HOST / "hos_report_run.c"),
str(HOST / "log_redact.c"), "-o", str(exe), "-ldbghelp", "-ladvapi32"], check=True)
env = dict(os.environ)
env.pop("HOS_CRASH_MINIDUMP", None)
env.pop("HOS_LOG_REDACT", None)
def game(name):
g = Path(tmp) / name
g.mkdir()
return str(g)
def run(g, mode, ok=(0,)):
r = subprocess.run([str(exe), g, mode], capture_output=True, text=True, timeout=60, env=env, creationflags=flags)
assert ok is None or r.returncode in ok, (mode, r.returncode, r.stdout, r.stderr)
m = re.search(r"run_id: ([0-9a-f]{32})", r.stdout)
assert m, (mode, r.stdout, r.stderr)
return r, m.group(1)
# a clean end, twice over, and a return (atexit): nothing pending, no marker left
g = game("clean")
run(g, "clean")
run(g, "return")
assert pending(g) == [] and running(g) == [], (pending(g), running(g))
# a crash through the exception filter: one complete record, the marker gone
g = game("crash")
r, run_id = run(g, "crash", ok=(0xC0000005,))
names = pending(g)
assert len(names) == 1 and re.fullmatch(r"crash-\d{8}T\d{6}Z\.txt", names[0]), names
t = text_of(g, names[0])
assert t.startswith("Triforce crash record 1\n") and t.endswith("record_complete: yes\n"), t
for want in ("run_id: " + run_id, "reason: unhandled exception", "thread: fixture-thread", "exception: 0xc0000005",
"fault_address_class: other", "host_backtrace_method: Windows unwind", "guest_register: x30=0x80001234",
"guest_backtrace: 0x80005678", "dump: off", "version: fixture-v1"):
assert want in t, want
assert running(g) == [], running(g)
# a fatal end and a device lost: their fixed reasons, one record each run
for mode, reason in (("fatal", "hos_fatal"), ("device-lost", "device lost")):
g = game(mode)
run(g, mode, ok=(3,))
names = pending(g)
assert len(names) == 1, names
assert "reason: %s\n" % reason in text_of(g, names[0]), text_of(g, names[0])
# killed with no clean end: an unclean-end record at the next start, and the quit the player asked for in it
g = game("killed")
_, first = run(g, "killed", ok=(3,))
assert pending(g) == [] and sum(n.endswith(".running") for n in running(g)) == 1, running(g)
run(g, "clean")
names = pending(g)
assert len(names) == 1 and names[0].startswith("unclean-"), names
t = text_of(g, names[0])
assert t.startswith("Triforce unclean record 1\n") and "run_id: " + first in t and "quit_asked" not in t, t
assert "termination_note: ended from outside or lost power, not necessarily a crash" in t
g = game("quit")
run(g, "quit-killed", ok=(3,))
run(g, "clean")
assert "quit_asked: yes" in text_of(g, pending(g)[0])
# a second write never replaces the first; a small buffer is never overrun; a label stays one plain line
g = game("bounds")
run(g, "bounds")
assert len(pending(g)) == 1
g = game("label")
r, _ = run(g, "label")
assert "label: a?b?c?\n" in r.stdout, r.stdout # (6 bytes asked: the e-acute's second byte cut off)
# the home folder never in a record (host/log_redact.c's rule)
g = game("privacy")
run(g, "privacy")
t = text_of(g, pending(g)[0])
home = os.environ.get("USERPROFILE") or os.environ.get("HOME") or ""
assert home and home not in t and "thread: %USERPROFILE%/t" in t, t
# the newest 15 kept at a start; other files left alone
g = game("prune")
p = Path(g) / "crash-reports" / "pending"
p.mkdir(parents=True)
for day in range(1, 21):
(p / ("crash-202611%02dT000000Z.txt" % day)).write_text("x", encoding="utf-8")
(p / "notes.txt").write_text("mine", encoding="utf-8")
run(g, "clean")
names = pending(g)
assert len(names) == 16 and "notes.txt" in names and "crash-20261106T000000Z.txt" in names, names
assert "crash-20261105T000000Z.txt" not in names
# a folder it cannot write: no record, the game unaffected
g = game("readonly")
(Path(g) / "crash-reports").write_text("a file where the folder would be", encoding="utf-8")
run(g, "read-only")
# no minidump unless asked for; asked for (HOS_CRASH_MINIDUMP=1), a private one beside, never in the record's folder
assert not any((Path(tmp) / d / "crash-reports" / "local-only").exists() for d in os.listdir(tmp)
if (Path(tmp) / d).is_dir())
g = game("dump")
env["HOS_CRASH_MINIDUMP"] = "1"
run(g, "crash", ok=(0xC0000005,))
env.pop("HOS_CRASH_MINIDUMP")
names = pending(g)
assert len(names) == 1 and "dump: requested locally, not for sharing" in text_of(g, names[0])
local = sorted(x.name for x in (Path(g) / "crash-reports" / "local-only").iterdir())
stem = names[0][:-4]
assert stem + ".outcome.txt" in local, local
print("PASS: crash, fatal, device lost, unclean end (with the quit asked), clean ends, pruning, privacy, no dump by default")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--cc", default="gcc")
args = parser.parse_args()
source_contract()
if os.name != "nt":
print("SKIP: the fixture runs on Windows (its Linux paths are read above)")
return
run_fixture(args.cc)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,141 @@
"""The cursor over the game's window hides in play too, not only in the game's menus, once the pads or the keys are used
(host/display.c gm_cursor_shown), and shows again when the mouse is used. It is shown when the window opens. While it is
hidden a move of a few pixels does not bring it back, and neither does the window moving under it. The options keep
their own pointer, and a move under them counts as the mouse used.
The cursor's own functions are compiled from display.c with authored stand-ins for the Win32 calls and run; the window
procedure's three conditions are read as text (tests/test_screensaver.py runs its timer branch).
python -I -B tests/test_cursor_hidden_in_play.py [--cc gcc]
"""
import argparse
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
RUN_ALL_ARGS = ["--cc", "gcc"]
ROOT = Path(__file__).resolve().parents[1]
DISPLAY = (ROOT / "host" / "display.c").read_text(encoding="utf-8")
CC = "gcc"
def case(label):
start = DISPLAY.index(f"case {label}:")
end = DISPLAY.index("\n case ", start + 1)
return DISPLAY[start:end]
def function(signature):
start = DISPLAY.index(signature)
end = DISPLAY.index("{", start) + 1
depth = 1
while depth:
depth += (DISPLAY[end] == "{") - (DISPLAY[end] == "}")
end += 1
return DISPLAY[start:end]
FIXTURE = r'''
#include <stdint.h>
#include <stdio.h>
typedef long LONG;
typedef int64_t LONG64;
typedef unsigned long DWORD;
typedef unsigned UINT;
typedef void *HWND;
#define LOWORD(v) ((unsigned)(v) & 0xffff)
#define HIWORD(v) (((unsigned)(v) >> 16) & 0xffff)
static LONG64 InterlockedExchange64(volatile LONG64 *t, LONG64 v) { const LONG64 was = *t; *t = v; return was; }
static LONG InterlockedExchange(volatile LONG *t, LONG v) { const LONG was = *t; *t = v; return was; }
static LONG64 InterlockedCompareExchange64(volatile LONG64 *t, LONG64 v, LONG64 c) {
const LONG64 was = *t;
if (was == c) *t = v;
return was;
}
static int64_t now_ns = 1000, input_ns;
static int64_t hos_now_ns(void) { return ++now_ns; }
int64_t hos_player_input_ns(void) { return input_ns; }
static int at_x, at_y;
static UINT dpi = 96;
static DWORD GetMessagePos(void) { return (DWORD)((at_x & 0xffff) | ((unsigned)(at_y & 0xffff) << 16)); }
static UINT window_dpi(HWND w) { (void)w; return dpi; }
static int MulDiv(int a, int b, int c) { return (int)(((int64_t)a * b + c / 2) / c); }
@CURSOR@
static void pad(void) { input_ns = ++now_ns; }
static void move(int x, int y) { at_x = x, at_y = y; gm_mouse_moved(NULL); }
#define CHECK(x) do { if (!(x)) { printf("FAIL line %d: %s\n", __LINE__, #x); return 1; } } while (0)
int main(void) {
CHECK(gm_cursor_shown()); /* the window opens with its cursor shown */
move(500, 400); CHECK(gm_cursor_shown());
pad(); CHECK(!gm_cursor_shown()); /* the first pad or key input hides it */
move(500, 400); CHECK(!gm_cursor_shown()); /* a repeat at rest, or the window moved under it */
move(503, 396); CHECK(!gm_cursor_shown()); /* within 4 pixels of where it was hidden */
move(496, 404); CHECK(!gm_cursor_shown()); /* (from that point, not from the last move) */
move(505, 400); CHECK(gm_cursor_shown()); /* past them: the mouse used */
pad(); CHECK(!gm_cursor_shown());
move(505, 395); CHECK(gm_cursor_shown()); /* either axis */
move(506, 395); pad(); CHECK(!gm_cursor_shown());
move(-300, 395); CHECK(gm_cursor_shown()); /* a screen left of the first one: negative coordinates */
move(-301, 395); CHECK(gm_cursor_shown()); /* shown: every move is the mouse in use, */
pad(); move(-301, 395); CHECK(!gm_cursor_shown());
move(-302, 395); CHECK(!gm_cursor_shown()); /* and the pad after it hides it again */
dpi = 192; /* the slack follows the window's dpi: 8 pixels at 200% */
move(-309, 395); CHECK(!gm_cursor_shown());
move(-310, 395); CHECK(gm_cursor_shown());
pad(); CHECK(!gm_cursor_shown());
gm_mouse_used(); CHECK(gm_cursor_shown()); /* a button pressed in the game's menus */
CHECK(!gm_move_counts(1, 5, 5, 5, 5, 4) && gm_move_counts(1, 5, 6, 5, 5, 4));
CHECK(!gm_move_counts(0, 9, 1, 5, 5, 4) && gm_move_counts(0, 10, 5, 5, 5, 4) && gm_move_counts(0, 5, 0, 5, 5, 4));
printf("PASS\n");
return 0;
}
'''
class CursorHiddenInPlayTests(unittest.TestCase):
def test_the_cursor_is_shown_until_the_pads_and_hidden_until_a_real_move(self):
start = DISPLAY.index("static volatile LONG gm_shown")
state = DISPLAY[start:DISPLAY.index("static int gm_move_counts(", start)]
state = state[:state.rindex("/*")] # (without the next function's comment)
cursor = "\n".join([state, function("static int gm_move_counts("), function("static void gm_mouse_moved(HWND w)")])
with tempfile.TemporaryDirectory(prefix="triforce-cursor-") as temp:
source, executable = Path(temp) / "fixture.c", Path(temp) / "fixture.exe"
source.write_text(FIXTURE.replace("@CURSOR@", cursor), encoding="utf-8")
subprocess.run([CC, "-std=c11", "-O0", "-Wall", "-Wextra", "-Werror", str(source), "-o", str(executable)], check=True)
run = subprocess.run([str(executable)], capture_output=True, text=True)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
def test_set_cursor_hides_it_outside_the_game_menus(self):
body = case("WM_SETCURSOR")
self.assertIn("(mouse_captured || (!menu_open && !gm_cursor_shown()))", body)
self.assertNotIn("game_menu_open", body)
def test_a_move_counts_in_play_and_under_the_options(self):
body = case("WM_MOUSEMOVE")
self.assertIn("if (!mouse_captured) gm_mouse_moved(w);", body) # (the captured mouse's moves are the camera's)
self.assertNotIn("menu_open", body.split("gm_mouse_moved(w);")[0])
def test_the_pads_hide_it_at_once_in_play(self):
body = case("WM_TIMER")
line = next(l for l in body.splitlines() if "gm_cursor_off(w);" in l)
self.assertNotIn("game_menu_open", line)
self.assertIn("!menu_open && !gm_cursor_shown()", line)
self.assertIn("GetForegroundWindow() == w", line)
def test_a_game_menu_hides_it_at_the_screen_point(self):
# (the point a move is measured from is a screen point everywhere: not turned into a client point here)
body = function("static void menus_mouse(HWND w, int insert_open, int game_open)")
hide = body[body.index("GetCursorPos(&at);"):body.index("gm_my = at.y;")]
self.assertNotIn("ScreenToClient", hide)
self.assertIn("InterlockedExchange(&gm_shown, 0), gm_mx = at.x", hide)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--cc", default="gcc")
args, rest = parser.parse_known_args()
CC = args.cc
unittest.main(argv=sys.argv[:1] + rest)

Some files were not shown because too many files have changed in this diff Show More