Initial public release
This commit is contained in:
@@ -0,0 +1 @@
|
||||
build/
|
||||
@@ -0,0 +1,104 @@
|
||||
DM_ROOT ?= $(HOME)/dm-work
|
||||
# dm/host 单测一条命令:make -C dm/host/tests run(秒级;产物放 build/ 不进仓)
|
||||
# dm/host unit tests in one command: make -C dm/host/tests run (takes seconds; build output goes to build/ and is not committed)
|
||||
PY ?= $(DM_ROOT)/build/cache/dm/venv/bin/python
|
||||
EXEFS ?= $(DM_ROOT)/data/switch/3.3.94012/Update/ExeFS
|
||||
B = build
|
||||
run: $(B)/t_textbox $(B)/t_padmap $(B)/t_touch $(B)/t_hid_receipt $(B)/t_hid_script $(B)/t_touch_mac $(B)/t_oe $(B)/t_fs $(B)/t_fs_case $(B)/t_romfs_validate $(B)/t_audio $(B)/t_audio_spsc $(B)/t_swkbd $(B)/t_altstack $(B)/t_movie $(B)/t_condvar $(B)/t_condvar_old $(B)/t_target_rank $(B)/t_hud_dead $(B)/t_namegen $(B)/t_modetx $(B)/t_unit_level $(B)/t_widget $(B)/t_doorspot $(B)/t_cloudsync $(B)/t_i18n $(B)/main.orig.bin $(B)/subsdk0.orig.bin
|
||||
python3 native_write_scan.py --selftest ..
|
||||
python3 mode_scan.py ../..
|
||||
python3 ../../ios/tools/dm_i18n.py --check
|
||||
python3 ../../i18n/scan_literals.py
|
||||
$(B)/t_textbox
|
||||
$(B)/t_touch
|
||||
$(B)/t_hid_script 2>/dev/null
|
||||
$(B)/t_hid_receipt 2>/dev/null
|
||||
$(B)/t_touch_mac
|
||||
$(B)/t_oe 2>/dev/null
|
||||
$(B)/t_fs 2>/dev/null
|
||||
TMPDIR="$(abspath $(B))" $(B)/t_fs_case 2>/dev/null
|
||||
DM_ROMFS="$(DM_ROOT)/data/switch/3.3.94012/Update/RomFS" $(B)/t_romfs_validate
|
||||
$(B)/t_audio
|
||||
$(B)/t_audio_spsc
|
||||
$(B)/t_swkbd
|
||||
$(B)/t_altstack
|
||||
$(B)/t_movie
|
||||
$(B)/t_condvar
|
||||
$(B)/t_condvar_old
|
||||
$(B)/t_target_rank 2>/dev/null
|
||||
$(B)/t_hud_dead
|
||||
$(B)/t_namegen
|
||||
$(B)/t_modetx
|
||||
$(B)/t_padmap
|
||||
$(B)/t_unit_level
|
||||
$(B)/t_widget
|
||||
$(B)/t_doorspot
|
||||
TMPDIR="$(abspath $(B))" $(B)/t_cloudsync 2>/dev/null
|
||||
for m in en zh none sysen systw tags game; do TMPDIR="$(abspath $(B))" $(B)/t_i18n $$m || exit 1; done
|
||||
$(PY) movie_cut.py $(B)/main.orig.bin $(B)/subsdk0.orig.bin
|
||||
$(PY) oe_notify.py $(B)/main.orig.bin
|
||||
$(B)/t_i18n: t_i18n.c ../dm_i18n.c ../dm_i18n.h ../dm_i18n_tab.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_i18n.c ../dm_i18n.c
|
||||
$(B)/t_hud_dead: t_hud_dead.c ../dm_hud.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_hud_dead.c
|
||||
$(B)/t_textbox: t_textbox.c ../dm_textbox_core.c ../dm_textbox_core.h | $(B)
|
||||
clang -O1 -Wall -Werror -o $@ t_textbox.c ../dm_textbox_core.c
|
||||
$(B)/t_doorspot: t_doorspot.c ../dm_doorspot.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_doorspot.c
|
||||
$(B)/t_widget: t_widget.c ../dm_widget.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_widget.c
|
||||
$(B)/t_unit_level: t_unit_level.c ../dm_unit.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_unit_level.c
|
||||
$(B)/t_padmap: t_padmap.c ../dm_padmap.h ../dm_input.h | $(B)
|
||||
clang -O1 -Wall -Werror -o $@ t_padmap.c
|
||||
$(B)/t_modetx: t_modetx.c ../dm_modetx.h | $(B)
|
||||
clang -O1 -Wall -Werror -o $@ t_modetx.c
|
||||
$(B)/t_namegen: t_namegen.c ../dm_namegen.c | $(B)
|
||||
clang -O1 -Wall -Werror -o $@ t_namegen.c ../dm_namegen.c
|
||||
$(B)/t_cloudsync: t_cloudsync.c ../dm_cloudsync.c ../dm.h | $(B)
|
||||
clang -O1 -Wall -Werror -I.. -o $@ t_cloudsync.c ../dm_cloudsync.c
|
||||
$(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_touch.c ../hle_touch.c
|
||||
$(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_fs.c t_fs_stub.c ../dm_i18n.c
|
||||
$(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox
|
||||
$(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox
|
||||
$(B)/t_audio_spsc_tsan: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox
|
||||
$(B)/t_swkbd: t_swkbd.c ../hle_swkbd.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_swkbd.c ../hle_swkbd.c
|
||||
$(B)/t_movie: t_movie.c ../hle_movie.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_movie.c ../hle_movie.c
|
||||
$(B)/t_altstack: t_altstack.c t_altstack_stub.c ../crash.c ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_altstack.c t_altstack_stub.c ../crash.c
|
||||
$(B)/%.orig.bin: $(EXEFS)/% | $(B)
|
||||
$(PY) ../../tools/nso.py $< $@ > /dev/null
|
||||
$(B):
|
||||
mkdir -p $@
|
||||
.PHONY: run tsan
|
||||
tsan: $(B)/t_audio_spsc_tsan
|
||||
$(B)/t_audio_spsc_tsan
|
||||
$(B)/t_condvar: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -I.. -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c
|
||||
$(B)/t_condvar_old: t_condvar.c t_condvar_stub.c ../hle_thread.c ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -DDM_TEST_HOOKS -DDM_TEST_CV_OLD_ORDER -I.. -o $@ t_condvar.c t_condvar_stub.c ../hle_thread.c
|
||||
|
||||
$(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_fs_case.c ../dm_i18n.c
|
||||
$(B)/t_romfs_validate: t_romfs_validate.c ../romfs_validate.c ../romfs_validate.h ../dm_i18n.c ../dm_i18n_tab.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_romfs_validate.c ../romfs_validate.c ../dm_i18n.c
|
||||
|
||||
$(B)/t_hid_script: t_hid_script.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_script.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
|
||||
|
||||
$(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_oe.c
|
||||
|
||||
$(B)/t_hid_receipt: t_hid_receipt.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_receipt.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
|
||||
$(B)/t_touch_mac: t_touch_mac.c ../touch_mac.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../../ios/Sources/dm_touch_controls.c ../../ios/Sources/dm_touch_controls.h ../../host/dm_input.h | $(B) # 测试 #include 了 touch_mac.c 与 dm_touch_controls.c,须列为依赖(漏列致改源不重编) | the test #includes touch_mac.c and dm_touch_controls.c, which must be listed as dependencies (omitting them means source changes do not trigger a rebuild)
|
||||
clang -std=c11 -Wall -Wextra -Werror -I.. -I../../ios/Sources -o $@ t_touch_mac.c ../dm_cursor.c ../dm_hud.c -lm
|
||||
$(B)/t_target_rank: t_target_rank.c ../hle_target.c ../dm.h | $(B)
|
||||
clang -O1 -Wno-unused-function -I.. -o $@ t_target_rank.c ../hle_target.c
|
||||
@@ -0,0 +1,21 @@
|
||||
# 只执行原GetStat之后的客户端STA门/规则跳板;末端用明确STOP替身,不验证原getter或真实Move速度。
|
||||
# Executes only the client STA gate/rule trampoline after the original GetStat; the end uses an explicit STOP stand-in, and neither the original getter nor the real Move speed is verified.
|
||||
import sys,struct
|
||||
from pathlib import Path
|
||||
from unicorn import Uc,UC_ARCH_ARM64,UC_MODE_ARM,UC_HOOK_CODE
|
||||
from unicorn.arm64_const import *
|
||||
b=Path(sys.argv[1]).read_bytes();u=Uc(UC_ARCH_ARM64,UC_MODE_ARM);u.mem_map(0,0x4000000);u.mem_write(0,b);u.mem_map(0x7000000,0x10000)
|
||||
UNIT=0x7001000;ctx={}
|
||||
def hook(u,a,n,d):
|
||||
if a in [0x4ac36c,0x4ac3f4]:ctx['target']=a;u.emu_stop()
|
||||
u.hook_add(UC_HOOK_CODE,hook);bad=0;n=0
|
||||
for kind in [0,1,2,3,4,5,6,99]:
|
||||
for sta in [0,1,22016,0xffffffff]:
|
||||
ctx.clear();u.mem_write(UNIT,struct.pack('<I',kind));u.reg_write(UC_ARM64_REG_X19,UNIT);u.reg_write(UC_ARM64_REG_W0,sta);u.reg_write(UC_ARM64_REG_SP,0x700f000);u.reg_write(UC_ARM64_REG_NZCV,0xa0000000)
|
||||
u.emu_start(0x4ac368,0x4000000,count=100)
|
||||
target=0x4ac3f4 if kind==0 or sta else 0x4ac36c
|
||||
ok=ctx.get('target')==target and u.reg_read(UC_ARM64_REG_W0)==sta and u.reg_read(UC_ARM64_REG_X19)==UNIT and u.reg_read(UC_ARM64_REG_SP)==0x700f000 and u.reg_read(UC_ARM64_REG_NZCV)==0xa0000000
|
||||
n+=1
|
||||
if not ok:bad+=1;print('FAIL type',kind,'STA',sta,'期望',hex(target),'→真',ctx)
|
||||
print(f'CLIENT_STA_GATE {n}项,失败{bad};仅type0跳STA自动Stop,非player保持原零/非零分支,原W0/X19/SP/NZCV不改;末端为替身')
|
||||
sys.exit(bool(bad))
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""手柄 / 触屏模式的登记闸门(宿主单测里跑,秒级)。只读源码,不跑游戏。
|
||||
三条:
|
||||
1. dm_cursor.c 每帧那一长行里的每个泵,要么带「if (tm) 」(触屏专属:手柄模式与切换进行中不跑),要么在它上方注释「两种模式都跑:」的单子上;
|
||||
文件里定义的每个 *_pump 也必须在这一行或那张单子上出现——新加一个泵、两边都不登记就红。
|
||||
2. 散判模式(dm_padmode_current())与替玩家按键 / 发消息(fe_key / ui_auto_key / fe_send / dm_ui_key_pulse)的处数按文件记在下面两张表里,只许减不许加。
|
||||
要加:先想清楚它在另一种模式下该停、照常还是换做法,登记进 dm_mode_items.h(要随切换清理的)或上面那张单子,再改这里的数并在提交说明里写原因。
|
||||
3. dm_mode_items.h 里登记的进 / 出函数都得有定义。
|
||||
用法:mode_scan.py <dm 目录>
|
||||
Registration gate for controller / touch modes (run in the host unit tests, takes seconds). Reads source only, does not run the game.
|
||||
Three rules:
|
||||
1. Every pump on the long per-frame line in dm_cursor.c either carries "if (tm) " (touch-only: not run in controller mode or while a switch is in progress) or is on the list in the comment above it headed 「两种模式都跑:」(runs in both modes:);
|
||||
every *_pump defined in the file must also appear on this line or on that list -- a newly added pump registered in neither fails.
|
||||
2. The number of places that check the mode ad hoc (dm_padmode_current()) and that press keys / send messages on the player's behalf (fe_key / ui_auto_key / fe_send / dm_ui_key_pulse) is recorded per file in the two tables below, and may only decrease, never increase.
|
||||
To add one: first think through whether in the other mode it should stop, carry on as usual, or work differently, register it in dm_mode_items.h (for things to be cleaned up on a switch) or on the list above, then change the number here and state the reason in the commit message.
|
||||
3. Every enter / leave function registered in dm_mode_items.h must have a definition.
|
||||
Usage: mode_scan.py <dm directory>
|
||||
"""
|
||||
import re, sys, os, glob
|
||||
root = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '..', '..')
|
||||
red = []
|
||||
def src(rel): return open(os.path.join(root, rel), encoding='utf-8').read()
|
||||
def strip_comments(s): return re.sub(r'//[^\n]*', '', re.sub(r'/\*.*?\*/', '', s, flags=re.S))
|
||||
|
||||
# ---- 1 ----
|
||||
cur = src('host/dm_cursor.c')
|
||||
m = re.search(r'^.*int tm = ui_touch_mode\(\);.*$', cur, re.M)
|
||||
if not m: red.append('dm_cursor.c 里找不到每帧那一行(int tm = ui_touch_mode();)')
|
||||
else:
|
||||
line = m.group(0)
|
||||
both_txt = re.search(r'两种模式都跑:(.*?)\nstatic int ui_touch_mode', cur, re.S)
|
||||
both = set(re.findall(r'\b(\w+_pump|ui_map_center|ui_panel_heal)\b', both_txt.group(1))) if both_txt else set()
|
||||
if not both: red.append('dm_cursor.c 里找不到「两种模式都跑:」那张单子')
|
||||
on_line = {}
|
||||
for mm in re.finditer(r'(if \(tm\) )?\b(\w+_pump|ui_map_center)\(', line): on_line[mm.group(2)] = bool(mm.group(1))
|
||||
for name, gated in sorted(on_line.items()):
|
||||
if not gated and name not in both: red.append('每帧那一行里的 %s 既没带 if (tm)、也不在「两种模式都跑」单子上' % name)
|
||||
if gated and name in both: red.append('%s 带了 if (tm) 又列在「两种模式都跑」单子上,二选一' % name)
|
||||
for name in sorted(set(re.findall(r'^static void (\w+_pump)\(', cur, re.M))):
|
||||
if name not in on_line and name not in both: red.append('dm_cursor.c 定义了 %s,但每帧那一行和「两种模式都跑」单子上都没有它' % name)
|
||||
|
||||
# ---- 2 ----
|
||||
PADMODE = {'host/dm_cursor.c': 8, 'host/dm_custom.c': 2, 'host/dm_kills.c': 2, 'host/dm_rift_ui.c': 4, 'host/dm_runeword.c': 3, 'host/dm_vault_ui.c': 1, 'host/dm_update.c': 2, 'host/hle_tact.c': 1}
|
||||
AUTOKEY = {'host/dm_cursor.c': 38, 'host/dm_rift_ui.c': 6, 'host/hle_hid.c': 2, 'ios/Sources/front_ios.m': 4}
|
||||
def count(pat, skip_defs):
|
||||
out = {}
|
||||
for f in sorted(glob.glob(os.path.join(root, 'host', '*.c')) + glob.glob(os.path.join(root, 'ios', 'Sources', '*.m')) + glob.glob(os.path.join(root, 'ios', 'Sources', '*.c'))):
|
||||
rel = os.path.relpath(f, root); s = strip_comments(open(f, encoding='utf-8').read()); n = 0
|
||||
for mm in re.finditer(pat, s):
|
||||
ls = s.rfind('\n', 0, mm.start()) + 1; head = s[ls:mm.start()]
|
||||
if skip_defs and re.search(r'(^|\s)(static\s+)?(void|int|uint64_t)\s+$', head): continue # 函数定义 / 声明本身不算调用 | A function definition / declaration itself does not count as a call
|
||||
n += 1
|
||||
if n: out[rel] = n
|
||||
return out
|
||||
for label, table, got in (('散判模式 dm_padmode_current()', PADMODE, count(r'\bdm_padmode_current\(\)', True)),
|
||||
('替玩家按键 / 发消息', AUTOKEY, count(r'\b(fe_key|ui_auto_key|fe_send|dm_ui_key_pulse|dm_ui_key_pulse_alone|dm_ui_send|dm_ui_send_queue)\(', True))):
|
||||
if label.startswith('散判') and 'host/dm_padmode.c' in got: got.pop('host/dm_padmode.c')
|
||||
for rel in sorted(set(got) | set(table)):
|
||||
g, t = got.get(rel, 0), table.get(rel, 0)
|
||||
if g > t: red.append('%s:%s 现有 %d 处,表里记的是 %d 处——新增的先登记(见本文件开头),再改表' % (label, rel, g, t))
|
||||
elif g < t: red.append('%s:%s 现有 %d 处,比表里的 %d 少了——把表里的数改小(只许减)' % (label, rel, g, t))
|
||||
|
||||
# ---- 3 ----
|
||||
items = src('host/dm_mode_items.h'); allsrc = ''.join(open(f, encoding='utf-8').read() for f in glob.glob(os.path.join(root, 'host', '*.c')))
|
||||
for name, side, enter, leave in re.findall(r'X\("([^"]+)",\s*(\d),\s*(\w+),\s*(\w+)\)', items):
|
||||
for fn in (enter, leave):
|
||||
if not re.search(r'\bvoid %s\(void\)\s*\{' % fn, allsrc): red.append('dm_mode_items.h 登记项「%s」的函数 %s 没有定义' % (name, fn))
|
||||
|
||||
if red:
|
||||
print('模式登记闸门 红:%d 条' % len(red)); [print(' ' + r) for r in red]; sys.exit(1)
|
||||
print('✓ 模式登记闸门:每帧泵 %d 个都已分类,散判模式与替按键的处数没有超出登记,登记项函数齐全' % (len(on_line) if m else 0))
|
||||
@@ -0,0 +1,47 @@
|
||||
# 执行原ARM编解码;只有libm调用用显式f32替身。不是速度或游戏停止判据。
|
||||
# Executes the original ARM codec; only libm calls use explicit f32 stand-ins. Not a criterion for speed or for the game stopping.
|
||||
import math, struct, hashlib, sys
|
||||
from pathlib import Path
|
||||
from unicorn import Uc, UC_ARCH_ARM64, UC_MODE_ARM, UC_HOOK_CODE
|
||||
from unicorn.arm64_const import *
|
||||
P=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('build')/'main.orig.bin'
|
||||
b=P.read_bytes(); u=Uc(UC_ARCH_ARM64,UC_MODE_ARM)
|
||||
u.mem_map(0,0x4000000); u.mem_write(0,b)
|
||||
u.mem_map(0x7000000,0x20000)
|
||||
STOP,VEC,OUT,AMP,FLAG=0x7000000,0x7001000,0x7002000,0x7002010,0x7002020
|
||||
bits=lambda v:struct.unpack('<I',struct.pack('<f',v))[0]
|
||||
flt=lambda v:struct.unpack('<f',struct.pack('<I',v))[0]
|
||||
def hook(u,a,n,d):
|
||||
if a==STOP: u.emu_stop(); return
|
||||
fn={0x1b77270:lambda:math.atan2(flt(u.reg_read(UC_ARM64_REG_S0)),flt(u.reg_read(UC_ARM64_REG_S1))),
|
||||
0x1b77220:lambda:math.fmod(flt(u.reg_read(UC_ARM64_REG_S0)),flt(u.reg_read(UC_ARM64_REG_S1))),
|
||||
0x1b77130:lambda:math.cos(flt(u.reg_read(UC_ARM64_REG_S0))),
|
||||
0x1b77120:lambda:math.sin(flt(u.reg_read(UC_ARM64_REG_S0)))}.get(a)
|
||||
if fn:
|
||||
u.reg_write(UC_ARM64_REG_S0,bits(fn())); u.reg_write(UC_ARM64_REG_PC,u.reg_read(UC_ARM64_REG_LR))
|
||||
u.hook_add(UC_HOOK_CODE,hook)
|
||||
def call(pc):
|
||||
u.reg_write(UC_ARM64_REG_SP,0x701fff0);u.reg_write(UC_ARM64_REG_LR,STOP)
|
||||
u.emu_start(pc,STOP+4,count=3000)
|
||||
assert u.reg_read(UC_ARM64_REG_PC)==STOP
|
||||
n=0
|
||||
# 期望先写死:四轴方向10bit=512/768/0/256;幅度5bit=0/0/0/7/15/31/31。
|
||||
# Expectations hard-coded first: four-axis direction 10bit=512/768/0/256; magnitude 5bit=0/0/0/7/15/31/31.
|
||||
for dx,dy,direction in [(1,0,512),(0,1,768),(-1,0,0),(0,-1,256)]:
|
||||
packets=[]
|
||||
for amp,mag in [(-1,0),(0,0),(1/64,0),(.25,7),(.5,15),(1,31),(2,31)]:
|
||||
pair=[]
|
||||
for run in [0,1]:
|
||||
u.mem_write(VEC,struct.pack('<ff',dx,dy));u.reg_write(UC_ARM64_REG_X0,VEC);u.reg_write(UC_ARM64_REG_X1,run);u.reg_write(UC_ARM64_REG_S0,bits(amp));call(0x4cd4b0)
|
||||
packet=u.reg_read(UC_ARM64_REG_W0);want=direction|(mag<<10)|(run<<15)
|
||||
assert packet==want,('encode',dx,dy,amp,run,hex(packet),hex(want))
|
||||
pair.append(packet)
|
||||
u.mem_write(OUT,b'\xff'*0x30);u.reg_write(UC_ARM64_REG_X0,packet);u.reg_write(UC_ARM64_REG_X1,OUT);u.reg_write(UC_ARM64_REG_X2,AMP);u.reg_write(UC_ARM64_REG_X3,FLAG);call(0x4cd5f0)
|
||||
x,y=struct.unpack('<ff',u.mem_read(OUT,8));a=struct.unpack('<f',u.mem_read(AMP,4))[0];f=u.mem_read(FLAG,1)[0]
|
||||
assert abs(x-dx)<1e-6 and abs(y-dy)<1e-6,('direction',dx,dy,x,y)
|
||||
assert abs(a-mag/31)<1e-7 and f==run,('decode',amp,mag,a,f,run)
|
||||
n+=1
|
||||
assert pair[0]^pair[1]==0x8000
|
||||
print(f'轴({dx},{dy}) 方向码{direction}:7幅度×2走跑位,编解码全同')
|
||||
print('原映像SHA256',hashlib.sha256(b).hexdigest())
|
||||
print(f'ORIGINAL_MOVE_CODEC OK {n}/{n};28对只差bit15,零/微幅量化保持0;未测速度/停杆/真实动作')
|
||||
@@ -0,0 +1,93 @@
|
||||
# 过场空播静态核对(hle_movie.c 头注释里的游戏侧协议):在原映像上逐条核关键指令与虚表槽名,任一不符即红。
|
||||
# 用法:movie_cut.py <main.orig.bin> <subsdk0.orig.bin> (.orig.bin 由 dm/tools/nso.py 从 ExeFS 生成)
|
||||
# Static check of cutscene no-op playback (the game-side protocol in the header comment of hle_movie.c): check the key instructions and vtable slot names one by one on the original image; any mismatch is a failure.
|
||||
# Usage: movie_cut.py <main.orig.bin> <subsdk0.orig.bin> (.orig.bin is generated from ExeFS by dm/tools/nso.py)
|
||||
import struct, sys
|
||||
from capstone import *
|
||||
main, sub = open(sys.argv[1], 'rb').read(), open(sys.argv[2], 'rb').read()
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
|
||||
def ins(a): i = next(md.disasm(main[a:a + 4], a)); return f'{i.mnemonic} {i.op_str}'
|
||||
|
||||
# (偏移, 期望反汇编, 这条在链里的意义)——过场「按真实时长空播」所依赖的游戏侧协议(hle_movie.c 头注释)
|
||||
# (offset, expected disassembly, meaning of this instruction in the chain) -- the game-side protocol that cutscene "no-op playback for the real duration" (plays nothing but lasts the real duration) depends on (header comment of hle_movie.c)
|
||||
CHAIN = [
|
||||
(0x898ed0, 'mov w1, #0x10', 'Extractor 对象 0x10 字节:剪口把状态指针存在第二个字'),
|
||||
(0x899960, 'mov w1, #0x10', 'Decoder 对象 0x10 字节:同上'),
|
||||
(0x899780, 'ldr x8, [x8, #0x20]', 'Setup 调 Extractor 槽4 GetTrackCount'),
|
||||
(0x89979c, 'b.lt #0x899928', '轨数 < 1 跳过选轨(剪口给 0 轨)'),
|
||||
(0x898f70, 'stp x24, x23, [x19, #0x1b8]', 'DecoderEvents[0..1] = {P+0x18, P+0x40}'),
|
||||
(0x899044, 'mov w8, #1', 'P+0x18 的等待项种类 1 = 输入可用'),
|
||||
(0x8990b8, 'mov w8, #2', 'P+0x40 的等待项种类 2 = 输出可用'),
|
||||
(0x8999e4, 'ldr x8, [x8, #0x28]', 'Setup 调 Decoder 槽5 Start'),
|
||||
(0x899f54, 'cmp w21, #0', 'Open 返回 (Start 状态 == 0):剪口 Start 成功 ⇒ 在播'),
|
||||
(0x899f5c, 'cset w0, eq', ''),
|
||||
(0xbbfe40, 'bl #0x898230', '每帧更新调播放器更新'),
|
||||
(0x89832c, 'ldrb w8, [x8, #0x489]', '帧队列空时返回 !P[+0x489](播完标志)…'),
|
||||
(0x898334, 'cset w0, eq', '… 未播完即视为在播'),
|
||||
(0x8992e0, 'cmp w21, #1', '解码线程:种类 1 走输入路径'),
|
||||
(0x8992e8, 'cmp w21, #2', '解码线程:种类 2 走输出路径'),
|
||||
(0x899508, 'ldr x8, [x8, #0x48]', '输入:Decoder 槽9 AcquireInputBufferIndex'),
|
||||
(0x899534, 'ldr x8, [x8, #0x50]', '输入:Decoder 槽10 GetInputBuffer'),
|
||||
(0x8995a8, 'ldr x8, [x8, #0x50]', '输入:Extractor 槽10 Read'),
|
||||
(0x8995b8, 'cmp w23, #2, lsl #12', 'Read 返回 0x2000 = 流尾 …'),
|
||||
(0x8995c0, 'ldrb w8, [x19, #0x12]', '… 循环标志 …'),
|
||||
(0x8995d4, 'ldr x8, [x8, #0x40]', '… 循环则 Extractor 槽8 SeekTo(剪口重挂定时)'),
|
||||
(0x899620, 'mov w26, #4', '… 否则送入标志 4(流尾)'),
|
||||
(0x899634, 'ldr x8, [x8, #0x60]', '输入:Extractor 槽12 GetSampleTime'),
|
||||
(0x899670, 'ldr x8, [x8, #0x58]', '输入:Decoder 槽11 SendInputBufferForDecode'),
|
||||
(0x89968c, 'ldr x8, [x8, #0x58]', '输入:Extractor 槽11 Advance'),
|
||||
(0x89932c, 'ldr x8, [x8, #0x60]', '输出:Decoder 槽12 AcquireOutputBufferIndex'),
|
||||
(0x899338, 'tst w0, #0xffffdfff', '状态 0 / 0x2000 才入帧队列(剪口无输出回 0x1008)'),
|
||||
(0x899cb4, 'cmp x9, #2', '丢帧只在队列 ≥2 时(单个流尾项不会被丢)'),
|
||||
(0x89a650, 'ldr x8, [x8, #0x90]', '取帧:Decoder 槽18 GetOutputBufferFormat(剪口回非 0)'),
|
||||
(0x89a65c, 'cmp w27, #4', '标志 4 …'),
|
||||
(0x89a670, 'strb w8, [x25, #0x489]', '… 置播完 ⇒ 游戏走正常播完路径'),
|
||||
(0x899fdc, 'ldr x8, [x8, #0x30]', '收尾调 Decoder 槽6 Stop(剪口撤销定时)'),
|
||||
(0x899ff0, 'ldr x8, [x8, #8]', '收尾调 Decoder 槽1 删除析构'),
|
||||
(0x89a004, 'ldr x8, [x8, #8]', '收尾调 Extractor 槽1 删除析构'),
|
||||
]
|
||||
bad = 0
|
||||
for a, want, why in CHAIN:
|
||||
got = ins(a); ok = got == want; bad += not ok
|
||||
print(f'{"✓" if ok else "✗"} {a:#x} {got:28s} {"" if ok else "期望 " + want} {why}')
|
||||
|
||||
# 虚表槽名(subsdk0 动态符号 + RELATIVE 重定位):剪口虚表按这些槽号排
|
||||
# Vtable slot names (subsdk0 dynamic symbols + RELATIVE relocations): the cut vtable is ordered by these slot numbers
|
||||
m0 = struct.unpack_from('<I', sub, 4)[0]; dyn = m0 + struct.unpack_from('<i', sub, m0 + 4)[0]
|
||||
D = {}; o = dyn
|
||||
while True:
|
||||
t, v = struct.unpack_from('<qQ', sub, o); o += 16
|
||||
if t == 0: break
|
||||
D.setdefault(t, v)
|
||||
rel = {}
|
||||
for k in range(D[8] // 24):
|
||||
off, info, add = struct.unpack_from('<QQq', sub, D[7] + 24 * k)
|
||||
rel[off] = add if info & 0xffffffff == 1027 else ('sym', info >> 32) # RELATIVE 给地址;ABS64 / GLOB_DAT 给符号号 | RELATIVE gives an address; ABS64 / GLOB_DAT give a symbol number
|
||||
names, sym, symn = {}, {}, {}
|
||||
for k in range(1, (D[5] - D[6]) // 24):
|
||||
nm, info, oth, shn, val, sz = struct.unpack_from('<IBBHQQ', sub, D[6] + 24 * k)
|
||||
s = sub[D[5] + nm:sub.index(b'\0', D[5] + nm)].decode(); symn[k] = s
|
||||
if shn and val: names.setdefault(val, s); sym[s] = val
|
||||
def slot_name(r): return symn.get(r[1], '?') if isinstance(r, tuple) else names.get(r, '?')
|
||||
VT = [('_ZTVN5movie9ExtractorE', 4, '_ZN5movie9Extractor13GetTrackCountEPi'),
|
||||
('_ZTVN5movie9ExtractorE', 15, '_ZN5movie9Extractor13SetDataSourceEPNS_18ClientStreamReaderEPKc'),
|
||||
('_ZTVN5movie7DecoderE', 2, '_ZN5movie7Decoder9ConfigureEPNS_9MediaDataE'),
|
||||
('_ZTVN5movie7DecoderE', 3, '_ZN5movie7Decoder20RegisterClientEventsEPNS_13DecoderEventsE'),
|
||||
('_ZTVN5movie7DecoderE', 5, '_ZN5movie7Decoder5StartEv'),
|
||||
('_ZTVN5movie7DecoderE', 6, '_ZN5movie7Decoder4StopEv'),
|
||||
('_ZTVN5movie9ExtractorE', 8, '_ZN5movie9Extractor6SeekToEl'),
|
||||
('_ZTVN5movie9ExtractorE', 10, '_ZN5movie9Extractor4ReadEPNS_6BufferE'),
|
||||
('_ZTVN5movie9ExtractorE', 11, '_ZN5movie9Extractor7AdvanceEv'),
|
||||
('_ZTVN5movie9ExtractorE', 12, '_ZN5movie9Extractor13GetSampleTimeEPl'),
|
||||
('_ZTVN5movie7DecoderE', 9, '_ZN5movie7Decoder23AcquireInputBufferIndexEPiS1_'),
|
||||
('_ZTVN5movie7DecoderE', 10, '_ZN5movie7Decoder14GetInputBufferEiPNS_6BufferE'),
|
||||
('_ZTVN5movie7DecoderE', 11, '_ZN5movie7Decoder24SendInputBufferForDecodeEiiilj'),
|
||||
('_ZTVN5movie7DecoderE', 12, '_ZN5movie7Decoder24AcquireOutputBufferIndexEPiPlPjS1_'),
|
||||
('_ZTVN5movie7DecoderE', 15, '_ZN5movie7Decoder24ReleaseOutputBufferIndexEi'),
|
||||
('_ZTVN5movie7DecoderE', 18, '_ZN5movie7Decoder21GetOutputBufferFormatEiPNS_9MediaDataE')]
|
||||
for vt, slot, want in VT:
|
||||
got = slot_name(rel.get(sym[vt] + 16 + 8 * slot, 0)); ok = got == want; bad += not ok
|
||||
print(f'{"✓" if ok else "✗"} {vt} 槽{slot} {got}{"" if ok else " 期望 " + want}')
|
||||
n = len(CHAIN) + len(VT)
|
||||
print(f'{"全过" if not bad else "红"}:{n - bad}/{n}')
|
||||
sys.exit(1 if bad else 0)
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
# 我们自己的功能不许写原版储藏箱控件(编年史仓库是独立页面;丢装备事故:编年史页把原版 grid 设成不可见、游戏从不重设,个人 / 共享页看起来全空)。
|
||||
# 静态扫:编年史页(dm_vault_ui.c 全文)与个人仓库页码(dm_cursor.c 的 ui_pages_pump)里不许出现原版储藏箱控件名——这两处只该碰 TouchVault / TouchPgPage 底下的控件。
|
||||
# 运行时另有一道:dm_vault_ui.c vu_guard(写之前沿父链核是不是我们的控件,不是就报红不写)。
|
||||
# 第二道(不写原版控件):整个宿主(dm/host/*.c)不许直接写控件的可见位 +0x50 / +0x51,只许在带守卫的函数里写——
|
||||
# dm_cursor.c ui_show_ours、dm_vault_ui.c vu_show、dm_kills.c kb_show(名字不是 Touch 开头就报红不写)。别处要改可见,调它们
|
||||
# 用法:native_write_scan.py <dm/host 目录>;--selftest 先拿一段故意违规的文本验这个扫描本身会报红
|
||||
# Our own features must not write the original game's stash widgets (the chronicle vault is a separate page; lost-equipment incident: the chronicle page set the original grid invisible and the game never resets it, so the personal / shared pages looked completely empty).
|
||||
# Static scan: the chronicle page (all of dm_vault_ui.c) and the personal stash page numbers (ui_pages_pump in dm_cursor.c) must not contain original stash widget names -- these two places should only touch widgets under TouchVault / TouchPgPage.
|
||||
# There is another check at run time: dm_vault_ui.c vu_guard (before writing, walk the parent chain to check whether it is our widget; if not, report a failure and do not write).
|
||||
# Second check (do not write original-game widgets): the whole host (dm/host/*.c) must not write a widget's visible flag +0x50 / +0x51 directly, only inside guarded functions --
|
||||
# dm_cursor.c ui_show_ours, dm_vault_ui.c vu_show, dm_kills.c kb_show (a name not starting with Touch is reported as a failure and not written). To change visibility elsewhere, call them
|
||||
# Usage: native_write_scan.py <dm/host directory>; --selftest first verifies with a deliberately violating piece of text that the scan itself reports a failure
|
||||
import os, re, sys
|
||||
|
||||
NATIVE = ['grid', 'gold_amount', 'gold_withdraw', 'gold_max', 'basicstash_container', 'advancedstash_gems', 'advancedstash_materials', 'advancedstash_runes',
|
||||
'advancedstash_horadriccube', 'SharedStashTabContainer', 'StashNavigation', 'CurrentSharedStashText', 'background', 'PreviousSeasonToggleDisplay']
|
||||
|
||||
def scan(text, where):
|
||||
bad = []
|
||||
for no, line in enumerate(text.split('\n'), 1):
|
||||
code = line.split('//', 1)[0]
|
||||
for nm in NATIVE:
|
||||
if re.search(r'"%s"' % re.escape(nm), code): bad.append('%s:%d 出现原版控件名「%s」:%s' % (where, no, nm, line.strip()[:120]))
|
||||
return bad
|
||||
|
||||
VIS = re.compile(r'\+\s*0x5[01]\)\s*=(?!=)')
|
||||
GUARDED = ('ui_show_ours', 'vu_show', 'kb_show')
|
||||
def vis_scan(text, where): # 直接写可见位的行;在带守卫的函数里(定义那一行或其函数体内)的不算 | lines that write the visible flag directly; those inside a guarded function (its definition line or its body) do not count
|
||||
bad, inside = [], None
|
||||
for no, line in enumerate(text.split('\n'), 1):
|
||||
m = re.match(r'static\s+\w+\s+(\w+)\(', line)
|
||||
if m: inside = m.group(1) if m.group(1) in GUARDED else None
|
||||
code = line.split('//', 1)[0]
|
||||
if VIS.search(code) and not inside: bad.append('%s:%d 直接写了可见位(要走 %s):%s' % (where, no, ' / '.join(GUARDED), line.strip()[:120]))
|
||||
if line.startswith('}'): inside = None
|
||||
return bad
|
||||
|
||||
# 第三道(位置守卫):dm_cursor.c 里写控件矩形(+0x70 x、+0x74 y、+0x78 宽、+0x7c 高)只许在 mv_offset(原版控件,名单 + 记原值 + 必写回)
|
||||
# 与 ui_move_ours(只许 Touch 开头)里。认两种写法:直接 *(int32_t *)(… + 0x7?) = …;或同一函数里先取 int32_t *名 = (int32_t *)(… + 0x7?),再写 名[k] = / *名 =
|
||||
# Third check (position guard): in dm_cursor.c, writing a widget rectangle (+0x70 x, +0x74 y, +0x78 width, +0x7c height) is allowed only in mv_offset (original-game widgets, allow list + record original value + must write back)
|
||||
# and in ui_move_ours (only names starting with Touch). Two forms are recognized: a direct *(int32_t *)(... + 0x7?) = ...; or, within the same function, first taking int32_t *name = (int32_t *)(... + 0x7?) and then writing name[k] = / *name =
|
||||
RECT_OK = ('mv_offset', 'ui_move_ours')
|
||||
RECT_PTR = re.compile(r'int32_t\s*\*\s*(\w+)\s*=\s*\(int32_t\s*\*\)\s*\([^;]*\+\s*0x7[0-9a-c]\b')
|
||||
RECT_DIRECT = re.compile(r'\*\s*\(int32_t\s*\*\)\s*\([^)]*\+\s*0x7[0-9a-c]\)\s*=(?!=)')
|
||||
def rect_scan(text, where):
|
||||
bad, fn, ptrs = [], None, set()
|
||||
for no, line in enumerate(text.split('\n'), 1):
|
||||
m = re.match(r'(?:static\s+)?\w+\s+\*?(\w+)\(', line)
|
||||
if m and not line.startswith(' '): fn, ptrs = m.group(1), set()
|
||||
code = line.split('//', 1)[0]
|
||||
for pm in RECT_PTR.finditer(code): ptrs.add(pm.group(1))
|
||||
code = RECT_PTR.sub('', code) # 声明那一处(int32_t *名 = …)本身不算写 | the declaration itself (int32_t *name = ...) does not count as a write
|
||||
hit = RECT_DIRECT.search(code) or any(re.search(r'(?<![\w.>])(?:\*\s*%s|%s\s*\[\s*\d\s*\])\s*=(?!=)' % (q, q), code) for q in ptrs)
|
||||
if hit and fn not in RECT_OK: bad.append('%s:%d 在 %s 里直接写了控件矩形(原版控件走 mv_offset、我们的走 ui_move_ours):%s' % (where, no, fn, line.strip()[:120]))
|
||||
return bad
|
||||
|
||||
def pages_pump(src):
|
||||
i = src.find('static void ui_pages_pump(')
|
||||
if i < 0: raise SystemExit('native_write_scan:dm_cursor.c 里找不到 ui_pages_pump(改名了要同步这里)')
|
||||
j = src.find('\n}\n', i)
|
||||
return src[i:j]
|
||||
|
||||
def main():
|
||||
if '--selftest' in sys.argv:
|
||||
if not scan(' vu_show(vu_find(bk, "grid", 2), 0);', 'selftest') or scan(' vu_show(vu_find(vt, "TouchV_Back", 0), 1); // "grid" 只在注释里', 'selftest') \
|
||||
or not vis_scan('static void f(uint64_t w) {\n *(uint8_t *)(w + 0x50) = 0;\n}', 'selftest') or vis_scan('static void ui_show_ours(uint64_t w, int on) {\n *(uint8_t *)(w + 0x50) = 1;\n}\n if (*(uint8_t *)(w + 0x50) == 1) x();', 'selftest') \
|
||||
or not rect_scan('static void f(uint64_t w) {\n int32_t *r = (int32_t *)(w + 0x70); r[0] = 5;\n}', 'selftest') or not rect_scan('static void g(uint64_t w) {\n *(int32_t *)(w + 0x74) = 3;\n}', 'selftest') \
|
||||
or rect_scan('static void k(uint64_t w) {\n int32_t *rx = (int32_t *)(w + 0x70), ww = *(int32_t *)(w + 0x78); if (*rx) x();\n}\nstatic void mv_offset(uint64_t w) {\n int32_t *v = (int32_t *)(w + 0x70); *v = 1;\n}\nstatic int h(float *r) {\n r[0] = 1.0f; int x = *(int32_t *)(w + 0x70); return x;\n}', 'selftest'):
|
||||
print('✗ native_write_scan 自检失败:该报的没报或不该报的报了'); return 1
|
||||
print('✓ native_write_scan 自检:违规行会报红、注释里的名字不算')
|
||||
host = next(a for a in sys.argv[1:] if not a.startswith('--'))
|
||||
bad = scan(open(os.path.join(host, 'dm_vault_ui.c'), encoding='utf-8').read(), 'dm_vault_ui.c')
|
||||
bad += scan(pages_pump(open(os.path.join(host, 'dm_cursor.c'), encoding='utf-8').read()), 'dm_cursor.c ui_pages_pump')
|
||||
srcs = sorted(f for f in os.listdir(host) if f.endswith('.c'))
|
||||
for f in srcs: bad += vis_scan(open(os.path.join(host, f), encoding='utf-8', errors='replace').read(), f)
|
||||
bad += rect_scan(open(os.path.join(host, 'dm_cursor.c'), encoding='utf-8').read(), 'dm_cursor.c')
|
||||
if bad:
|
||||
print('✗ 我们的功能碰了原版控件(编年史页 / 个人仓库页码只许写 TouchVault / TouchPgPage 底下的;可见位只许走带守卫的函数):'); [print(' ' + b) for b in bad]; return 1
|
||||
print('✓ 编年史页与个人仓库页码不碰原版储藏箱控件(扫 %d 个名字);宿主 %d 个源文件没有绕过守卫直接写可见位;dm_cursor.c 写控件矩形只在 mv_offset / ui_move_ours 里' % (len(NATIVE), len(srcs))); return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,59 @@
|
||||
# 直接跑原映像 main+e10d30;只替换系统查询与resize回调,不重写消费函数。
|
||||
# 手写期望:消息循环结束focus/op/perf各为当前值;目标尺寸对应性能档;相同目标仅resize一次。
|
||||
# Runs the original image main+e10d30 directly; only the system queries and the resize callback are replaced, the consumer function is not rewritten.
|
||||
# Hand-written expectations: at the end of the message loop focus/op/perf each hold the current value; the target size corresponds to the performance mode; the same target is resized only once.
|
||||
import struct,itertools,hashlib,sys
|
||||
from pathlib import Path
|
||||
from unicorn import Uc,UC_ARCH_ARM64,UC_MODE_ARM,UC_HOOK_CODE
|
||||
from unicorn.arm64_const import *
|
||||
P=Path(sys.argv[1]);b=P.read_bytes()
|
||||
u=Uc(UC_ARCH_ARM64,UC_MODE_ARM);u.mem_map(0,0x4000000);u.mem_write(0,b);u.mem_map(0x7000000,0x2000);u.mem_map(0x7100000,0x10000)
|
||||
if sys.argv[2:] == ['--negative']:
|
||||
u.mem_write(0xe10e24,bytes.fromhex('1f2003d5')) # 只在负对照中移除尺寸相同跳过,重复通知会重复resize | only in the negative control is the same-size skip removed, so repeated notifications resize repeatedly
|
||||
print('NEGATIVE:本地原函数副本e10e24 b.eq→nop,不改资源正本')
|
||||
u.mem_write(0x3211718,struct.pack('<Q',0x7001001));u.mem_write(0x7001000,struct.pack('<Q',0x7001100));u.mem_write(0x7001110,struct.pack('<Q',0x7001200))
|
||||
state={}
|
||||
def hook(u,a,n,d):
|
||||
if a==0x7001800:u.emu_stop();return
|
||||
if a==0x1b77890:
|
||||
q=state['q'];out=u.reg_read(UC_ARM64_REG_X0)
|
||||
if q:u.mem_write(out,struct.pack('<I',q.pop(0)));u.reg_write(UC_ARM64_REG_X0,1)
|
||||
else:u.reg_write(UC_ARM64_REG_X0,0)
|
||||
elif a==0x1b778a0:u.reg_write(UC_ARM64_REG_X0,state['mode'])
|
||||
elif a==0x1b778b0:u.reg_write(UC_ARM64_REG_X0,state['focus'])
|
||||
elif a==0x1b778c0:u.reg_write(UC_ARM64_REG_X0,state['mode'])
|
||||
elif a==0x7001200:
|
||||
w=struct.unpack('<Q',u.mem_read(u.reg_read(UC_ARM64_REG_X3),8))[0];h=struct.unpack('<Q',u.mem_read(u.reg_read(UC_ARM64_REG_X4),8))[0]
|
||||
state['resize'].append((w,h));u.reg_write(UC_ARM64_REG_X0,0)
|
||||
else:return
|
||||
u.reg_write(UC_ARM64_REG_PC,u.reg_read(UC_ARM64_REG_LR))
|
||||
u.hook_add(UC_HOOK_CODE,hook)
|
||||
def run(q,mode,focus,canvas=(1600,900),target=(0,0)):
|
||||
state.update(q=list(q),mode=mode,focus=focus,resize=[])
|
||||
u.mem_write(0x211da30,struct.pack('<II',*canvas));u.mem_write(0x211da38,struct.pack('<II',*target))
|
||||
for a in [0x315e628,0x315e630,0x32137e8,0x32137ec]:u.mem_write(a,b'\x00'*8)
|
||||
u.reg_write(UC_ARM64_REG_SP,0x710fff0);u.reg_write(UC_ARM64_REG_LR,0x7001800)
|
||||
try:u.emu_start(0xe10d30,0x7001804,count=20000)
|
||||
except Exception:
|
||||
print("FAIL PC",hex(u.reg_read(UC_ARM64_REG_PC)),"LR",hex(u.reg_read(UC_ARM64_REG_LR)),"SP",hex(u.reg_read(UC_ARM64_REG_SP)));raise
|
||||
assert u.reg_read(UC_ARM64_REG_PC)==0x7001800,'未返回'
|
||||
return (struct.unpack('<I',u.mem_read(0x315e628,4))[0],u.mem_read(0x315e630,2),u.mem_read(0x32137e8,1),u.mem_read(0x32137ec,1),struct.unpack('<II',u.mem_read(0x211da38,8)),list(state['resize']))
|
||||
checks=0
|
||||
print('原映像SHA256',hashlib.sha256(b).hexdigest())
|
||||
for focus,mode in [(1,0),(3,1)]:
|
||||
for order in itertools.permutations([15,30,31]):
|
||||
full=[m for m in order for _ in range(11)] # 33条,确实超过旧32容量;每个消息仍不携带历史值 | 33 messages, really exceeding the old capacity of 32; each message still carries no historical value
|
||||
a=run(full,mode,focus);c=run(order,mode,focus);checks+=1
|
||||
size=(1280,720) if mode==0 else (1600,900)
|
||||
want=(focus,bytes([mode,mode]),bytes([mode]),bytes([mode]),size,[size])
|
||||
ok=a==c==want
|
||||
print(('✓' if ok else '✗')+f' 顺序{order} focus={focus} mode={mode}:33条原始通知/3条状态通知 → 写回相同且resize恰1次 {c}')
|
||||
if not ok:raise SystemExit(1)
|
||||
for mode in [0,1]:
|
||||
size=(1280,720) if mode==0 else (1600,900)
|
||||
for name,canvas,target,out,resizes in [('目标已匹配',(1600,900),size,size,[]),('容量不足',(1,1),(777,333),(777,333),[]),('宽度匹配高度不同',(1600,900),(size[0],333),size,[size])]:
|
||||
a=run([15]*11+[30]*11+[31]*11,mode,2,canvas,target);c=run([15,30,31],mode,2,canvas,target);checks+=1
|
||||
want=(2,bytes([mode,mode]),bytes([mode]),bytes([mode]),out,resizes)
|
||||
ok=a==c==want;print(('✓' if ok else '✗')+f' {name} mode={mode} focus=2:33/3条通知写回符合手写期望,resize={len(c[-1])}')
|
||||
if not ok:raise SystemExit(1)
|
||||
print(f'CONSUMER_EQUIV OK {checks}/{checks}:原版ARM消费函数、33→3通知、手写状态/尺寸/resize')
|
||||
@@ -0,0 +1,52 @@
|
||||
# 新规则产物独立登记核验;不执行游戏、不信任改写器自己的摘要。
|
||||
# Independent registration check of the new rule's build output; does not execute the game and does not trust the rewriter's own digest.
|
||||
import sys,struct,hashlib
|
||||
from pathlib import Path
|
||||
D=Path(sys.argv[1]); b=(D/'main.patched.bin').read_bytes(); orig=Path(sys.argv[2]).read_bytes()
|
||||
headers={};blocks=[]
|
||||
try:
|
||||
for line in (D/'main.rules.tsv').read_text().splitlines():
|
||||
if line.startswith('# '):k,v=line[2:].split('\t',1);headers[k]=v
|
||||
else:blocks.append(line.split('\t'))
|
||||
assert headers['RULESET']=='touch-run-v4'
|
||||
assert headers['BUILD_ID']=='db0507f36b84200ac05f75d76ed5026f'
|
||||
assert headers['ORIGINAL_SHA256']==hashlib.sha256(orig).hexdigest()=='6843ab6909f96e1558b4b73b0fa807f3873409120cf3e1ef8a86dbebb275ee27'
|
||||
assert headers['IMAGE_SHA256']==hashlib.sha256(b).hexdigest()
|
||||
expected={0x2c620c:0x52800029,0x2c6210:0xb90e5109,0x369a90:None,0x369980:0xd503201f,0x2b2c74:0xd503201f,0x2b2dc0:0xd503201f,0x2b30fc:0x52800021,0x2b3104:0x52800021,0x6dc2c4:0x52800062,0x6dce90:0xd503201f,0x6dcec0:None,0x6c6648:None,0x6c6290:None,0x4ac368:None,0x6c6580:None}
|
||||
cuts={}
|
||||
for line in (D/'main.cuts.tsv').read_text().splitlines():
|
||||
if line.startswith('#'):continue
|
||||
off,old,new,scope,why=line.split('\t',4)
|
||||
if why.startswith('touch-run-v4:'):cuts[int(off,16)]=(old,new,scope)
|
||||
assert set(cuts)==set(expected),('剪口集合',set(cuts)^set(expected))
|
||||
def w(at):return struct.unpack_from('<I',b,at)[0]
|
||||
def branch(at):
|
||||
v=w(at);assert v&0xfc000000==0x14000000;imm=v&0x3ffffff
|
||||
return at+4*((imm^0x2000000)-0x2000000)
|
||||
for off,newword in expected.items():
|
||||
old,new,scope=cuts[off];assert scope=='全';assert orig[off:off+4]==bytes.fromhex(old);assert b[off:off+4]==bytes.fromhex(new)
|
||||
if newword is not None:assert w(off)==newword
|
||||
assert branch(0x369a90)==0x369900 and branch(0x6dcec0)==0x6dce50
|
||||
assert len(blocks)==4
|
||||
fixheaders={}
|
||||
for line in (D/'main.fixups.tsv').read_text().splitlines():
|
||||
if line.startswith('# '):k,v=line[2:].split('\t');fixheaders[k]=int(v,0)
|
||||
po=fixheaders['PATCH_OFF'];seen=set()
|
||||
for off,raw,sha,why in blocks:
|
||||
off=int(off,16);body=bytes.fromhex(raw);assert po<=off<len(b) and off+len(body)<=len(b);assert b[off:off+len(body)]==body;assert hashlib.sha256(body).hexdigest()==sha
|
||||
src=next(s for s in [0x6c6648,0x6c6290,0x4ac368,0x6c6580] if branch(s)==off);assert src not in seen;seen.add(src)
|
||||
if src==0x6c6580:
|
||||
assert len(body)==24 and w(off)==0x35000088 and w(off+4)==0x51000849 and w(off+8)==0x35000049 and w(off+12)==0x52800062 and w(off+16)==0x51000849 and branch(off+20)==0x6c6584
|
||||
continue
|
||||
assert w(off)==0xb9400268
|
||||
assert w(off+4)==(0x34000048 if src==0x4ac368 else 0x35000048)
|
||||
if src==0x6c6648:
|
||||
assert len(body)==24 and branch(off+8)==0x6c664c and w(off+12)==0x34000040 and branch(off+16)==0x6c664c and branch(off+20)==0x6c6654
|
||||
elif src==0x6c6290:
|
||||
assert len(body)==20 and branch(off+8)==0x6c62ec and w(off+12)==0x710006df and branch(off+16)==0x6c6294
|
||||
else:
|
||||
assert len(body)==28 and branch(off+8)==off+16 and branch(off+12)==0x4ac3f4 and w(off+16)==0x34000040 and branch(off+20)==0x4ac3f4 and branch(off+24)==0x4ac36c
|
||||
assert seen=={0x6c6648,0x6c6290,0x4ac368,0x6c6580}
|
||||
print('RUN_MANIFEST OK 原像/成像hash、buildid、15剪口白名单、4跳板hash/范围/结构/入口B')
|
||||
except (AssertionError,KeyError,OSError,ValueError,StopIteration) as e:
|
||||
print('RUN_MANIFEST FAIL',type(e).__name__,str(e));sys.exit(1)
|
||||
@@ -0,0 +1,91 @@
|
||||
# 新规则的局部原ARM契约;不代替速度/真实动作矩阵。
|
||||
# Local original-ARM contract of the new rule; does not replace the speed/real action matrix.
|
||||
import sys,struct,hashlib
|
||||
from pathlib import Path
|
||||
from unicorn import Uc,UC_ARCH_ARM64,UC_MODE_ARM,UC_HOOK_CODE
|
||||
from unicorn.arm64_const import *
|
||||
orig=Path(sys.argv[1]).read_bytes(); candidate=Path(sys.argv[2]).read_bytes()
|
||||
U,P,R,A,L=0x7001000,0x7002000,0x7003000,0x7004000,0x7005000
|
||||
fails=[]; total=0
|
||||
class Machine:
|
||||
def __init__(self,blob):
|
||||
self.u=u=Uc(UC_ARCH_ARM64,UC_MODE_ARM);u.mem_map(0,0x4000000);u.mem_write(0,blob);u.mem_map(0x7000000,0x20000)
|
||||
for addr,v in [(U+0x38,P),(P,R),(P+0x20,R),(R+0x18,A),(A+0x90,L)]:u.mem_write(addr,struct.pack('<Q',v))
|
||||
self.sta=0;self.calls=[];self.stop=0
|
||||
u.hook_add(UC_HOOK_CODE,self.hook)
|
||||
def hook(self,u,a,n,d):
|
||||
if a==self.stop:u.emu_stop();return
|
||||
if a==0x5b9290:self.calls.append(('get',10));u.reg_write(UC_ARM64_REG_X0,self.sta)
|
||||
elif a==0x5a13a0:u.reg_write(UC_ARM64_REG_X0,0)
|
||||
elif a==0x5bc5a0:
|
||||
assert u.reg_read(UC_ARM64_REG_W1)==10
|
||||
v=u.reg_read(UC_ARM64_REG_W2);v=(v^0x80000000)-0x80000000
|
||||
self.calls.append(('add',v));self.sta+=v
|
||||
elif a==0x5bc1f0:
|
||||
assert u.reg_read(UC_ARM64_REG_W1)==10
|
||||
self.calls.append(('set',u.reg_read(UC_ARM64_REG_W2)));self.sta=u.reg_read(UC_ARM64_REG_W2)
|
||||
elif a==0x6c6550 and self.stop==0x6c62ec:self.calls.append(('downgrade',u.reg_read(UC_ARM64_REG_W2)))
|
||||
elif a==0x45f9d0:u.reg_write(UC_ARM64_REG_X0,U)
|
||||
elif a==0x460fd0:
|
||||
v=u.reg_read(UC_ARM64_REG_W1);self.calls.append(('mode',v));u.mem_write(U+0xc,struct.pack('<I',v));u.reg_write(UC_ARM64_REG_X0,0)
|
||||
elif a in [0x4bbc50,0x5ca8a0]:
|
||||
v=u.reg_read(UC_ARM64_REG_W1);self.calls.append(('mode',v));u.mem_write(U+0xc,struct.pack('<I',v))
|
||||
elif a==0x2ceab0:self.calls.append(('packet',u.mem_read(u.reg_read(UC_ARM64_REG_X0),1)[0]))
|
||||
elif a==0x5a7510:pass
|
||||
else:return
|
||||
u.reg_write(UC_ARM64_REG_PC,u.reg_read(UC_ARM64_REG_LR))
|
||||
def go(self,start,stop):
|
||||
self.stop=stop;self.u.reg_write(UC_ARM64_REG_SP,0x701fff0)
|
||||
self.u.emu_start(start,stop+4,count=3000)
|
||||
assert self.u.reg_read(UC_ARM64_REG_PC)==stop,hex(self.u.reg_read(UC_ARM64_REG_PC))
|
||||
def selector(self,typ,town,sta,mode):
|
||||
u=self.u;self.sta=sta;self.calls=[];u.mem_write(U,struct.pack('<I',typ));u.mem_write(L+0x1f8,struct.pack('<I',1 if town else 2))
|
||||
u.reg_write(UC_ARM64_REG_X0,0x7006000);u.reg_write(UC_ARM64_REG_X1,U);u.reg_write(UC_ARM64_REG_X2,mode)
|
||||
self.go(0x6c6550,0x6c6678);return u.reg_read(UC_ARM64_REG_W22)
|
||||
def drain(self,typ,sta):
|
||||
self.sta=sta;self.calls=[];u=self.u;u.mem_write(U,struct.pack('<I',typ));u.reg_write(UC_ARM64_REG_X19,U);u.reg_write(UC_ARM64_REG_X20,0x7006000);u.reg_write(UC_ARM64_REG_W22,2)
|
||||
self.go(0x6c6290,0x6c62ec);return self.sta,list(self.calls)
|
||||
def check(label,actual,want):
|
||||
global total
|
||||
total+=1
|
||||
if actual!=want:fails.append((label,actual,want))
|
||||
a,b=Machine(orig),Machine(candidate)
|
||||
for typ in [0,1,2,3,4,6]:
|
||||
for town in [False,True]:
|
||||
for sta in [0,1,22272]:
|
||||
for mode in [1,2,3,6,7,10,17,19]:
|
||||
old=a.selector(typ,town,sta,mode)
|
||||
want=3 if typ==0 and mode in (2,3) else old
|
||||
check(f'select type={typ} town={town} sta={sta} mode={mode}',b.selector(typ,town,sta,mode),want)
|
||||
for typ in [0,1,2,3,4,6]:
|
||||
for sta in [0,1,22272]:
|
||||
old=a.drain(typ,sta);want=(sta,[]) if typ==0 else old
|
||||
check(f'cost type={typ} sta={sta}',b.drain(typ,sta),want)
|
||||
for pref in [0,1]:
|
||||
for hyst in [0,1]:
|
||||
for latch in [0,1]:
|
||||
u=b.u;u.reg_write(UC_ARM64_REG_W10,pref);u.reg_write(UC_ARM64_REG_W8,hyst);u.reg_write(UC_ARM64_REG_W9,latch)
|
||||
b.go(0x2b30e8,0x2b3108);check(f'client select {pref}/{hyst}/{latch}',u.reg_read(UC_ARM64_REG_W1),1)
|
||||
u=b.u;b.go(0x2c6208,0x2c6214);check('initial run preference',struct.unpack('<I',u.mem_read(0x2d20e50,4))[0],1)
|
||||
# 构建剪口入口转向检验不宣称完整On执行。
|
||||
# The build cut entry redirection check does not claim full On execution.
|
||||
for start,target in [(0x369a90,0x369900),(0x6dcec0,0x6dce50)]:
|
||||
u=b.u;u.reg_write(UC_ARM64_REG_SP,0x701fff0);u.emu_start(start,0x4000000,count=1);check(f'off redirect {start:x}',u.reg_read(UC_ARM64_REG_PC),target)
|
||||
# 真实On/Off函数完整执行;lookup/stat/动画切换/发包为显式外围替身。
|
||||
# The real On/Off functions are executed in full; lookup/stat/animation switch/packet send are explicit peripheral stand-ins.
|
||||
for typ in [0,1]:
|
||||
for mode in [0,1,2,3,4,5,6,7,10,17,19]:
|
||||
for sta in [0,1,22272]:
|
||||
for entry in [0x369900,0x369a90,0x6dce50,0x6dcec0]:
|
||||
u=b.u;b.sta=sta;b.calls=[];u.mem_write(U,struct.pack('<I',typ));u.mem_write(U+0xc,struct.pack('<I',mode))
|
||||
u.mem_write(0x2d20ba1,b'\0');u.mem_write(0x2d20e50,struct.pack('<II',0,0));u.reg_write(UC_ARM64_REG_X1,U);u.reg_write(UC_ARM64_REG_W3,1);u.reg_write(UC_ARM64_REG_LR,0x7000100)
|
||||
b.go(entry,0x7000100);want=3 if typ==0 and mode==2 else mode
|
||||
actual=struct.unpack('<I',u.mem_read(U+0xc,4))[0]
|
||||
check(f'toggle entry={entry:x} type={typ} mode={mode} sta={sta}',actual,want)
|
||||
packets=[v for k,v in b.calls if k=='packet']
|
||||
wp=[0x49] if entry<0x600000 and typ==0 and mode==2 else []
|
||||
check(f'toggle packets entry={entry:x} type={typ} mode={mode} sta={sta}',packets,wp)
|
||||
print('ORIGINAL_SHA256',hashlib.sha256(orig).hexdigest());print('CANDIDATE_SHA256',hashlib.sha256(candidate).hexdigest())
|
||||
for label,actual,want in fails[:30]:print(f'FAIL {label}: 期望{want} → 真结果{actual}')
|
||||
print(f'RUN_RULE_LOCAL {total}项,失败{len(fails)};选择器/扣除窗/编码选择/偏好/入口转向;非完整动作/速度判据')
|
||||
sys.exit(bool(fails))
|
||||
@@ -0,0 +1,30 @@
|
||||
# disabled_bit_guard只测原位资格;人工局部内存fixture,不证明存活player控制锁的合法来源。
|
||||
# 执行原完整42 handler的输入合法性与分派;decoder/下游movement/致命日志为显式外围替身。
|
||||
# disabled_bit_guard only tests in-place eligibility; a hand-made local memory fixture, which does not prove the legitimate source of the control lock of a living player.
|
||||
# Executes the input validity checks and dispatch of the original full 42 handler; the decoder/downstream movement/fatal log are explicit peripheral stand-ins.
|
||||
import sys,struct
|
||||
from pathlib import Path
|
||||
from unicorn import *
|
||||
from unicorn.arm64_const import *
|
||||
b=Path(sys.argv[1]).read_bytes();u=Uc(UC_ARCH_ARM64,UC_MODE_ARM);u.mem_map(0,0x4000000);u.mem_write(0,b);u.mem_map(0x7000000,0x20000)
|
||||
G,U,D,C,P,PK,STOP=0x7001000,0x7002000,0x7003000,0x7004000,0x7005000,0x7006000,0x701f000
|
||||
ctx={}
|
||||
def hook(u,a,n,d):
|
||||
if a==STOP:ctx['returned']=True;u.emu_stop();return
|
||||
if a==0x4cd5f0:
|
||||
v=u.reg_read(UC_ARM64_REG_W0);u.mem_write(u.reg_read(UC_ARM64_REG_X1),struct.pack('<ff',1,0));u.mem_write(u.reg_read(UC_ARM64_REG_X2),struct.pack('<f',1));u.mem_write(u.reg_read(UC_ARM64_REG_X3),bytes([v>>15]));u.reg_write(UC_ARM64_REG_PC,u.reg_read(UC_ARM64_REG_LR))
|
||||
elif a==0x6cd670:ctx['move']=u.reg_read(UC_ARM64_REG_W2);u.reg_write(UC_ARM64_REG_W0,0);u.reg_write(UC_ARM64_REG_PC,u.reg_read(UC_ARM64_REG_LR))
|
||||
elif a==0xde1850:ctx['fatal']=True;u.emu_stop()
|
||||
u.hook_add(UC_HOOK_CODE,hook);bad=0;n=0
|
||||
for bit in [0,1]:
|
||||
for case in ['valid','badlen','dead0','dead17','disabled_bit_guard','far','nonplayer']:
|
||||
ctx.clear();u.mem_write(G,b'\0'*0x1000);u.mem_write(U,b'\0'*0x400);u.mem_write(D,b'\0'*0x200);u.mem_write(C,b'\0'*0x1000);u.mem_write(P,b'\0'*0x300)
|
||||
u.mem_write(U,struct.pack('<I',int(case=='nonplayer')));u.mem_write(U+12,struct.pack('<I',0 if case=='dead0'else 17 if case=='dead17'else 1));u.mem_write(U+0x10,struct.pack('<Q',D));u.mem_write(D+0xf0,struct.pack('<Q',C));u.mem_write(U+0x38,struct.pack('<Q',P));u.mem_write(P+2,struct.pack('<H',5826));u.mem_write(P+6,struct.pack('<H',4520));u.mem_write(U+0x126,bytes([int(case=='disabled_bit_guard')]));u.mem_write(G+0x170,struct.pack('<I',421));u.mem_write(PK,struct.pack('<BHHH',0x42,512|(31<<10)|(bit<<15),5926 if case=='far'else 5826,4520))
|
||||
for r,v in [(UC_ARM64_REG_X0,G),(UC_ARM64_REG_X1,U),(UC_ARM64_REG_X2,PK),(UC_ARM64_REG_X3,6 if case=='badlen'else 7),(UC_ARM64_REG_SP,0x701fff0),(UC_ARM64_REG_LR,STOP)]:u.reg_write(r,v)
|
||||
u.emu_start(0x6dc270,STOP+4,count=5000)
|
||||
wantmove=3 if case=='valid'else None;wantstatus=3 if case=='badlen'else 1 if case in ['dead0','dead17','disabled_bit_guard','far']else 0
|
||||
ok=(ctx.get('fatal',False) or ctx.get('returned',False)) and ctx.get('move')==wantmove and (ctx.get('fatal',False)==(case=='nonplayer')) and (case=='nonplayer'or u.reg_read(UC_ARM64_REG_W0)==wantstatus)
|
||||
n+=1
|
||||
if not ok:bad+=1;print('FAIL',bit,case,'期望move',wantmove,'→真',ctx,'status',u.reg_read(UC_ARM64_REG_W0))
|
||||
print(f'SERVER42_RULE {n}项,失败{bad};真实RET到STOP/原致命停机判据;bit0/1合法请求Run3,长度/死亡/禁用位/坐标/非player原检查;不含下游真实速度')
|
||||
sys.exit(bool(bad))
|
||||
@@ -0,0 +1,22 @@
|
||||
# 通用移动分派索引点的独立规则测试;入口已经过原null/type5门,终点为明确替身,不验证真实路径。
|
||||
# Independent rule test of the generic movement dispatch index point; the entry has already passed the original null/type5 gate, the end point is an explicit stand-in, and the real path is not verified.
|
||||
import sys,struct
|
||||
from pathlib import Path
|
||||
from unicorn import Uc,UC_ARCH_ARM64,UC_MODE_ARM,UC_HOOK_CODE
|
||||
from unicorn.arm64_const import *
|
||||
u=Uc(UC_ARCH_ARM64,UC_MODE_ARM);u.mem_map(0,0x4000000);u.mem_write(0,Path(sys.argv[1]).read_bytes());u.mem_map(0x7000000,0x10000);ctx={};bad=0;n=0
|
||||
G,UNIT,SP=0x7001000,0x7002000,0x700f000
|
||||
def hook(u,a,n,d):
|
||||
if a==0x6c6584:ctx['arrived']=True;u.emu_stop()
|
||||
u.hook_add(UC_HOOK_CODE,hook)
|
||||
for kind in [0,1,2,3,4,5,6,99]:
|
||||
for mode in [0,1,2,3,5,6,10,0xffffffff]:
|
||||
ctx.clear();u.mem_write(UNIT,struct.pack('<I',kind))
|
||||
for r,v in [(UC_ARM64_REG_X0,G),(UC_ARM64_REG_X19,UNIT),(UC_ARM64_REG_W8,kind),(UC_ARM64_REG_W2,mode),(UC_ARM64_REG_SP,SP),(UC_ARM64_REG_NZCV,0xa0000000)]:u.reg_write(r,v)
|
||||
u.emu_start(0x6c6580,0x4000000,count=100)
|
||||
want=3 if kind==0 and mode==2 else mode
|
||||
ok=ctx.get('arrived',False) and u.reg_read(UC_ARM64_REG_W2)==want and u.reg_read(UC_ARM64_REG_W9)==((want-2)&0xffffffff) and u.reg_read(UC_ARM64_REG_W8)==kind and u.reg_read(UC_ARM64_REG_X0)==G and u.reg_read(UC_ARM64_REG_X19)==UNIT and u.reg_read(UC_ARM64_REG_SP)==SP and u.reg_read(UC_ARM64_REG_NZCV)==0xa0000000
|
||||
n+=1
|
||||
if not ok:bad+=1;print('FAIL type',kind,'request',mode,'期望规范',want,'→真',u.reg_read(UC_ARM64_REG_W2),'arrived',ctx.get('arrived',False))
|
||||
print(f'SERVER_WALK_REQUEST {n}项,失败{bad};仅type0请求2规范为3并重算索引,其余请求/类型与W0/X19/W8/SP/NZCV保原;终点替身')
|
||||
sys.exit(bool(bad))
|
||||
@@ -0,0 +1,15 @@
|
||||
// 单测(crash.c 备用栈随线程释放):起 2000 个短命线程各调 crash_thread_init,期望堆不随线程数增长(每线程调 2 次,各 64 KiB;修前实测泄漏 250 MiB)
|
||||
// Unit test (crash.c alternate stack is freed with the thread): start 2000 short-lived threads each calling crash_thread_init, and expect the heap not to grow with the thread count (2 calls per thread, 64 KiB each; before the fix a 250 MiB leak was measured)
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <malloc/malloc.h>
|
||||
void crash_thread_init(void);
|
||||
static void *body(void *a) { crash_thread_init(); crash_thread_init(); return a; }
|
||||
static size_t inuse(void) { malloc_statistics_t st; malloc_zone_statistics(NULL, &st); return st.size_in_use; }
|
||||
int main(void) {
|
||||
size_t before = inuse();
|
||||
for (int i = 0; i < 2000; i++) { pthread_t t; pthread_create(&t, 0, body, 0); pthread_join(t, 0); }
|
||||
double grew = (inuse() - (double)before) / 1048576.0;
|
||||
printf("2000 个短命线程后堆增长 %.2f MiB(期望 < 1;修前实测 250)%s\n", grew, grew < 1 ? "✓" : "✗");
|
||||
return !(grew < 1);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
#include <stdint.h>
|
||||
typedef struct module_t module_t;
|
||||
module_t *module_of(const void *p) { (void)p; return 0; }
|
||||
@@ -0,0 +1,60 @@
|
||||
// hle_audio.c 单测(静音接收端):3 块各 100 ms 缓冲 → 按序在约 100/200/300 ms 释放、每次释放触发事件。
|
||||
// 期望值由采样率与块长直接算出:4800 帧 / 48 kHz = 100 ms。
|
||||
// hle_audio.c unit test (silent sink): 3 buffers of 100 ms each -> released in order at about 100/200/300 ms, each release triggering the event.
|
||||
// Expected values are computed directly from the sample rate and block length: 4800 frames / 48 kHz = 100 ms.
|
||||
#include "../hle_audio.c"
|
||||
#include <time.h>
|
||||
uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec; }
|
||||
static struct { const void *k; void *v; } om[8];
|
||||
void *objmap_get(const void *k) { for (int i = 0; i < 8; i++) if (om[i].k == k) return om[i].v; return NULL; }
|
||||
void objmap_put(const void *k, void *v) { for (int i = 0; i < 8; i++) if (!om[i].k) { om[i].k = k; om[i].v = v; return; } }
|
||||
void *objmap_del(const void *k) { for (int i = 0; i < 8; i++) if (om[i].k == k) { om[i].k = 0; return om[i].v; } return NULL; }
|
||||
static _Atomic int g_sig;
|
||||
void hle_signal_system_event(void *g) { (void)g; atomic_fetch_add_explicit(&g_sig, 1, memory_order_seq_cst); }
|
||||
void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } // 真实现要客体线程 + SDK 内核事件;单测只数触发次数 | the real implementation needs a guest thread + SDK kernel event; the unit test only counts triggers
|
||||
int main(void) {
|
||||
char out[64], ev[64]; uint8_t prm[16]; gbuf b[3]; static int16_t pcm[3][4800 * 2];
|
||||
h_au_InitParam(prm);
|
||||
if (h_au_Open(out, ev, NULL, prm)) return 1;
|
||||
if (h_au_Ch(out) != 2 || h_au_Rate(out) != 48000 || h_au_State(out) != STATE_STOPPED) { puts("FAIL 参数"); return 1; }
|
||||
for (int i = 0; i < 3; i++) { h_au_SetBuf(&b[i], pcm[i], sizeof pcm[i], sizeof pcm[i]); if (!h_au_Append(out, &b[i])) return 1; }
|
||||
if (h_au_Released(out)) { puts("FAIL 未开始就有释放"); return 1; }
|
||||
uint64_t t0 = now_ns(); h_au_Start(out);
|
||||
int got = 0, fail = 0;
|
||||
while (got < 3 && now_ns() - t0 < 10000000000ull) {
|
||||
gbuf *r = h_au_Released(out);
|
||||
if (!r) { usleep(1000); continue; }
|
||||
int ok = r == &b[got];
|
||||
printf("释放 #%d:期望 块%d 按序 → 真结果 块%ld %s\n", got, got, (long)(r - b), ok ? "✓" : "✗");
|
||||
fail |= !ok; got++;
|
||||
}
|
||||
h_au_Close(out);
|
||||
int sig1 = atomic_load_explicit(&g_sig, memory_order_acquire);
|
||||
printf("释放 %d/3,事件触发 %d 次(期望 3)\n", got, sig1);
|
||||
if (fail || got != 3 || sig1 != 3) return 1;
|
||||
|
||||
// 场景 2:真出声端(PCM 全 0,听不到)播 6 块各 100 ms,第 150 ms 暂停(切后台 / 来电)、第 350 ms 恢复。
|
||||
// 期望:暂停期间由静音接收端接手按实时消耗,6 块按序全部释放、事件 6 次;总时长 ≈ 600 ms(实时,不因暂停停住也不加速)。
|
||||
// Scenario 2: the real audio output sink (PCM all 0, inaudible) plays 6 blocks of 100 ms each, pausing at 150 ms (app to background / incoming call) and resuming at 350 ms.
|
||||
// Expected: during the pause the silent sink takes over and consumes in real time, all 6 blocks are released in order with 6 events; total duration ~ 600 ms (real time, neither stalled by the pause nor sped up).
|
||||
setenv("DM_AUDIO", "1", 1);
|
||||
char out2[64]; gbuf b2[6]; static int16_t pcm2[6][4800 * 2]; g_sig = 0;
|
||||
if (h_au_Open(out2, ev, NULL, prm)) return 1;
|
||||
for (int i = 0; i < 6; i++) { h_au_SetBuf(&b2[i], pcm2[i], sizeof pcm2[i], sizeof pcm2[i]); h_au_Append(out2, &b2[i]); }
|
||||
t0 = now_ns(); h_au_Start(out2);
|
||||
int got2 = 0, order_ok = 1, susp = 0, resumed = 0;
|
||||
while (got2 < 6 && now_ns() - t0 < 10000000000ull) {
|
||||
uint64_t ms = (now_ns() - t0) / 1000000;
|
||||
if (!susp && ms >= 150) { dm_audio_suspend(1); susp = 1; }
|
||||
if (susp && !resumed && ms >= 350) { dm_audio_suspend(0); resumed = 1; }
|
||||
gbuf *r = h_au_Released(out2);
|
||||
if (!r) { usleep(1000); continue; }
|
||||
order_ok &= r == &b2[got2]; got2++;
|
||||
}
|
||||
double total = (now_ns() - t0) / 1e6;
|
||||
h_au_Close(out2);
|
||||
int sig2 = atomic_load_explicit(&g_sig, memory_order_acquire);
|
||||
int ok2 = got2 == 6 && order_ok && sig2 == 6 && total > 520;
|
||||
printf("暂停 / 恢复:释放 %d/6 按序=%d 事件 %d(期望 6)总时长下限 520 ms,真结果 %.0f ms %s\n", got2, order_ok, sig2, total, ok2 ? "✓" : "✗");
|
||||
return !ok2;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// hle_audio.c 无锁队列压测:生产 / 出声 / 收回三线程并发 10 万块,字节流与收回顺序按序号逐一核对,事件不丢。
|
||||
// hle_audio.c lock-free queue stress test: three threads producing / playing / reclaiming 100 thousand blocks concurrently, the byte stream and reclaim order checked one by one by sequence number, no event lost.
|
||||
#include "../hle_audio.c"
|
||||
#include <sched.h>
|
||||
#include <time.h>
|
||||
|
||||
enum { NBUF = 100000, MAX_SIZE = 37 };
|
||||
|
||||
uint64_t now_ns(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return (uint64_t)t.tv_sec * 1000000000ull + t.tv_nsec; }
|
||||
static struct { const void *k; void *v; } om[8];
|
||||
void *objmap_get(const void *k) { for (int i = 0; i < 8; i++) if (om[i].k == k) return om[i].v; return NULL; }
|
||||
void objmap_put(const void *k, void *v) { for (int i = 0; i < 8; i++) if (!om[i].k) { om[i].k = k; om[i].v = v; return; } }
|
||||
void *objmap_del(const void *k) { for (int i = 0; i < 8; i++) if (om[i].k == k) { om[i].k = 0; return om[i].v; } return NULL; }
|
||||
|
||||
static _Atomic int g_sig, g_after_last;
|
||||
static _Atomic int g_last_pull;
|
||||
void hle_signal_system_event(void *g) {
|
||||
(void)g;
|
||||
atomic_fetch_add_explicit(&g_sig, 1, memory_order_seq_cst);
|
||||
if (atomic_load_explicit(&g_last_pull, memory_order_seq_cst)) atomic_store(&g_after_last, 1);
|
||||
}
|
||||
void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; }
|
||||
|
||||
typedef struct {
|
||||
void *out;
|
||||
aout *a;
|
||||
gbuf *bufs;
|
||||
uint8_t (*data)[MAX_SIZE];
|
||||
uint8_t *scratch;
|
||||
uint32_t *sizes;
|
||||
uint64_t total_bytes;
|
||||
_Atomic int failed;
|
||||
_Atomic int released;
|
||||
} test_ctx;
|
||||
|
||||
static uint32_t next_random(uint32_t *state) {
|
||||
*state = *state * 1664525u + 1013904223u;
|
||||
return *state;
|
||||
}
|
||||
|
||||
static uint64_t available_bytes(aout *a) {
|
||||
uint32_t qh = atomic_load_explicit(&a->q_head, memory_order_relaxed);
|
||||
uint32_t qt = atomic_load_explicit(&a->q_tail, memory_order_acquire);
|
||||
if (qh == qt) return 0;
|
||||
uint64_t bytes = a->q[qh & (QMAX - 1)]->size - a->pos;
|
||||
for (uint32_t i = qh + 1; i != qt; i++) bytes += a->q[i & (QMAX - 1)]->size;
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static void *producer(void *p) {
|
||||
test_ctx *t = p;
|
||||
for (uint32_t i = 0; i < NBUF; i++) {
|
||||
t->bufs[i].ptr = t->data[i]; t->bufs[i].cap = MAX_SIZE; t->bufs[i].size = t->sizes[i];
|
||||
// 真实缓冲池:在途(已追加未收回)不超过 QMAX,收回后才能再追加
|
||||
// Real buffer pool: buffers in flight (appended, not yet reclaimed) do not exceed QMAX, and more can be appended only after reclaiming
|
||||
while (i - (uint32_t)atomic_load_explicit(&t->released, memory_order_acquire) >= QMAX) sched_yield();
|
||||
while (!h_au_Append(t->out, &t->bufs[i])) sched_yield();
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void *consumer(void *p) {
|
||||
test_ctx *t = p;
|
||||
uint32_t state = 7;
|
||||
uint64_t want = 0, done = 0;
|
||||
while (done < t->total_bytes) {
|
||||
uint64_t avail = available_bytes(t->a);
|
||||
if (!avail) {
|
||||
if (atomic_load_explicit(&t->released, memory_order_acquire) == NBUF) break;
|
||||
sched_yield();
|
||||
continue;
|
||||
}
|
||||
uint64_t n = 1 + next_random(&state) % 512;
|
||||
if (n > avail) n = avail;
|
||||
if (done + n == t->total_bytes) atomic_store(&g_last_pull, 1);
|
||||
pull(t->a, t->scratch, n);
|
||||
for (uint64_t i = 0; i < n; i++) {
|
||||
if (t->scratch[i] != (uint8_t)(want++)) atomic_store(&t->failed, 1);
|
||||
}
|
||||
done += n;
|
||||
if (atomic_load(&t->released) == NBUF && !available_bytes(t->a)) break;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void *release_reader(void *p) {
|
||||
test_ctx *t = p;
|
||||
for (int i = 0; i < NBUF; ) {
|
||||
gbuf *b = h_au_Released(t->out);
|
||||
if (!b) { sched_yield(); continue; }
|
||||
if (b != &t->bufs[i]) atomic_store(&t->failed, 1);
|
||||
i++;
|
||||
atomic_store_explicit(&t->released, i, memory_order_release);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
char out[64], ev[64]; uint8_t prm[16];
|
||||
test_ctx t = {0};
|
||||
t.bufs = calloc(NBUF, sizeof *t.bufs); t.data = calloc(NBUF, sizeof *t.data); t.sizes = calloc(NBUF, sizeof *t.sizes); t.scratch = malloc(512);
|
||||
if (!t.bufs || !t.data || !t.sizes || !t.scratch) return 2;
|
||||
h_au_InitParam(prm);
|
||||
uint32_t state = 1; uint64_t cursor = 0;
|
||||
for (uint32_t i = 0; i < NBUF; i++) {
|
||||
t.sizes[i] = 1 + next_random(&state) % MAX_SIZE;
|
||||
for (uint32_t j = 0; j < t.sizes[i]; j++) t.data[i][j] = (uint8_t)(cursor++);
|
||||
t.total_bytes += t.sizes[i];
|
||||
}
|
||||
if (h_au_Open(out, ev, NULL, prm)) return 3;
|
||||
t.out = out; t.a = ao(out);
|
||||
atomic_store(&t.a->state, STATE_STARTED);
|
||||
pthread_t p, c, r;
|
||||
pthread_create(&p, NULL, producer, &t);
|
||||
pthread_create(&c, NULL, consumer, &t);
|
||||
pthread_create(&r, NULL, release_reader, &t);
|
||||
pthread_join(p, NULL); pthread_join(c, NULL); pthread_join(r, NULL);
|
||||
atomic_store(&t.a->state, STATE_STOPPED);
|
||||
h_au_Close(out);
|
||||
int sig = atomic_load(&g_sig), after = atomic_load(&g_after_last), released = atomic_load(&t.released), failed = atomic_load(&t.failed);
|
||||
printf("SPSC:追加/释放 %d/%d,事件 %d,最后释放后触发=%d,失败=%d\n", NBUF, released, sig, after, failed);
|
||||
free(t.scratch); free(t.sizes); free(t.data); free(t.bufs);
|
||||
return released != NBUF || failed || sig < 1 || !after;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// iCloud 同步核心单测(秒级):dm_cloudsync.c。两个本地目录当两台设备、一个本地目录当云端;期望都是按「后写覆盖先写」手推的,不跑被测实现得出。
|
||||
// iCloud sync core unit test (takes seconds): dm_cloudsync.c. Two local directories act as two devices and one local directory as the cloud; all expectations are derived by hand from "later write overwrites earlier write", not obtained by running the implementation under test.
|
||||
#include <dirent.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/time.h>
|
||||
#include <unistd.h>
|
||||
int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit));
|
||||
int dm_cloud_conflict_take(void);
|
||||
#if __has_include("../stash_seed.h") // 公开仓库不带这份预置(它是游戏生成的一份存档的字节):不在时跳过用到它的 ⑱ ⑲ 两组 | the public repository does not ship this seed (it is the bytes of a save the game generated): when it is absent, the two groups that use it, 18 and 19, are skipped
|
||||
#include "../stash_seed.h"
|
||||
#define T_HAVE_STASH_SEED 1
|
||||
#endif
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
static char R[512];
|
||||
static void path(char *o, const char *a, const char *b) { snprintf(o, 1024, "%s/%s/%s", R, a, b); }
|
||||
static void put(const char *dev, const char *rel, const char *txt, long sec) { // 写一个文件并把修改时间定成 sec 秒 | write a file and set its modification time to sec seconds
|
||||
char p[1024]; path(p, dev, rel); char d[1024]; strcpy(d, p); for (char *s = d + strlen(R) + 1; (s = strchr(s, '/')); s++) { *s = 0; mkdir(d, 0755); *s = '/'; }
|
||||
FILE *f = fopen(p, "w"); fputs(txt, f); fclose(f); struct timeval tv[2] = { { sec, 0 }, { sec, 0 } }; utimes(p, tv);
|
||||
}
|
||||
static const char *get(const char *dev, const char *rel) { static char b[256]; char p[1024]; path(p, dev, rel); FILE *f = fopen(p, "r"); if (!f) return NULL; size_t n = fread(b, 1, 255, f); b[n] = 0; fclose(f); return b; }
|
||||
static long mtime(const char *dev, const char *rel) { char p[1024]; struct stat st; path(p, dev, rel); return stat(p, &st) ? -1 : st.st_mtimespec.tv_sec; }
|
||||
static int dsync(const char *dev, int down, uint64_t now) { char s[1024], c[1024], b[1024], t[1024]; path(s, dev, "save"); snprintf(c, sizeof c, "%s/cloud", R); path(b, dev, "bak"); path(t, dev, "state"); return dm_cloud_sync(s, c, b, t, down, now, NULL); }
|
||||
static int count_bak(const char *dev, const char *pre) { char d[1024]; path(d, dev, "bak"); DIR *dp = opendir(d); struct dirent *e; int n = 0; while (dp && (e = readdir(dp))) n += !strncmp(e->d_name, pre, strlen(pre)); if (dp) closedir(dp); return n; }
|
||||
static int no_skip(const char *u) { return strcmp(u, "Alice"); }
|
||||
// 共享仓库档:一页物品(items 件,只写页头与件数)+ 一段编年史(chron 字节);侧文件:n 件。只造结构,同步那边只看结构(dm_cloudsync.c rich_of)
|
||||
// Shared stash file: one page of items (items pieces, only the page header and item count are written) + one chronicle section (chron bytes); side file: n pieces. Only the structure is built, as the sync side only looks at structure (dm_cloudsync.c rich_of)
|
||||
static void put_bin(const char *dev, const char *rel, const uint8_t *d, size_t n, long sec) {
|
||||
char p[1024]; path(p, dev, rel); char dd[1024]; strcpy(dd, p); for (char *x = dd + strlen(R) + 1; (x = strchr(x, '/')); x++) { *x = 0; mkdir(dd, 0755); *x = '/'; }
|
||||
FILE *f = fopen(p, "wb"); fwrite(d, 1, n, f); fclose(f); struct timeval tv[2] = { { sec, 0 }, { sec, 0 } }; utimes(p, tv);
|
||||
}
|
||||
static void put_d2i(const char *dev, int items, int chron, long sec) {
|
||||
static uint8_t b[8192]; memset(b, 0, sizeof b); uint32_t l1 = 68, l2 = (uint32_t)chron;
|
||||
memcpy(b, "\x55\xaa\x55\xaa", 4); memcpy(b + 16, &l1, 4); memcpy(b + 64, "JM", 2); b[66] = (uint8_t)items;
|
||||
memcpy(b + 68, "\x55\xaa\x55\xaa", 4); memcpy(b + 68 + 16, &l2, 4); b[68 + 64] = 0xc0;
|
||||
put_bin(dev, "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i", b, 68 + l2, sec);
|
||||
}
|
||||
static void put_vault(const char *dev, int n, long sec) { uint8_t b[8] = { 'S', 'W', 'V', 'T', 1, 0, (uint8_t)n, 0 }; put_bin(dev, "save/ModernSharedStashSoftCoreV2.swvault", b, 8, sec); }
|
||||
static int d2i_items(const char *dev, const char *rel) { char p[1024]; path(p, dev, rel); FILE *f = fopen(p, "rb"); if (!f) return -1; uint8_t b[70]; size_t n = fread(b, 1, 70, f); fclose(f); return n >= 67 ? b[66] : -1; }
|
||||
|
||||
int main(void) {
|
||||
snprintf(R, sizeof R, "%s/t_cloudsync.%d", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp", getpid()); mkdir(R, 0755);
|
||||
char c[1024]; snprintf(c, sizeof c, "%s/cloud", R); mkdir(c, 0755);
|
||||
// ① A 有角色 Alice(时刻 1000 秒)、共享仓库、Settings;B 空 → A 上传,B 启动拿到 Alice 与共享仓库,Settings 不同步,修改时间照 A 的
|
||||
// (1) A has character Alice (timestamp 1000 seconds), the shared stash and Settings; B is empty -> A uploads, B gets Alice and the shared stash at startup, Settings is not synced, and modification times follow A's
|
||||
put("A", "save/Alice/Alice.d2s", "a1", 1000); put("A", "save/Alice/Alice.key", "k", 900);
|
||||
put("A", "save/SharedStashSoftCoreV2.d2i", "s1", 1100); put("A", "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i", "m1", 1100); put("A", "save/Settings/Settings.json", "{}", 1100);
|
||||
put("B", "save/Settings/Settings.json", "{b}", 1200);
|
||||
CHECK(dsync("A", 0, 0) == 2, "① A 上传应为 2 个单位(Alice、_stash)");
|
||||
CHECK(dsync("B", 1, 0) == 2, "① B 下载应为 2 个单位");
|
||||
CHECK(get("B", "save/Alice/Alice.d2s") && !strcmp(get("B", "save/Alice/Alice.d2s"), "a1"), "① B 的 Alice 应是 a1");
|
||||
CHECK(mtime("B", "save/Alice/Alice.d2s") == 1000, "① 修改时间应还原成 1000,实为 %ld", mtime("B", "save/Alice/Alice.d2s"));
|
||||
CHECK(get("B", "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i") && !strcmp(get("B", "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i"), "m1"), "① B 的共享仓库应是 m1");
|
||||
CHECK(!strcmp(get("B", "save/Settings/Settings.json"), "{b}"), "① B 的 Settings 不该被动");
|
||||
CHECK(dsync("A", 1, 0) == 0 && dsync("B", 1, 0) == 0, "① 再同步一次两边都应无动作");
|
||||
// ② 只有 B 改(2000)→ B 运行中上传;A 启动拿到,A 原来那份进备份
|
||||
// (2) Only B changed (2000) -> B uploads while running; A gets it at startup, and A's former copy goes to backup
|
||||
put("B", "save/Alice/Alice.d2s", "b2", 2000);
|
||||
CHECK(dsync("B", 0, 0) == 1, "② B 应上传 1 个");
|
||||
CHECK(dsync("A", 0, 0) == 0 && !strcmp(get("A", "save/Alice/Alice.d2s"), "a1"), "② A 运行中不该改本地");
|
||||
CHECK(dsync("A", 1, 0) == 1 && !strcmp(get("A", "save/Alice/Alice.d2s"), "b2"), "② A 启动后应是 b2");
|
||||
CHECK(get("A", "bak/Alice-1000000/Alice/Alice.d2s") && !strcmp(get("A", "bak/Alice-1000000/Alice/Alice.d2s"), "a1"), "② A 被覆盖的 a1 应在备份 Alice-1000000");
|
||||
// ③ 两边都改,B 后写(A 3000 先传,B 3500)→ B 运行中照样上传(后写赢),云端原来的 a3 进 B 的备份;A 启动拿到 b3
|
||||
// (3) Both sides changed, B wrote later (A's 3000 uploaded first, B 3500) -> B still uploads while running (last write wins), the cloud's former a3 goes to B's backup; A gets b3 at startup
|
||||
put("A", "save/Alice/Alice.d2s", "a3", 3000); put("B", "save/Alice/Alice.d2s", "b3", 3500);
|
||||
CHECK(dsync("A", 0, 0) == 1, "③ A 先上传");
|
||||
CHECK(dsync("B", 0, 0) == 1, "③ B 后写也上传");
|
||||
CHECK(get("B", "bak/Alice-3000000/Alice/Alice.d2s") && !strcmp(get("B", "bak/Alice-3000000/Alice/Alice.d2s"), "a3"), "③ 被覆盖的云端 a3 应在 B 的备份");
|
||||
CHECK(dsync("A", 1, 0) == 1 && !strcmp(get("A", "save/Alice/Alice.d2s"), "b3"), "③ A 启动后应是 b3");
|
||||
// ④ 两边都改,A 后写(A 5000 已传;B 4000 没传就重启)→ B 启动拿 A 的 a4,b4 进备份 Alice-4000000
|
||||
// (4) Both sides changed, A wrote later (A's 5000 uploaded; B's 4000 not uploaded before restarting) -> B gets A's a4 at startup, b4 goes to backup Alice-4000000
|
||||
put("A", "save/Alice/Alice.d2s", "a4", 5000); CHECK(dsync("A", 0, 0) == 1, "④ A 上传");
|
||||
put("B", "save/Alice/Alice.d2s", "b4", 4000);
|
||||
CHECK(dsync("B", 1, 0) == 1 && !strcmp(get("B", "save/Alice/Alice.d2s"), "a4"), "④ B 启动后应是 a4(云端 5000 > 本机 4000)");
|
||||
CHECK(get("B", "bak/Alice-4000000/Alice/Alice.d2s") && !strcmp(get("B", "bak/Alice-4000000/Alice/Alice.d2s"), "b4"), "④ B 被覆盖的 b4 应在备份");
|
||||
// ⑤ 云端的包还没下载好(ready 返回 0)→ 跳过,本地不动
|
||||
// (5) The cloud package has not finished downloading (ready returns 0) -> skip, local files untouched
|
||||
put("A", "save/Alice/Alice.d2s", "a5", 6000); CHECK(dsync("A", 0, 0) == 1, "⑤ A 上传");
|
||||
{ char s[1024], b[1024], t[1024]; path(s, "B", "save"); path(b, "B", "bak"); path(t, "B", "state"); CHECK(dm_cloud_sync(s, c, b, t, 1, 0, no_skip) == 0 && !strcmp(get("B", "save/Alice/Alice.d2s"), "a4"), "⑤ 没下载好时 B 应不动"); }
|
||||
CHECK(dsync("B", 1, 0) == 1 && !strcmp(get("B", "save/Alice/Alice.d2s"), "a5"), "⑤ 下载好后 B 应是 a5");
|
||||
// ⑥ A 删 Alice → 云端删除标记;B 启动也删,B 那份进备份;B 的备份只留 3 份(此前有 1000000 不在 B、3000000、4000000,再加 6000000 = 3 份)
|
||||
// (6) A deletes Alice -> deletion marker in the cloud; B also deletes at startup and B's copy goes to backup; B's backup keeps only 3 copies (before this there were 1000000 not on B, 3000000, 4000000, plus 6000000 = 3 copies)
|
||||
{ char p[1024]; path(p, "A", "save/Alice/Alice.d2s"); unlink(p); path(p, "A", "save/Alice/Alice.key"); unlink(p); path(p, "A", "save/Alice"); rmdir(p); }
|
||||
CHECK(dsync("A", 0, 7000000) == 1, "⑥ A 应写删除标记");
|
||||
CHECK(dsync("B", 1, 0) == 1 && !get("B", "save/Alice/Alice.d2s"), "⑥ B 启动后 Alice 应被删");
|
||||
CHECK(get("B", "bak/Alice-6000000/Alice/Alice.d2s") && !strcmp(get("B", "bak/Alice-6000000/Alice/Alice.d2s"), "a5"), "⑥ B 被删的 a5 应在备份");
|
||||
CHECK(count_bak("B", "Alice-") == 3, "⑥ B 的 Alice 备份应留 3 份,实为 %d", count_bak("B", "Alice-"));
|
||||
for (long t = 8; t <= 9; t++) { char v[8]; snprintf(v, sizeof v, "x%ld", t); put("B", "save/Bob/Bob.d2s", v, t * 1000); } // 无关角色不受影响 | unrelated characters are not affected
|
||||
CHECK(dsync("B", 1, 0) == 1, "⑥ B 的新角色 Bob 上传");
|
||||
// ⑦ 删除之后 A 又建了同名角色(9500)→ 上传(复活);B 启动拿到
|
||||
// (7) After the deletion A created a character with the same name again (9500) -> upload (revive); B gets it at startup
|
||||
put("A", "save/Alice/Alice.d2s", "a7", 9500);
|
||||
CHECK(dsync("A", 1, 0) == 2 && !strcmp(get("A", "save/Bob/Bob.d2s"), "x9"), "⑦ A:Alice 上传 + Bob 下载");
|
||||
CHECK(dsync("B", 1, 0) == 1 && get("B", "save/Alice/Alice.d2s") && !strcmp(get("B", "save/Alice/Alice.d2s"), "a7"), "⑦ B 启动后应有新建的 Alice a7");
|
||||
// ⑧ 共享仓库:B 改(10000)→ A 启动拿到
|
||||
// (8) Shared stash: B changes it (10000) -> A gets it at startup
|
||||
put("B", "save/SharedStashSoftCoreV2.d2i", "s8", 10000);
|
||||
CHECK(dsync("B", 0, 0) == 1 && dsync("A", 1, 0) == 1 && !strcmp(get("A", "save/SharedStashSoftCoreV2.d2i"), "s8"), "⑧ A 的共享仓库应是 s8");
|
||||
CHECK(!strcmp(get("A", "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i"), "m1"), "⑧ 共享仓库的另一个文件应保留 m1");
|
||||
// ⑨ 存档目录被游戏以外的原因清空(状态文件还在)→ 启动时不算删除,从云端全拿回来,云端不出现删除标记
|
||||
// (9) The save directory was emptied by something other than the game (the state file is still there) -> at startup it does not count as a deletion, everything is fetched back from the cloud, and no deletion marker appears in the cloud
|
||||
{ char p[1024]; path(p, "A", "save"); char cmd[1200]; snprintf(cmd, sizeof cmd, "rm -rf '%s'", p); system(cmd); mkdir(p, 0755); }
|
||||
CHECK(dsync("A", 1, 0) == 3, "⑨ A 启动应下载 3 个(Alice、Bob、_stash)");
|
||||
CHECK(get("A", "save/Alice/Alice.d2s") && !strcmp(get("A", "save/Alice/Alice.d2s"), "a7") && get("A", "save/Bob/Bob.d2s") && !strcmp(get("A", "save/SharedStashSoftCoreV2.d2i"), "s8"), "⑨ A 应拿回 Alice a7、Bob、共享仓库 s8");
|
||||
CHECK(dsync("B", 1, 0) == 0 && get("B", "save/Alice/Alice.d2s"), "⑨ B 不受影响(没有删除标记传过来)");
|
||||
// ⑩ 备份目录写不进(这里用同名普通文件把它堵住)→ 覆盖和删除都不动本地;解开后照常进行(原先备份写失败仍照样覆盖 / 删)
|
||||
// (10) The backup directory cannot be written (here it is blocked with a regular file of the same name) -> neither overwrite nor delete touches local files; after unblocking it proceeds as usual (previously it still overwrote / deleted when the backup write failed)
|
||||
{ char s[1024], c2[1024], b[1024], t2[1024], bf[1024]; snprintf(c2, sizeof c2, "%s/cloud2", R); mkdir(c2, 0755);
|
||||
#define SY(dev, down, now) (path(s, dev, "save"), path(b, dev, "bak"), path(t2, dev, "state"), dm_cloud_sync(s, c2, b, t2, down, now, NULL))
|
||||
put("F", "save/Settings/Settings.json", "{}", 1); // F 是一台已有存档目录的设备 | F is a device that already has a save directory
|
||||
put("E", "save/Eve/Eve.d2s", "e1", 1000); CHECK(SY("E", 0, 0) == 1 && SY("F", 1, 0) == 1 && get("F", "save/Eve/Eve.d2s") && !strcmp(get("F", "save/Eve/Eve.d2s"), "e1"), "⑩ 准备:F 拿到 Eve e1");
|
||||
put("E", "save/Eve/Eve.d2s", "e2", 2000); CHECK(SY("E", 0, 0) == 1, "⑩ E 上传 e2");
|
||||
path(bf, "F", "bak"); FILE *f = fopen(bf, "w"); fclose(f); // F 的备份目录位置是个普通文件:建不了目录 | F's backup directory location is a regular file: the directory cannot be created
|
||||
CHECK(SY("F", 1, 0) == 0 && get("F", "save/Eve/Eve.d2s") && !strcmp(get("F", "save/Eve/Eve.d2s"), "e1"), "⑩ 备份写不进时 F 不应覆盖,仍是 e1");
|
||||
unlink(bf);
|
||||
CHECK(SY("F", 1, 0) == 1 && get("F", "save/Eve/Eve.d2s") && !strcmp(get("F", "save/Eve/Eve.d2s"), "e2") && get("F", "bak/Eve-1000000/Eve/Eve.d2s") && !strcmp(get("F", "bak/Eve-1000000/Eve/Eve.d2s"), "e1"), "⑩ 解开后 F 换成 e2,e1 整份在备份里");
|
||||
{ char p2[1024]; path(p2, "E", "save/Eve/Eve.d2s"); unlink(p2); path(p2, "E", "save/Eve"); rmdir(p2); }
|
||||
CHECK(SY("E", 0, 3000000) == 1, "⑩ E 运行中删了 Eve,写删除标记");
|
||||
char bk[1100]; snprintf(bk, sizeof bk, "%s.keep", bf); rename(bf, bk); f = fopen(bf, "w"); fclose(f); // 已有的备份目录先挪开,再用普通文件堵住 | move the existing backup directory aside first, then block it with a regular file
|
||||
CHECK(SY("F", 1, 0) == 0 && get("F", "save/Eve/Eve.d2s"), "⑩ 备份写不进时 F 不应删 Eve");
|
||||
unlink(bf); rename(bk, bf);
|
||||
CHECK(SY("F", 1, 0) == 1 && !get("F", "save/Eve/Eve.d2s") && get("F", "bak/Eve-2000000/Eve/Eve.d2s"), "⑩ 解开后 F 删 Eve,e2 整份在备份里");
|
||||
#undef SY
|
||||
}
|
||||
// ⑪–⑮ 编年史被整份换空:新设备首次同步以云端为准;共享仓库不许被「明显更少」的一份覆盖(另一个云端目录 cloud3,设备 G / H)
|
||||
// (11)-(15) Chronicle replaced wholesale by an empty one: a new device's first sync takes the cloud as authoritative; the shared stash must not be overwritten by a copy with "clearly less" (another cloud directory cloud3, devices G / H)
|
||||
{ char s3[1024], c3[1024], b3[1024], t3[1024]; snprintf(c3, sizeof c3, "%s/cloud3", R); mkdir(c3, 0755);
|
||||
#define S3(dev, down) (path(s3, dev, "save"), path(b3, dev, "bak"), path(t3, dev, "state"), dm_cloud_sync(s3, c3, b3, t3, down, 0, NULL))
|
||||
#define D2I "save/ModernSharedStashSoftCoreV2/ModernSharedStashSoftCoreV2.d2i"
|
||||
put_d2i("G", 5, 300, 1000); put_vault("G", 3, 1000);
|
||||
CHECK(S3("G", 0) == 1, "⑫ 云端为空:G 首次同步上传共享仓库");
|
||||
dm_cloud_conflict_take();
|
||||
put_d2i("H", 0, 148, 5000); // H 新装:游戏刚建的空共享仓库,时刻比云端新 | H freshly installed: the empty shared stash the game just created, with a timestamp newer than the cloud's
|
||||
CHECK(S3("H", 0) == 0 && d2i_items("H", D2I) == 0, "⑪ 新设备运行中首次同步:不传不改(不能拿空仓库盖云端)");
|
||||
CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 5 && get("H", "save/ModernSharedStashSoftCoreV2.swvault"), "⑪ 新设备启动首次同步:以云端为准,拿到 5 件与编年史仓库");
|
||||
CHECK(count_bak("H", "_stash-") == 1, "⑪ 新设备本来那份空仓库进备份");
|
||||
CHECK(!dm_cloud_conflict_take(), "⑪ 正常首次同步不算冲突");
|
||||
put_d2i("G", 6, 400, 6000); CHECK(S3("G", 0) == 1, "⑭ G 编年史变长(400)照常上传");
|
||||
CHECK(S3("H", 1) == 1 && d2i_items("H", D2I) == 6, "⑭ H 启动拿到 G 的新版");
|
||||
put_d2i("H", 0, 148, 7000); // H 上的共享仓库不知为何变空(编年史 148、0 件),时刻更新 | the shared stash on H somehow became empty (chronicle 148, 0 items), with a newer timestamp
|
||||
CHECK(S3("H", 0) == 0, "⑬ H 运行中要上传变空的那份:拦下");
|
||||
CHECK(dm_cloud_conflict_take() == 1, "⑬ 拦下记冲突(进局弹提示)");
|
||||
CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑬ 云端没被盖:G 仍是 6 件");
|
||||
put_d2i("H", 7, 500, 7500); CHECK(S3("H", 0) == 1, "⑮ H 正常玩:编年史 500 上传");
|
||||
put_d2i("G", 6, 450, 7600); // G 没同步到 H 的 500 就自己写了 450(两边都改,G 后写) | G wrote 450 itself without having synced H's 500 (both sides changed, G wrote later)
|
||||
CHECK(S3("G", 0) == 0, "⑮ G 运行中要拿编年史 450 盖云端的 500:拦下");
|
||||
CHECK(S3("G", 1) == 0 && d2i_items("G", D2I) == 6, "⑮ G 启动:云端 500 比本机 450 时刻早但编年史长——按后写赢会上传,被拦;本机不动");
|
||||
CHECK(dm_cloud_conflict_take() == 1, "⑮ 记冲突");
|
||||
{ char p3[1024]; path(p3, "H", "save/ModernSharedStashSoftCoreV2.swvault"); unlink(p3); } put_d2i("H", 7, 500, 8000);
|
||||
CHECK(S3("H", 0) == 0 && dm_cloud_conflict_take() == 1, "⑬ 编年史仓库侧文件没了(云端有 3 件):拦下");
|
||||
put_vault("H", 0, 8100); put_d2i("H", 0, 500, 8100);
|
||||
CHECK(S3("H", 0) == 1 && !dm_cloud_conflict_take(), "⑯ 正常玩法:共享仓库物品取空、编年史仓库取空(文件还在,0 件),编年史没变短——照常上传");
|
||||
// ⑰ rf3 那个形状:云端专家仓库 2 件、编年史还是新建的 148;本机这份被换成游戏新建的空档(0 件、148),状态记录还在、云端没变 = 走「只本机改了」的上传
|
||||
// (17) That rf3 shape: cloud hardcore stash has 2 items and the chronicle is still the freshly created 148; the local copy was replaced by the empty file the game freshly creates (0 items, 148), the state record is still there and the cloud is unchanged = takes the "only local changed" upload
|
||||
{ char cd[1024]; snprintf(cd, sizeof cd, "%s/cloud4", R); mkdir(cd, 0755);
|
||||
#define S4(dev, down) (path(s3, dev, "save"), path(b3, dev, "bak"), path(t3, dev, "state"), dm_cloud_sync(s3, cd, b3, t3, down, 0, NULL))
|
||||
put_d2i("J", 2, 148, 1000); CHECK(S4("J", 1) == 1, "⑰ 准备:J 上传 2 件、编年史 148 的仓库");
|
||||
put_d2i("J", 0, 148, 2000); dm_cloud_conflict_take();
|
||||
CHECK(S4("J", 0) == 0 && dm_cloud_conflict_take() == 1, "⑰ 运行中要拿新建空档(0 件、148)盖 2 件的那份:拦下");
|
||||
CHECK(S4("J", 1) == 0, "⑰ 启动时同样拦下(不上传)");
|
||||
put_d2i("J", 0, 300, 3000); CHECK(S4("J", 0) == 1, "⑰ 编年史长过新建大小的仓库取空:照常上传");
|
||||
// ⑱ rf3 真形状:云端专家仓库是另一台的预置(stash_seed.h),本机还没有专家仓库档(启动同步跑在写预置之前)→ 不拦、不弹;本机写了预置后上传也不拦
|
||||
// (18) The real rf3 shape: the cloud hardcore stash is another device's preset (stash_seed.h), and the local device has no hardcore stash file yet (startup sync runs before the preset is written) -> not blocked, no prompt; uploading after the local device writes the preset is not blocked either
|
||||
#ifdef T_HAVE_STASH_SEED
|
||||
{ char cd5[1024]; snprintf(cd5, sizeof cd5, "%s/cloud5", R); mkdir(cd5, 0755);
|
||||
#define S5(dev, down) (path(s3, dev, "save"), path(b3, dev, "bak"), path(t3, dev, "state"), dm_cloud_sync(s3, cd5, b3, t3, down, 0, NULL))
|
||||
#define HC "save/ModernSharedStashHardCoreV2/ModernSharedStashHardCoreV2.d2i"
|
||||
put_bin("K", HC, g_stash_seed, sizeof g_stash_seed, 1000); put_d2i("K", 3, 400, 1000); CHECK(S5("K", 1) == 1, "⑱ 准备:K 上传(专家仓库是预置)");
|
||||
{ char p5[1024]; path(p5, "K", HC); unlink(p5); } put_d2i("K", 3, 400, 2000); dm_cloud_conflict_take();
|
||||
S5("K", 0); CHECK(!dm_cloud_conflict_take(), "⑱ 本机还没有专家仓库档、云端只是预置:不算丢东西,不弹");
|
||||
put_bin("K", HC, g_stash_seed, sizeof g_stash_seed, 3000); S5("K", 0); CHECK(!dm_cloud_conflict_take(), "⑱ 本机写了预置再上传:不拦");
|
||||
// ⑲ 反过来:云端有真东西,本机是预置 → 照拦
|
||||
// (19) The reverse: the cloud has real content and the local copy is the preset -> still blocked
|
||||
put_d2i("K", 5, 600, 4000); S5("K", 0); dm_cloud_conflict_take();
|
||||
{ uint8_t big[700]; memset(big, 0, sizeof big); uint32_t l1 = 68, l2 = 300; memcpy(big, "\x55\xaa\x55\xaa", 4); memcpy(big + 16, &l1, 4); memcpy(big + 64, "JM", 2); big[66] = 9; memcpy(big + 68, "\x55\xaa\x55\xaa", 4); memcpy(big + 84, &l2, 4); big[132] = 0xc0;
|
||||
put_bin("K", HC, big, 68 + 300, 5000); CHECK(S5("K", 0) == 1, "⑲ 准备:专家仓库有 9 件、编年史 300 上传"); }
|
||||
put_bin("K", HC, g_stash_seed, sizeof g_stash_seed, 6000);
|
||||
CHECK(S5("K", 0) == 0 && dm_cloud_conflict_take() == 1, "⑲ 本机变回预置要盖 9 件的那份:拦下");
|
||||
#undef HC
|
||||
#undef S5
|
||||
}
|
||||
#else
|
||||
printf("跳过 ⑱ ⑲:没有共享仓库预置 stash_seed.h(公开仓库不带)\n");
|
||||
#endif
|
||||
#undef S4
|
||||
}
|
||||
#undef D2I
|
||||
#undef S3
|
||||
}
|
||||
printf("t_cloudsync: %d 项,%d 失败\n", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
// svc 0x1C(WaitProcessWideKeyAtomic)与 SDK 用户态快路径之间的可见性窗口,确定性单测(资源表读写锁丢唤醒卡死)。
|
||||
// 场景:W 持互斥锁后调 0x1C 等条件变量;钩子落在 0x1C「放锁之后、挂链之前」,此刻让 R 按 SDK 用户态写法动作:
|
||||
// CAS 0→R 抢锁 → 读条件键,非 0 才发 svc 0x1D(键, 1)(sdk InternalConditionVariable::Signal 0x351140 同此)→ 放锁:锁字仍是 R 的标签则 CAS→0,带等待位则 svc 0x1B。
|
||||
// 期望(Horizon 内核语义:等待者先发布「有等待」再放锁 ⇒ 任何在其放锁后改条件的线程必能看到键非 0 并唤醒它):
|
||||
// W 的 0x1C 返回 0;返回时锁字 = W 的标签(被唤醒者持锁);条件键 = 0(无剩余等待者)。
|
||||
// 构建两份:t_condvar(现行顺序,须全过)与 t_condvar_old(-DDM_TEST_CV_OLD_ORDER 还原旧顺序,须判出丢唤醒 = 负对照有效)。
|
||||
// Deterministic unit test of the visibility window between svc 0x1C (WaitProcessWideKeyAtomic) and the SDK's user-mode fast path (the lost wakeup hang of the resource table read-write lock).
|
||||
// Scenario: W holds the mutex and calls 0x1C to wait on the condition variable; the hook sits in 0x1C "after releasing the lock, before linking into the wait list", and at this moment R acts the way the SDK's user-mode code does:
|
||||
// CAS 0->R to grab the lock -> read the condition key, send svc 0x1D(key, 1) only if non-zero (same as sdk InternalConditionVariable::Signal 0x351140) -> release the lock: CAS->0 if the lock word is still R's tag, svc 0x1B if the waiter bit is set.
|
||||
// Expected (Horizon kernel semantics: a waiter publishes "there is a waiter" before releasing the lock => any thread that changes the condition after it releases the lock is bound to see a non-zero key and wake it):
|
||||
// W's 0x1C returns 0; on return the lock word = W's tag (the woken thread holds the lock); condition key = 0 (no remaining waiters).
|
||||
// Two builds: t_condvar (current order, must fully pass) and t_condvar_old (-DDM_TEST_CV_OLD_ORDER restores the old order, must detect the lost wakeup = the negative control is valid).
|
||||
#include "../dm.h"
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <unistd.h>
|
||||
int svc_thread(int num, uint64_t *regs);
|
||||
uint32_t svc_thread_main_init(void);
|
||||
void (*dm_test_cv_after_release)(void);
|
||||
|
||||
static _Atomic uint32_t g_mutex, g_key; // 互斥锁字、条件键(对应 SDK InternalCriticalSection / InternalConditionVariable 的一个字) | mutex word, condition key (corresponding to one word of the SDK's InternalCriticalSection / InternalConditionVariable)
|
||||
static uint32_t g_wtag, g_rtag = 0x2002;
|
||||
static _Atomic int g_rstate; // 0 未动 1 已抢到锁 2 将发 0x1D 3 完成 | 0 not started 1 lock acquired 2 about to send 0x1D 3 done
|
||||
static pthread_mutex_t g_m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_c = PTHREAD_COND_INITIALIZER;
|
||||
static int g_go, g_wdone; static int64_t g_wret = -1; static uint32_t g_wlock_after;
|
||||
static void state_set(int state) {
|
||||
atomic_store(&g_rstate, state);
|
||||
pthread_mutex_lock(&g_m); pthread_cond_broadcast(&g_c); pthread_mutex_unlock(&g_m);
|
||||
}
|
||||
|
||||
static void *reader(void *a) {
|
||||
(void)a;
|
||||
pthread_mutex_lock(&g_m); while (!g_go) pthread_cond_wait(&g_c, &g_m); pthread_mutex_unlock(&g_m);
|
||||
uint32_t z = 0; while (!atomic_compare_exchange_strong(&g_mutex, &z, g_rtag)) { z = 0; sched_yield(); } // 用户态抢锁 | grab the lock in user mode
|
||||
state_set(1);
|
||||
// (此处 R 改条件:例如把读者计数减到 0)
|
||||
// (here R changes the condition: for example decrementing the reader count to 0)
|
||||
if (atomic_load(&g_key)) { state_set(2); uint64_t r[8] = {(uint64_t)&g_key, 1}; svc_thread(0x1D, r); } // Signal 快路径:键 0 不发 svc | Signal fast path: key 0 sends no svc
|
||||
uint32_t v = g_rtag;
|
||||
if (!atomic_compare_exchange_strong(&g_mutex, &v, 0)) { uint64_t r[8] = {(uint64_t)&g_mutex}; svc_thread(0x1B, r); } // 带等待位 ⇒ ArbitrateUnlock | waiter bit set => ArbitrateUnlock
|
||||
state_set(3);
|
||||
return NULL;
|
||||
}
|
||||
static void hook(void) { // 在 W 的 0x1C 里、持宿主全局锁 G、已放锁未挂链:放 R 去跑,等它「完成」或「将发 0x1D(会卡在 G 上)」 | inside W's 0x1C, holding the host global lock G, lock released but not yet linked into the wait list: let R run and wait until it is "done" or "about to send 0x1D (will block on G)"
|
||||
dm_test_cv_after_release = NULL;
|
||||
pthread_mutex_lock(&g_m); g_go = 1; pthread_cond_broadcast(&g_c); pthread_mutex_unlock(&g_m);
|
||||
pthread_mutex_lock(&g_m); while (atomic_load(&g_rstate) != 2 && atomic_load(&g_rstate) != 3) pthread_cond_wait(&g_c, &g_m); pthread_mutex_unlock(&g_m);
|
||||
}
|
||||
static void *waiter(void *a) {
|
||||
(void)a;
|
||||
g_wtag = svc_thread_main_init();
|
||||
uint32_t z = 0; atomic_compare_exchange_strong(&g_mutex, &z, g_wtag); // W 持锁 | W holds the lock
|
||||
dm_test_cv_after_release = hook;
|
||||
uint64_t r[8] = {(uint64_t)&g_mutex, (uint64_t)&g_key, g_wtag, (uint64_t)-1};
|
||||
svc_thread(0x1C, r);
|
||||
pthread_mutex_lock(&g_m); g_wret = (int64_t)r[0]; g_wlock_after = atomic_load(&g_mutex); g_wdone = 1; pthread_cond_broadcast(&g_c); pthread_mutex_unlock(&g_m);
|
||||
return NULL;
|
||||
}
|
||||
int main(void) {
|
||||
pthread_t w, rd; pthread_create(&rd, NULL, reader, NULL); pthread_create(&w, NULL, waiter, NULL);
|
||||
struct timespec dl; clock_gettime(CLOCK_REALTIME, &dl); dl.tv_sec += 10;
|
||||
pthread_mutex_lock(&g_m); while (!g_wdone) if (pthread_cond_timedwait(&g_c, &g_m, &dl)) break; int done = g_wdone; pthread_mutex_unlock(&g_m);
|
||||
#ifdef DM_TEST_CV_OLD_ORDER
|
||||
// 负对照:旧顺序必丢唤醒(R 读到键 0 不发 0x1D,W 挂上去后无人唤醒)
|
||||
// Negative control: the old order always loses the wakeup (R reads key 0 and does not send 0x1D, and nobody wakes W after it is queued)
|
||||
int ok = !done && atomic_load(&g_rstate) == 3;
|
||||
printf("%s 旧顺序负对照:W %s,R 状态 %d(期望 W 不醒、R 未发 0x1D 即完成)\n", ok ? "✓" : "✗", done ? "被唤醒" : "10 秒未醒", atomic_load(&g_rstate));
|
||||
printf(ok ? "全过:1/1\n" : "失败:负对照没判出丢唤醒(判据无效)\n");
|
||||
#else
|
||||
int ok = done && g_wret == 0 && g_wlock_after == g_wtag && atomic_load(&g_key) == 0;
|
||||
printf("%s 现行顺序:W %s 返回 %lld,锁字 %#x(期望 W 标签 %#x),条件键 %u(期望 0),R 状态 %d\n", ok ? "✓" : "✗",
|
||||
done ? "被唤醒" : "2 秒未醒", (long long)g_wret, g_wlock_after, g_wtag, atomic_load(&g_key), atomic_load(&g_rstate));
|
||||
printf(ok ? "全过:1/1\n" : "失败:1/1\n");
|
||||
#endif
|
||||
fflush(stdout); _exit(ok ? 0 : 1);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// t_condvar 的桩:hle_thread.c 在单测里用不到的宿主设施
|
||||
// Stubs for t_condvar: host facilities of hle_thread.c that the unit test does not use
|
||||
#include "../dm.h"
|
||||
struct dm_flags g_flag;
|
||||
uint64_t g_t0_ns;
|
||||
void crash_thread_init(void) {}
|
||||
void guest_thread_init(void) {}
|
||||
void dm_thread_enter(uint64_t entry, uint64_t arg, uint64_t sp) { (void)entry; (void)arg; (void)sp; abort(); }
|
||||
void *guest_sym(const char *name) { (void)name; return NULL; }
|
||||
module_t *module_of(const void *p) { (void)p; return NULL; }
|
||||
void dm_prof_add(int id, uint64_t ns, uint64_t bytes) { (void)id; (void)ns; (void)bytes; }
|
||||
#include <mach/mach_time.h>
|
||||
uint64_t now_ns(void) { static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb); return mach_absolute_time() * tb.numer / tb.denom; }
|
||||
uint64_t guest_ns(void) { return now_ns(); }
|
||||
int dm_detclock_enabled(void) { return 0; }
|
||||
@@ -0,0 +1,62 @@
|
||||
// 秘境结算门落点的单测(dm_doorspot.h,秒级)。期望值都是按图手算的,不跑被测实现。
|
||||
// 现场:洞穴 / 地穴类窄图,人贴墙站,旧规则的理想点(背对守护者 10 格、左右错 5 格)落在墙里。
|
||||
// 红 → 绿:同一张图上,旧规则的落点是挡格(old_spot_blocked);新规则的落点必须是可达格。
|
||||
// Unit test of the rift completion door landing points (dm_doorspot.h, takes seconds). The expected values are all computed by hand from the maps, without running the implementation under test.
|
||||
// Situation: narrow maps of the Cave / Pit kind, the player standing against a wall, and the old rule's ideal point (10 cells with the back to the guardian, offset 5 cells left / right) lands inside a wall.
|
||||
// Fail → pass: on the same map, the old rule's landing point is a blocked cell (old_spot_blocked); the new rule's landing point must be a reachable cell.
|
||||
#include "dm_doorspot.h"
|
||||
#include <stdio.h>
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
static struct ds_grid g;
|
||||
static void fill(int v) { memset(g.blk, v, sizeof g.blk); }
|
||||
static void rect(int x0, int y0, int x1, int y1, int v) { for (int y = y0; y <= y1; y++) for (int x = x0; x <= x1; x++) if (x >= -DS_R && x <= DS_R && y >= -DS_R && y <= DS_R) g.blk[(y + DS_R) * DS_W + x + DS_R] = (uint8_t)v; }
|
||||
static int blk(int x, int y) { return ds_blk(&g, x + DS_R, y + DS_R); }
|
||||
static int dist(int x, int y) { return ds_dist(&g, x + DS_R, y + DS_R); }
|
||||
|
||||
int main(void) {
|
||||
int x, y, t;
|
||||
// ① 空地:理想点本身合规 → 原样取到(野外图不退化)
|
||||
// ① Open ground: the ideal point itself qualifies → taken as is (wilderness maps do not degrade)
|
||||
fill(0); ds_flood(&g);
|
||||
t = ds_pick(&g, 12, -3, 0, 0, 0, 6, &x, &y); CHECK(t == 0 && x == 12 && y == -3, "空地上应取理想点 12,-3 档 0,得到 %d,%d 档 %d", x, y, t);
|
||||
t = ds_pick(&g, 2, 12, 1, 12, -3, 6, &x, &y); CHECK(t == 0 && x == 2 && y == 12, "空地上第二扇应取理想点 2,12,得到 %d,%d 档 %d", x, y, t);
|
||||
CHECK(dist(12, -3) == 15, "空地上 12,-3 走 15 步,算出 %d", dist(12, -3));
|
||||
|
||||
// ② 横向走廊(y −4..4 可走,其余是墙),人在中间,理想点在正下方墙里
|
||||
// ② Horizontal corridor (y −4..4 walkable, the rest is wall), the player in the middle, the ideal point inside the wall straight below
|
||||
fill(1); rect(-DS_R, -4, DS_R, 4, 0); ds_flood(&g);
|
||||
CHECK(blk(5, 10) && blk(-5, 10), "对照:旧规则的两个落点 ±5,10 在墙里");
|
||||
// 十字占位 → 可达的 y 是 −3..3;周围 2 格都可达 → y −1..1。离 (5,10) 最近的是 (5,1)
|
||||
// Cross footprint → the reachable y is −3..3; the 2 cells around all reachable → y −1..1. The nearest to (5,10) is (5,1)
|
||||
t = ds_pick(&g, 5, 10, 0, 0, 0, 6, &x, &y); CHECK(t == 0 && x == 5 && y == 1, "走廊里应取 5,1 档 0,得到 %d,%d 档 %d", x, y, t);
|
||||
CHECK(dist(x, y) >= 0 && !blk(x, y), "落点必须可达且不挡");
|
||||
int x2, y2; t = ds_pick(&g, -5, 10, 1, x, y, 6, &x2, &y2); CHECK(t == 0 && x2 == -5 && y2 == 1, "走廊里第二扇应取 -5,1,得到 %d,%d 档 %d", x2, y2, t);
|
||||
|
||||
// ③ 墙那边有一片空地但和人不连通:不许选过去
|
||||
// ③ There is a patch of open ground beyond the wall but it is not connected to the player: it must not be chosen
|
||||
fill(1); rect(-DS_R, -4, DS_R, 4, 0); rect(-DS_R, 8, DS_R, 16, 0); ds_flood(&g);
|
||||
CHECK(!blk(5, 10) && dist(5, 10) < 0, "对照:5,10 不挡、但从人这里走不到");
|
||||
t = ds_pick(&g, 5, 10, 0, 0, 0, 6, &x, &y); CHECK(dist(x, y) >= 0 && y <= 1, "隔墙空地不许选,应留在人这一侧,得到 %d,%d", x, y);
|
||||
|
||||
// ④ 窄道(3 格宽:y −1..1):摆不出 5 × 5、3 × 3 → 档 2,取离人最近的可达格(十字占位下只有 y = 0 一行可达,离人 1 格)
|
||||
// ④ Narrow passage (3 cells wide: y −1..1): neither 5 × 5 nor 3 × 3 fits → tier 2, take the reachable cell nearest to the player (with the cross footprint only the row y = 0 is reachable, 1 cell from the player)
|
||||
fill(1); rect(-DS_R, -1, DS_R, 1, 0); ds_flood(&g);
|
||||
t = ds_pick(&g, 5, 10, 0, 0, 0, 6, &x, &y); CHECK(t == 2 && y == 0 && abs(x) == 1, "窄道里应退到脚下最近的可达格(±1,0)档 2,得到 %d,%d 档 %d", x, y, t);
|
||||
t = ds_pick(&g, -5, 10, 1, x, y, 6, &x2, &y2); CHECK(t == 2 && y2 == 0 && abs(x2 - x) >= 2 && dist(x2, y2) >= 0, "窄道里第二扇离第一扇至少 2 格且可达,得到 %d,%d 档 %d", x2, y2, t);
|
||||
|
||||
// ⑤ 人被围死在一格里:落在脚下
|
||||
// ⑤ The player is boxed into a single cell: land at the feet
|
||||
fill(1); rect(0, 0, 0, 0, 0); ds_flood(&g);
|
||||
t = ds_pick(&g, 5, 10, 0, 0, 0, 6, &x, &y); CHECK(t == 3 && x == 0 && y == 0 && g.reach == 1, "围死时落在脚下档 3,得到 %d,%d 档 %d(可达 %d 格)", x, y, t, g.reach);
|
||||
|
||||
// ⑥ 要绕远路才到的格不选:理想点在一道长墙背面,绕过去超过 36 步
|
||||
// ⑥ Cells reached only by a long detour are not chosen: the ideal point is behind a long wall, and going around takes more than 36 steps
|
||||
fill(0); rect(-20, 6, 20, 7, 1); ds_flood(&g);
|
||||
CHECK(dist(0, 12) > DS_FAR, "对照:墙背面 0,12 要走 %d 步(> %d)", dist(0, 12), DS_FAR);
|
||||
t = ds_pick(&g, 0, 12, 0, 0, 0, 6, &x, &y); CHECK(t == 0 && abs(x) == 3 && y == 2, "长墙前应取墙这一侧的 ±3,2(y = 2 是周围 2 格都可达的最靠墙一行;离人至少 3 格所以 x = ±3),得到 %d,%d 档 %d", x, y, t);
|
||||
|
||||
printf("t_doorspot:%d 项,%d 项不通\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// 存档写与存档事务单测(秒级):直接包含 hle_fs.c 调它的静态实现;pwrite 换成可编排的假实现。
|
||||
// 期望值全部按语义手写,不调被测实现算:
|
||||
// ① pwrite 返回 0(盘满时可能出现)→ WriteFile 一次调用后返回失败(原先在此死循环);
|
||||
// ② pwrite 分段写(先 3 字节再其余)→ 成功且文件内容完整;
|
||||
// ③ 事务:①的失败使这个事务的 Commit 被拒、工作目录回到已提交版;下一个事务写在工作目录,Commit 前已提交目录仍是旧版,Commit 后是新版;
|
||||
// ④ DM_TEST_FS_FAIL=write:N:errno 只让存档第 N 次写失败,前后的写照常;该事务 Commit 被拒、已提交版不变、前端收到一次通知;
|
||||
// 下一个事务照常提交,最终存档 = 下一个事务的内容;
|
||||
// ⑤ 重新挂载丢弃未提交内容。
|
||||
// Save write and save transaction unit test (takes seconds): includes hle_fs.c directly and calls its static implementation; pwrite is replaced by a scriptable fake.
|
||||
// All expected values are hand-written from the semantics, not computed by calling the implementation under test:
|
||||
// (1) pwrite returns 0 (can happen when the disk is full) -> WriteFile returns failure after one call (it used to loop forever here);
|
||||
// (2) pwrite writes in pieces (3 bytes first, then the rest) -> success and the file content is complete;
|
||||
// (3) transaction: the failure in (1) causes this transaction's Commit to be rejected and the working directory to return to the committed version; the next transaction writes in the working directory, the committed directory is still the old version before Commit and the new version after Commit;
|
||||
// (4) DM_TEST_FS_FAIL=write:N:errno makes only the Nth save write fail, with writes before and after proceeding normally; that transaction's Commit is rejected, the committed version is unchanged, and the front end receives one notification;
|
||||
// the next transaction commits normally, and the final save = the content of the next transaction;
|
||||
// (5) remounting discards uncommitted content.
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
static ssize_t fake_pwrite(int fd, const void *buf, size_t n, off_t off);
|
||||
#define pwrite fake_pwrite
|
||||
#include "../hle_fs.c"
|
||||
#undef pwrite
|
||||
ssize_t pwrite(int, const void *, size_t, off_t);
|
||||
|
||||
struct dm_flags g_flag; uint64_t g_t0_ns; uint64_t now_ns(void) { return 0; } // 日志时间戳与读路径的桩(写路径不用) | stubs for log timestamps and the read path (not used by the write path)
|
||||
void dm_prof_add(int id, uint64_t ns, uint64_t b) { (void)id; (void)ns; (void)b; } void dm_guest_write_prepare(void *a, size_t n) { (void)a; (void)n; }
|
||||
extern int g_nfail, g_lasterr; // 前端通知计数(t_fs_stub.c 的强实现替掉 hle_fs.c 的弱实现) | front-end notification count (the strong implementation in t_fs_stub.c replaces the weak one in hle_fs.c)
|
||||
static int g_mode, g_calls; // 0 照常写;1 一律返回 0;2 第一次只写 3 字节 | 0 write normally; 1 always return 0; 2 write only 3 bytes the first time
|
||||
static ssize_t fake_pwrite(int fd, const void *buf, size_t n, off_t off) {
|
||||
g_calls++;
|
||||
if (g_mode == 1) { if (g_calls > 1000) { printf(" ✗ pwrite 返回 0 后被重试超过 1000 次(死循环)\n"); exit(1); } return 0; }
|
||||
if (g_mode == 2 && g_calls == 1 && n > 3) n = 3;
|
||||
return pwrite(fd, buf, n, off);
|
||||
}
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); } else printf(" ✓ "); printf(__VA_ARGS__); printf("\n"); } while (0)
|
||||
static void put(const char *p, const char *s) { FILE *f = fopen(p, "w"); fputs(s, f); fclose(f); }
|
||||
static int same(const char *p, const char *s) {
|
||||
char b[64] = {0}; FILE *f = fopen(p, "r"); if (!f) return 0; size_t k = fread(b, 1, sizeof b - 1, f); fclose(f);
|
||||
return k == strlen(s) && !memcmp(b, s, k);
|
||||
}
|
||||
static Result write_save(const char *path, const char *s) { // 打开 → 定长 → 写 → 关 | open -> set size -> write -> close
|
||||
uint64_t h; Result r = h_fs_OpenFile(&h, path, MODE_WRITE); if (r) return r;
|
||||
h_fs_SetFileSize(h, (int64_t)strlen(s));
|
||||
r = h_fs_WriteFile(h, 0, s, strlen(s), NULL); h_fs_CloseFile(h); return r;
|
||||
}
|
||||
static int read_fs(const char *path, char *out, size_t n) { uint64_t h; size_t got = 0; if (h_fs_OpenFile(&h, path, MODE_READ)) return 0; Result r = h_fs_ReadFile(&got, h, 0, out, n - 1); h_fs_CloseFile(h); out[got] = 0; return !r; }
|
||||
|
||||
// 剔零档案的偏移换算(dm_data_pread):原始内容 = 按位置算的固定字节序列,零段位置填 0;剔零文件 = 去掉零段。
|
||||
// 期望值由「原始序列」直接取,不经被测实现。覆盖:跨保留段 / 零段边界、整段落在零段、开头结尾、越过文件末尾。
|
||||
// Offset translation for zero-stripped archives (dm_data_pread): original content = a fixed byte sequence computed from position, with 0 filled in at zero-run positions; zero-stripped file = zero runs removed.
|
||||
// Expected values are taken directly from the "original sequence", not through the implementation under test. Covers: crossing kept-run / zero-run boundaries, a whole read falling in a zero run, start and end, reading past end of file.
|
||||
static int test_holes(void) {
|
||||
enum { N = 100000 }; static uint8_t orig[N], got[N]; const long hole[3][2] = {{0, 1000}, {30000, 25000}, {99000, 1000}}; // 开头、中间、结尾各一个零段 | one zero run each at the start, middle and end
|
||||
for (long i = 0; i < N; i++) orig[i] = (uint8_t)(i * 131 + (i >> 8) * 7 + 1);
|
||||
for (int h = 0; h < 3; h++) memset(orig + hole[h][0], 0, (size_t)hole[h][1]);
|
||||
char path[] = "/tmp/dm-holes.XXXXXX"; int tfd = mkstemp(path); if (tfd < 0) return 1; char hp[64]; snprintf(hp, sizeof hp, "%s.holes", path);
|
||||
long pos = 0; for (int h = 0; h <= 3; h++) { long end = h < 3 ? hole[h][0] : N; if (end > pos && write(tfd, orig + pos, (size_t)(end - pos)) != end - pos) return 1; if (h < 3) pos = hole[h][0] + hole[h][1]; }
|
||||
close(tfd); FILE *f = fopen(hp, "w"); fprintf(f, "size %d\n", N); for (int h = 0; h < 3; h++) fprintf(f, "%ld %ld\n", hole[h][0], hole[h][1]); fclose(f);
|
||||
int fd = open(path, O_RDONLY); dm_data_note_fd(fd, path); int bad = 0;
|
||||
const long q[][2] = {{0, 500}, {500, 1000}, {999, 2}, {1000, 29000}, {29990, 20}, {30000, 25000}, {40000, 100}, {54990, 20}, {55000, 44000}, {98990, 1010}, {99500, 500}, {99990, 100}, {0, N}, {100000, 10}, {123456, 10}};
|
||||
for (size_t k = 0; k < sizeof q / sizeof *q; k++) {
|
||||
long off = q[k][0], n = q[k][1], want = off >= N ? 0 : (off + n > N ? N - off : n);
|
||||
memset(got, 0xAA, sizeof got); ssize_t r = dm_data_pread(fd, got, (size_t)n, off);
|
||||
if (r != want || (want && memcmp(got, orig + off, (size_t)want))) { fprintf(stderr, "失败:剔零读 off=%ld n=%ld 返回 %zd(期望 %ld)\n", off, n, r, want); bad++; }
|
||||
}
|
||||
if (dm_data_logical_size(path, 49000) != N) { fprintf(stderr, "失败:剔零档案的原始大小\n"); bad++; }
|
||||
close(fd); g_hm[fd] = NULL; unlink(path); unlink(hp);
|
||||
printf("%s 剔零档案偏移换算 15 种读法逐字节等于原始内容\n", bad ? "✗" : "✓");
|
||||
return bad;
|
||||
}
|
||||
int main(void) {
|
||||
if (test_holes()) return 1;
|
||||
char root[1024], save[1100], work[1200], p[1200];
|
||||
const char *sp = getenv("TMPDIR"); snprintf(root, sizeof root, "%s/t_fs.XXXXXX", sp ? sp : "/private/tmp");
|
||||
if (!mkdtemp(root)) { perror("mkdtemp"); return 1; }
|
||||
char rom[1100], overlay[1100], rdata[1200], odata[1200], fn[1300], got[64];
|
||||
snprintf(rom, sizeof rom, "%s/rom", root); snprintf(overlay, sizeof overlay, "%s/overlay", root); snprintf(rdata, sizeof rdata, "%s/data", rom); snprintf(odata, sizeof odata, "%s/data", overlay);
|
||||
mkdir(rom, 0755); mkdir(overlay, 0755); mkdir(rdata, 0755); mkdir(odata, 0755);
|
||||
snprintf(fn, sizeof fn, "%s/same", rdata); put(fn, "base"); snprintf(fn, sizeof fn, "%s/same", odata); put(fn, "overlay"); snprintf(fn, sizeof fn, "%s/base", rdata); put(fn, "only-base"); snprintf(fn, sizeof fn, "%s/over", odata); put(fn, "only-overlay");
|
||||
setenv("DM_ROMFS", rom, 1); setenv("DM_ROMFS_OVERLAY", overlay, 1); CHECK(h_fs_MountRom("rom", NULL, 0) == RES_OK, "挂载 RomFS 两层 overlay");
|
||||
CHECK(read_fs("rom:/data/same", got, sizeof got) && !strcmp(got, "overlay"), "overlay 文件优先"); CHECK(read_fs("rom:/data/base", got, sizeof got) && !strcmp(got, "only-base"), "overlay 缺失时回退基底");
|
||||
uint64_t rh; CHECK(h_fs_OpenFile(&rh, "rom:/data/same", MODE_WRITE) == RES_FAIL, "两层挂载均拒绝写入");
|
||||
{ // 覆盖层里找文件(dm_overlay_file):两层用冒号连着(老机型 = 包内覆盖层 + 补充包),逐层找、前面的优先;把整串当一个目录就哪个也找不到 | Find a file in the overlay (dm_overlay_file): two layers joined by a colon (old devices = in-bundle overlay + Legacy Device Pack), searched layer by layer with earlier ones taking priority; treating the whole string as one directory finds nothing
|
||||
char l2[1100], two[2300], want[1300]; snprintf(l2, sizeof l2, "%s/pack", root); mkdir(l2, 0755); snprintf(two, sizeof two, "%s:%s", overlay, l2); setenv("DM_ROMFS_OVERLAY", two, 1);
|
||||
snprintf(fn, sizeof fn, "%s/mark", overlay); put(fn, "1"); snprintf(fn, sizeof fn, "%s/only2", l2); put(fn, "2"); snprintf(fn, sizeof fn, "%s/mark", l2); put(fn, "2");
|
||||
snprintf(want, sizeof want, "%s/mark", overlay); CHECK(dm_overlay_file("mark", p, sizeof p) == 1 && !strcmp(p, want), "两层都有:取第一层的");
|
||||
snprintf(want, sizeof want, "%s/only2", l2); CHECK(dm_overlay_file("only2", p, sizeof p) == 1 && !strcmp(p, want), "只有第二层有:取第二层的");
|
||||
snprintf(want, sizeof want, "%s/data/over", overlay); CHECK(dm_overlay_file("data/over", p, sizeof p) == 1 && !strcmp(p, want), "带子目录的相对路径");
|
||||
CHECK(dm_overlay_file("none", p, sizeof p) == 0 && !p[0], "哪层都没有:返回 0、输出清空");
|
||||
setenv("DM_ROMFS_OVERLAY", overlay, 1); snprintf(want, sizeof want, "%s/mark", overlay); CHECK(dm_overlay_file("mark", p, sizeof p) == 1 && !strcmp(p, want), "单层(新机型)照旧");
|
||||
unsetenv("DM_ROMFS_OVERLAY"); CHECK(dm_overlay_file("mark", p, sizeof p) == 0, "没设覆盖层:返回 0"); setenv("DM_ROMFS_OVERLAY", overlay, 1); }
|
||||
g_nmnt = 0;
|
||||
snprintf(save, sizeof save, "%s/save", root); snprintf(work, sizeof work, "%s.work", save);
|
||||
mkdir(save, 0755); snprintf(p, sizeof p, "%s/a", save); put(p, "old");
|
||||
setenv("DM_SAVE", save, 1); setenv("DM_TEST_FS_FAIL", "write:5:28", 1); // 存档第 5 次写失败,errno 28 = ENOSPC | the 5th save write fails, errno 28 = ENOSPC
|
||||
CHECK(h_fs_MountSave("save", NULL) == RES_OK, "挂载存档");
|
||||
|
||||
// 存档写计数:①=第 1 次 ②=第 2 次 ③=第 3 次 ④=第 4/5/6/7 次 ⑤=第 8 次
|
||||
// Save write count: (1)=1st (2)=2nd (3)=3rd (4)=4th/5th/6th/7th (5)=8th
|
||||
printf("① pwrite 返回 0\n");
|
||||
g_mode = 1; g_calls = 0;
|
||||
CHECK(write_save("save:/a", "xyz") == RES_FAIL, "WriteFile 返回失败 0x2A2");
|
||||
CHECK(g_calls == 1, "只调了 1 次 pwrite(实际 %d 次;原先无限重试)", g_calls);
|
||||
|
||||
printf("② pwrite 分段写\n");
|
||||
g_mode = 2; g_calls = 0;
|
||||
CHECK(write_save("save:/a", "abcdefg") == RES_OK, "WriteFile 成功");
|
||||
CHECK(g_calls == 2, "pwrite 调 2 次(3 字节 + 4 字节;实际 %d)", g_calls);
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "abcdefg"), "工作目录里是完整的 abcdefg");
|
||||
g_mode = 0;
|
||||
|
||||
printf("③ 事务\n");
|
||||
CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == 1 && g_lasterr == ENOSPC, "①②所在事务 Commit 被拒,前端通知 1 次 errno=ENOSPC(实际 %d 次 errno=%d)", g_nfail, g_lasterr);
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "old"), "工作目录丢弃、回到已提交版 old");
|
||||
CHECK(write_save("save:/a", "new") == RES_OK, "下一个事务:写 new");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "old"), "Commit 前已提交目录仍是 old");
|
||||
CHECK(h_fs_Commit("save") == RES_OK, "Commit");
|
||||
CHECK(same(p, "new"), "Commit 后已提交目录是 new");
|
||||
snprintf(p, sizeof p, "%s.new", save); CHECK(access(p, F_OK) != 0, "换下来的旧版已删(无 .new 残留)");
|
||||
|
||||
printf("④ DM_TEST_FS_FAIL=write:5:28\n");
|
||||
CHECK(write_save("save:/b", "4") == RES_PATH_NOT_FOUND, "(b 不存在,打开即失败,不计写)");
|
||||
h_fs_CreateFile("save:/b", 0);
|
||||
CHECK(write_save("save:/b", "4") == RES_OK, "第 4 次写成功");
|
||||
errno = 0; CHECK(write_save("save:/b", "5") == RES_FAIL && errno == 28, "第 5 次写失败 errno=28(实际 errno=%d)", errno);
|
||||
CHECK(write_save("save:/b", "6") == RES_OK, "第 6 次写成功");
|
||||
CHECK(h_fs_Commit("save") == RES_FAIL && g_nfail == 2 && g_lasterr == 28, "该事务 Commit 被拒,前端通知 errno=28(累计 %d 次)", g_nfail);
|
||||
snprintf(p, sizeof p, "%s/b", save); CHECK(access(p, F_OK) != 0, "已提交目录不变(没有 b)");
|
||||
snprintf(p, sizeof p, "%s/b", work); CHECK(access(p, F_OK) != 0, "工作目录丢弃(没有 b)");
|
||||
snprintf(p, sizeof p, "%s/a", save); CHECK(same(p, "new"), "已提交目录 a 仍是 new");
|
||||
h_fs_CreateFile("save:/b", 0);
|
||||
CHECK(write_save("save:/b", "7") == RES_OK && h_fs_Commit("save") == RES_OK, "下一个事务:写 b=7,Commit 成功");
|
||||
snprintf(p, sizeof p, "%s/b", save); CHECK(same(p, "7"), "最终已提交 b = 7(下一个事务的内容)");
|
||||
CHECK(g_nfail == 2, "成功的事务不发通知(累计仍 %d 次)", g_nfail);
|
||||
|
||||
printf("⑤ 重新挂载丢弃未提交内容\n");
|
||||
CHECK(write_save("save:/a", "v9") == RES_OK, "写 a=v9 不提交");
|
||||
g_nmnt = 0; // 模拟进程重启:挂载表清空 | simulate a process restart: clear the mount table
|
||||
CHECK(h_fs_MountSave("save", NULL) == RES_OK, "重新挂载");
|
||||
snprintf(p, sizeof p, "%s/a", work); CHECK(same(p, "new"), "工作目录 a 回到已提交版 new");
|
||||
snprintf(p, sizeof p, "%s/b", work); CHECK(same(p, "7"), "工作目录 b = 已提交的 7");
|
||||
|
||||
// 语言开关改写设置文件(settings_lang_apply):期望值按规则手算——只在「与开关不符」时把 Language / VoiceLanguage 改成 0(英文)或 8(简中),别的键和别的语言不动
|
||||
// Language switch rewriting the settings file (settings_lang_apply): expected values computed by hand from the rule -- only when it "does not match the switch" are Language / VoiceLanguage changed to 0 (English) or 8 (Simplified Chinese); other keys and other languages are untouched
|
||||
{ extern int g_t_lang; char sd[1200], sf[1300], gotj[512]; snprintf(sd, sizeof sd, "%s/langt", root); mkdir(sd, 0755); snprintf(sf, sizeof sf, "%s/Settings", sd); mkdir(sf, 0755); snprintf(sf, sizeof sf, "%s/Settings/Settings.json", sd);
|
||||
#define LANGCASE(dm, in, want, what) do { g_t_lang = (dm); put(sf, (in)); settings_lang_apply(sd); FILE *lf = fopen(sf, "rb"); size_t ln_ = lf ? fread(gotj, 1, sizeof gotj - 1, lf) : 0; if (lf) fclose(lf); gotj[ln_] = 0; CHECK(!strcmp(gotj, (want)), "语言开关:%s", (what)); } while (0)
|
||||
LANGCASE(-1, "{ \"Language\": 8, \"VoiceLanguage\": 8 }", "{ \"Language\": 8, \"VoiceLanguage\": 8 }", "没点过应用:一个字不动");
|
||||
LANGCASE(1, "{ \"A\": 1, \"Language\": 8, \"VoiceLanguage\": 8, \"B\": 2 }", "{ \"A\": 1, \"Language\": 0, \"VoiceLanguage\": 0, \"B\": 2 }", "开关 = 英文、文件是简中:文字和语音都改成 0,别的键不动");
|
||||
LANGCASE(0, "{ \"Language\": 0, \"VoiceLanguage\": 0 }", "{ \"Language\": 8, \"VoiceLanguage\": 8 }", "开关 = 中文、文件是英文:都改成 8");
|
||||
LANGCASE(0, "{ \"Language\": 9, \"VoiceLanguage\": 9 }", "{ \"Language\": 9, \"VoiceLanguage\": 9 }", "开关 = 中文、玩家在原版里选了繁中:不改回简中");
|
||||
LANGCASE(1, "{ \"Language\": 0, \"VoiceLanguage\": 0 }", "{ \"Language\": 0, \"VoiceLanguage\": 0 }", "开关 = 英文、文件已是英文:不动");
|
||||
LANGCASE(1, "{ \"Language\": 0, \"VoiceLanguage\": 8 }", "{ \"Language\": 0, \"VoiceLanguage\": 0 }", "开关 = 英文、文字已英文但语音还是中文:语音跟上");
|
||||
LANGCASE(1, "{ \"Language\": 12 }", "{\n \"VoiceLanguage\": 0, \"Language\": 0 }", "开关 = 英文、两位数的语言号且没有语音键:改写并补上语音键");
|
||||
g_t_lang = -1; }
|
||||
|
||||
char cmd[1200]; snprintf(cmd, sizeof cmd, "rm -rf '%s'", root); system(cmd);
|
||||
printf("== %d 项,失败 %d ==\n", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Horizon 路径大小写单测:期望手写;在默认不分大小写的 APFS 上跑真实文件操作。
|
||||
// 同名不同大小写必须共存,所有路径组件精确匹配,目录列举仍给客体名字,Commit/重挂保留名字与内容。
|
||||
// Horizon path case unit test: expectations are hand-written; runs real file operations on the default case-insensitive APFS.
|
||||
// Names differing only in case must coexist, all path components match exactly, directory listing still gives the guest names, and Commit/remount preserve names and content.
|
||||
#ifndef HLE_FS_SOURCE
|
||||
#define HLE_FS_SOURCE "../hle_fs.c"
|
||||
#endif
|
||||
#include <sys/xattr.h>
|
||||
#include <errno.h>
|
||||
static int fail_name_write;
|
||||
static int fake_setxattr(const char *p, const char *name, const void *v, size_t n, u_int32_t pos, int opt) {
|
||||
if (fail_name_write) { errno = ENOSPC; return -1; }
|
||||
return setxattr(p, name, v, n, pos, opt);
|
||||
}
|
||||
#define setxattr fake_setxattr
|
||||
#include HLE_FS_SOURCE
|
||||
#undef setxattr
|
||||
struct dm_flags g_flag; uint64_t g_t0_ns;
|
||||
uint64_t now_ns(void) { return 0; }
|
||||
void dm_prof_add(int id, uint64_t ns, uint64_t b) { (void)id; (void)ns; (void)b; }
|
||||
void dm_guest_write_prepare(void *a, size_t n) { (void)a; (void)n; }
|
||||
static int checks, fails;
|
||||
#define CHECK(c, text) do { checks++; int ok = !!(c); fails += !ok; printf("%s %s\n", ok ? "✓" : "✗", text); } while (0)
|
||||
static int content(const char *path, const char *want) {
|
||||
uint64_t h; if (h_fs_OpenFile(&h, path, MODE_READ)) return 0;
|
||||
char b[64] = {0}; size_t n = 0; Result r = h_fs_ReadFile(&n, h, 0, b, sizeof b);
|
||||
h_fs_CloseFile(h); return !r && n == strlen(want) && !memcmp(b, want, n);
|
||||
}
|
||||
static int write_text(const char *path, const char *text) {
|
||||
uint64_t h; if (h_fs_OpenFile(&h, path, MODE_WRITE)) return 0;
|
||||
Result r = h_fs_WriteFile(h, 0, text, strlen(text), NULL); h_fs_CloseFile(h); return !r;
|
||||
}
|
||||
static int listed(const char *path, const char *name, int type) {
|
||||
uint64_t h; if (h_fs_OpenDirectory(&h, path, 3)) return 0;
|
||||
DirectoryEntry e[32]; int64_t n = 0; int found = 0;
|
||||
h_fs_ReadDirectory(&n, e, h, 32); h_fs_CloseDirectory(h);
|
||||
for (int i = 0; i < n; i++) if (!strcmp(e[i].name, name) && e[i].type == type) found++;
|
||||
return found == 1;
|
||||
}
|
||||
static int entry_count(void) {
|
||||
uint64_t h; if (h_fs_OpenDirectory(&h, "save:/", 3)) return -1;
|
||||
DirectoryEntry e[32]; int64_t n = 0;
|
||||
h_fs_ReadDirectory(&n, e, h, 32); h_fs_CloseDirectory(h); return (int)n;
|
||||
}
|
||||
static void *create_race(void *p) { return (void *)(uintptr_t)h_fs_CreateFile(p, 0); }
|
||||
int dm_custom_lang_explicit(void) { return -1; } // 语言开关(dm_custom.c):这份单测不涉及,当作玩家没点过 | Language switch (dm_custom.c): not involved in this unit test, treated as the player never having tapped it
|
||||
int main(void) {
|
||||
char root[1024], save[1024], p[1100];
|
||||
const char *tmp = getenv("TMPDIR");
|
||||
if (tmp) snprintf(root, sizeof root, "%s/case.XXXXXX", tmp);
|
||||
else snprintf(root, sizeof root, "%s%s/run/platform/case.XXXXXX", getenv("DM_ROOT") ?: getenv("HOME"), getenv("DM_ROOT") ? "" : "/dm-work");
|
||||
if (!mkdtemp(root)) { perror("mkdtemp"); return 2; }
|
||||
snprintf(save, sizeof save, "%s/save", root); mkdir(save, 0755);
|
||||
snprintf(p, sizeof p, "%s/Legacy", save); FILE *f = fopen(p, "w"); fputs("old", f); fclose(f);
|
||||
setenv("DM_SAVE", save, 1); CHECK(h_fs_MountSave("save", NULL) == RES_OK, "挂载原有存档");
|
||||
uint64_t h = 0; int32_t type = -1;
|
||||
CHECK(content("save:/Legacy", "old"), "原有大小写名字可读");
|
||||
Result r = h_fs_OpenFile(&h, "save:/legacy", 1); if (!r) h_fs_CloseFile(h);
|
||||
CHECK(r == RES_PATH_NOT_FOUND, "错误大小写 OpenFile → PathNotFound");
|
||||
CHECK(h_fs_GetEntryType(&type, "save:/legacy") == RES_PATH_NOT_FOUND, "错误大小写 GetEntryType → PathNotFound");
|
||||
CHECK(h_fs_DeleteFile("save:/legacy") == RES_PATH_NOT_FOUND, "错误大小写 DeleteFile → PathNotFound");
|
||||
CHECK(content("save:/Legacy", "old"), "错名删除不影响原文件");
|
||||
CHECK(h_fs_CreateFile("save:/legacy", 0) == RES_OK, "Legacy 与 legacy 可以共存");
|
||||
CHECK(write_text("save:/legacy", "lower"), "写 legacy");
|
||||
CHECK(content("save:/Legacy", "old") && content("save:/legacy", "lower"), "两个名字读出独立内容 old/lower");
|
||||
CHECK(h_fs_CreateFile("save:/legacy", 0) == RES_PATH_EXISTS, "精确重复创建 → PathExists");
|
||||
CHECK(listed("save:/", "Legacy", ENT_FILE) && listed("save:/", "legacy", ENT_FILE), "目录列举保留 Legacy/legacy");
|
||||
CHECK(h_fs_CreateDirectory("save:/Dir") == RES_OK, "创建 Dir");
|
||||
CHECK(h_fs_CreateFile("save:/dir/x", 0) == RES_PATH_NOT_FOUND, "错误大小写中间目录拒绝创建");
|
||||
CHECK(h_fs_CreateDirectory("save:/dir") == RES_OK, "Dir 与 dir 可以共存");
|
||||
CHECK(h_fs_CreateFile("save:/Dir/X", 0) == RES_OK && write_text("save:/Dir/X", "upper"), "Dir/X 独立内容 upper");
|
||||
CHECK(h_fs_CreateFile("save:/dir/X", 0) == RES_OK && write_text("save:/dir/X", "lower"), "dir/X 独立内容 lower");
|
||||
CHECK(content("save:/Dir/X", "upper") && content("save:/dir/X", "lower"), "中间目录大小写读不混淆");
|
||||
r = h_fs_OpenDirectory(&h, "save:/DIR", 3); if (!r) h_fs_CloseDirectory(h);
|
||||
CHECK(r == RES_PATH_NOT_FOUND, "错误大小写 OpenDirectory → PathNotFound");
|
||||
CHECK(h_fs_DeleteDirRec("save:/DIR") == RES_PATH_NOT_FOUND, "错误大小写递归删除 → PathNotFound");
|
||||
CHECK(listed("save:/", "Dir", ENT_DIR) && listed("save:/", "dir", ENT_DIR), "目录列举保留 Dir/dir");
|
||||
CHECK(h_fs_RenameFile("save:/Legacy", "save:/legacy") == RES_PATH_EXISTS, "改名到已存在精确名字 → PathExists");
|
||||
CHECK(h_fs_RenameFile("save:/LEGACY", "save:/other") == RES_PATH_NOT_FOUND, "错名来源改名 → PathNotFound");
|
||||
CHECK(h_fs_RenameFile("save:/Legacy", "save:/LEGACY") == RES_OK, "仅改大小写的改名成功");
|
||||
CHECK(content("save:/LEGACY", "old") && content("save:/legacy", "lower"), "改名不覆盖另一个客体文件");
|
||||
CHECK(h_fs_GetEntryType(&type, "save:/Legacy") == RES_PATH_NOT_FOUND, "旧客体名字消失");
|
||||
CHECK(h_fs_Commit("save") == RES_OK, "提交两个大小写文件和目录");
|
||||
g_nmnt = 0; CHECK(h_fs_MountSave("save", NULL) == RES_OK, "重新挂载已提交存档");
|
||||
CHECK(content("save:/LEGACY", "old") && content("save:/legacy", "lower"), "提交重挂保留独立名字/内容");
|
||||
CHECK(content("save:/Dir/X", "upper") && content("save:/dir/X", "lower"), "提交重挂保留独立目录");
|
||||
CHECK(listed("save:/", "LEGACY", ENT_FILE) && listed("save:/", "legacy", ENT_FILE), "提交重挂列举不漏映射");
|
||||
CHECK(h_fs_DeleteFile("save:/legacy") == RES_OK && content("save:/LEGACY", "old"), "删除映射文件不伤另一个名字");
|
||||
CHECK(h_fs_DeleteDirRec("save:/dir") == RES_OK && content("save:/Dir/X", "upper"), "删除映射目录不伤另一个目录");
|
||||
CHECK(h_fs_CreateFile("save:/legacy", 0) == RES_OK && write_text("save:/legacy", "again"), "删除后可重新创建同名文件");
|
||||
CHECK(h_fs_RenameFile("save:/legacy", "save:/plain") == RES_OK && content("save:/plain", "again"), "映射文件改到普通名字可读");
|
||||
CHECK(listed("save:/", "plain", ENT_FILE) && !listed("save:/", "legacy", ENT_FILE), "改名更新列举,旧名字消失");
|
||||
CHECK(mount("rom", save, 1) == RES_OK && content("rom:/LEGACY", "old"), "只读挂载读取映射名字");
|
||||
CHECK(h_fs_GetEntryType(&type, "rom:/Legacy") == RES_PATH_NOT_FOUND, "只读挂载也按精确大小写查找");
|
||||
CHECK(h_fs_CreateDirectory("save:/Trail/") == RES_OK && listed("save:/", "Trail", ENT_DIR), "创建目录尾斜杠不变成空名字");
|
||||
CHECK(h_fs_CreateFile("save:/.dm-case-1", 0) == RES_OK && write_text("save:/.dm-case-1", "real"), "客体真实别名前缀名字可以创建");
|
||||
CHECK(content("save:/.dm-case-1", "real") && content("save:/LEGACY", "old"), "物理别名不冒充客体真实名字");
|
||||
CHECK(listed("save:/", ".dm-case-1", ENT_FILE), "客体真实别名前缀名字按原名列举");
|
||||
CHECK(h_fs_CreateFile("save:/plain", 0) == RES_PATH_EXISTS, "普通名字重复创建仍拒绝");
|
||||
int before = entry_count(); fail_name_write = 1;
|
||||
CHECK(h_fs_CreateFile("save:/PLAIN", 0) == RES_FAIL, "别名元数据盘满:创建文件返回失败");
|
||||
CHECK(entry_count() == before && h_fs_GetEntryType(&type, "save:/PLAIN") == RES_PATH_NOT_FOUND, "失败创建不遗留文件或客体名字");
|
||||
CHECK(h_fs_CreateDirectory("save:/trail") == RES_FAIL && entry_count() == before, "别名目录元数据失败:移除刚建目录");
|
||||
CHECK(h_fs_RenameFile("save:/plain", "save:/PLAIN") == RES_FAIL, "改名元数据失败返回失败");
|
||||
CHECK(content("save:/plain", "again") && h_fs_GetEntryType(&type, "save:/PLAIN") == RES_PATH_NOT_FOUND && entry_count() == before, "失败改名完整回退原名和内容");
|
||||
fail_name_write = 0;
|
||||
CHECK(h_fs_CreateFile("save:/PLAIN", -1) == RES_FAIL && entry_count() == before, "别名文件定长失败不遗留无元数据物理名");
|
||||
CHECK(h_fs_CreateFile("save:/Ä", 0) == RES_OK && h_fs_CreateFile("save:/ä", 0) == RES_OK, "非 ASCII 大小写同样共存");
|
||||
CHECK(write_text("save:/Ä", "upper") && write_text("save:/ä", "lower") && content("save:/Ä", "upper") && content("save:/ä", "lower"), "非 ASCII 名字内容独立");
|
||||
pthread_t t[2]; void *r0, *r1;
|
||||
pthread_create(&t[0], NULL, create_race, "save:/Race"); pthread_create(&t[1], NULL, create_race, "save:/race");
|
||||
pthread_join(t[0], &r0); pthread_join(t[1], &r1);
|
||||
CHECK(!r0 && !r1 && listed("save:/", "Race", ENT_FILE) && listed("save:/", "race", ENT_FILE), "并发创建大小写两个名字都独立发布");
|
||||
rm_tree(root);
|
||||
printf("== 大小写 %d 项,失败 %d ==\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
// t_fs 的桩:前端存档失败通知的强实现(另一个编译单元,链接时替掉 hle_fs.c 的弱实现,同 iOS 前端的做法)
|
||||
// Stub for t_fs: strong implementation of the front end's save-failure notification (a separate compilation unit that replaces the weak implementation in hle_fs.c at link time, the same way the iOS front end does it)
|
||||
int g_nfail, g_lasterr;
|
||||
void front_save_failed(int err) { g_nfail++; g_lasterr = err; }
|
||||
|
||||
int g_t_lang = -1; // 语言开关(dm_custom.c 的 lang_en)在设置文件里的值,t_fs.c 的用例改它:-1 没点过 / 0 简中 / 1 英文 | Value of the language switch (lang_en in dm_custom.c) in the settings file, changed by the cases in t_fs.c: -1 never tapped / 0 Simplified Chinese / 1 English
|
||||
int dm_custom_lang_explicit(void) { return g_t_lang; }
|
||||
@@ -0,0 +1,59 @@
|
||||
// 实际dm_input_set→GetNpadState返回收样;假时钟只固定timestamp,不替换输入/返回布局。
|
||||
// The actual dm_input_set -> GetNpadState return takes the sample; the fake clock only fixes the timestamp and does not replace the input/return layout.
|
||||
#ifndef HLE_HID_SOURCE
|
||||
#define HLE_HID_SOURCE "../hle_hid.c"
|
||||
#endif
|
||||
#include HLE_HID_SOURCE
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
#include <unistd.h>
|
||||
#include <sys/wait.h>
|
||||
static uint64_t clock_ns=1000000000ull;
|
||||
uint64_t dm_guest_frame(void) { return 0; }
|
||||
uint64_t dm_server_tick(void) { return UINT64_MAX; }
|
||||
int dm_loadscreen_up(void) { return 0; }
|
||||
void dm_hold_for_loadscreen(void) {}
|
||||
uint64_t now_ns(void) { return clock_ns; }
|
||||
uint64_t guest_ns(void) { return clock_ns; }
|
||||
static int opmode=1;
|
||||
int dm_opmode(void) { return opmode; }
|
||||
int touch_fill(void *p, uint64_t n) { (void)p;(void)n;return 0; }
|
||||
void dm_touch_set(const dm_touch *p,int n) { (void)p;(void)n; }
|
||||
void uimsg_subscribe(void (*f)(const char *,const char *,const char *)) { (void)f; }
|
||||
static int checks,fails;
|
||||
#define CK(c) do { checks++; if (!(c)) { fails++;printf("FAIL line=%d %s\n",__LINE__,#c); } } while(0)
|
||||
typedef struct { long long sampling; unsigned long long start,time,buttons,script; unsigned id,style,attrs; int lx,ly,rx,ry; } Row;
|
||||
static int load(const char *path,Row *rows,int *limit) {
|
||||
FILE *f=fopen(path,"r");if(!f)return -1;char s[512];int n=0;*limit=0;
|
||||
while(fgets(s,sizeof s,f)) { if(strstr(s,"limit_reached")){(*limit)++;continue;} Row r={0};
|
||||
int k=sscanf(s,"{\"event\":\"npad_return\",\"read_start_ns\":%llu,\"time_ns\":%llu,\"sampling\":%lld,\"id\":%u,\"style\":%u,\"buttons\":%llu,\"lx\":%d,\"ly\":%d,\"rx\":%d,\"ry\":%d,\"attributes\":%u,\"script_mask\":%llu}",&r.start,&r.time,&r.sampling,&r.id,&r.style,&r.buttons,&r.lx,&r.ly,&r.rx,&r.ry,&r.attrs,&r.script);
|
||||
CK(k==12);CK(r.start<=r.time);if(n<1024)rows[n]=r;n++;
|
||||
}fclose(f);return n;
|
||||
}
|
||||
static void exercise(int which) {
|
||||
char path[256];snprintf(path,sizeof path,"%s/hid-receipt-%d.jsonl",getenv("TMPDIR")?getenv("TMPDIR"):"/tmp",getpid());unlink(path);
|
||||
unsetenv("DM_KEYS");unsetenv("DM_HID_RECEIPT_LOG");if(which)setenv("DM_HID_RECEIPT_LOG",path,1);if(which==2)setenv("DM_KEYS","A@0+10",1);
|
||||
NpadState s;uint32_t id=0;Row *rows=calloc(1024,sizeof *rows);int limit=0,n;
|
||||
if(which==4) {
|
||||
dm_input_set(0,0,0,0,0);h_hid_GetFullKey(&s,&id);h_hid_GetFullKey(&s,&id);
|
||||
clock_ns+=1000000000ull;h_hid_GetFullKey(&s,&id);
|
||||
n=load(path,rows,&limit);CK(n==2);if(n==2){CK(rows[0].sampling==1&&rows[1].sampling==3);CK(rows[1].time-rows[0].time==1000000000ull);CK(!rows[0].buttons&&!rows[1].buttons);}CK(limit==0);
|
||||
} else if(which==3) {
|
||||
for(int i=0;i<1030;i++){dm_input_set(0,(i&1)?32767:-32767,0,0,0);h_hid_GetFullKey(&s,&id);CK(s.lx==((i&1)?32767:-32767));}
|
||||
n=load(path,rows,&limit);CK(n==1024);CK(limit==1);
|
||||
} else if(which==2) {
|
||||
dm_input_set(DM_BTN_B,123,-456,7,-8);h_hid_GetFullKey(&s,&id);CK(s.buttons==(DM_BTN_A|DM_BTN_B));CK(s.lx==123&&s.ly==-456);
|
||||
n=load(path,rows,&limit);CK(n==1);if(n==1){CK(rows[0].buttons==s.buttons);CK(rows[0].script==DM_BTN_A);CK(rows[0].lx==123&&rows[0].ly==-456&&rows[0].rx==7&&rows[0].ry==-8);}CK(limit==0);
|
||||
} else {
|
||||
dm_input_set(0,0,0,0,0);h_hid_GetFullKey(&s,&id);CK(s.sampling==1&&s.attributes==1);
|
||||
dm_input_set(DM_BTN_B,32767,-32767,11,-12);h_hid_GetFullKey(&s,&id);CK(s.buttons==DM_BTN_B&&s.lx==32767&&s.ly==-32767&&s.rx==11&&s.ry==-12);
|
||||
h_hid_GetFullKey(&s,&id);CK(s.sampling==3);
|
||||
dm_input_set(0,0,0,0,0);h_hid_GetFullKey(&s,&id);CK(!s.buttons&&!s.lx&&!s.ly);
|
||||
opmode=0;id=0x20;dm_input_set(DM_BTN_Y,-32767,0,0,0);h_hid_GetHandheld(&s,&id);CK(s.attributes==1&&s.buttons==DM_BTN_Y&&s.lx==-32767);
|
||||
id=0;h_hid_GetFullKey(&s,&id);CK(s.attributes==0&&!s.buttons&&!s.lx&&s.sampling==6);
|
||||
n=load(path,rows,&limit);
|
||||
if(!which)CK(n==-1);
|
||||
else {CK(n==5);CK(limit==0);if(n==5){CK(rows[0].sampling==1&&rows[0].time==clock_ns&&rows[0].buttons==0);CK(rows[1].sampling==2&&rows[1].buttons==DM_BTN_B&&rows[1].lx==32767&&rows[1].ry==-12);CK(rows[2].sampling==4&&rows[2].buttons==0&&rows[2].lx==0);CK(rows[3].id==0x20&&rows[3].style==STYLE_HANDHELD&&rows[3].attrs==1&&rows[3].lx==-32767);CK(rows[4].id==0&&rows[4].style==STYLE_FULLKEY&&rows[4].attrs==0&&rows[4].sampling==6);}}
|
||||
}
|
||||
free(rows);unlink(path);printf("HID_RECEIPT case=%d checks=%d failures=%d\n",which,checks,fails);fflush(stdout);_exit(fails?1:0);
|
||||
}
|
||||
int main(void){int fail=0;for(int i=0;i<5;i++){pid_t p=fork();if(!p)exercise(i);int s;waitpid(p,&s,0);fail+=!WIFEXITED(s)||WEXITSTATUS(s)!=0;}printf("HID_RECEIPT %s cases=5 failures=%d\n",fail?"FAIL":"PASS",fail);return !!fail;}
|
||||
@@ -0,0 +1,148 @@
|
||||
// HID脚本单测:假时钟逐帧推进,真实解析DM_KEYS、真实GetNpad路径;不睡眠、不按时长跳步骤。
|
||||
// Begin是动作开始/重复触发,End标记动作结束:两个Begin只需同一动作的一次End。
|
||||
// HID script unit test: a fake clock advances frame by frame, with real DM_KEYS parsing and the real GetNpad path; no sleeping, no skipping steps by duration.
|
||||
// Begin is action start/repeat trigger and End marks action end: two Begins need only one End of the same action.
|
||||
#ifndef HLE_HID_SOURCE
|
||||
#define HLE_HID_SOURCE "../hle_hid.c"
|
||||
#endif
|
||||
#include <signal.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
#include HLE_HID_SOURCE
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
static uint64_t clock_ns = 1000000000ull;
|
||||
static uint64_t guest_frame;
|
||||
static uint64_t server_tick;
|
||||
static int server_available;
|
||||
uint64_t now_ns(void) { return clock_ns; }
|
||||
uint64_t guest_ns(void) { return clock_ns; }
|
||||
uint64_t dm_guest_frame(void) { return guest_frame; }
|
||||
uint64_t dm_server_tick(void) { return server_available ? server_tick : UINT64_MAX; }
|
||||
int touch_fill(void *out, uint64_t max) { (void)out; (void)max; return 0; }
|
||||
static int test_loadscreen_up, hold_requests;
|
||||
int dm_loadscreen_up(void) { return test_loadscreen_up; } // 真判定在 diag.c;单测手动置位 | the real check is in diag.c; the unit test sets it by hand
|
||||
void dm_hold_for_loadscreen(void) { hold_requests++; } // 真实现冻结客体时钟;单测只数请求次数 | the real implementation freezes the guest clock; the unit test only counts requests
|
||||
int dm_opmode(void) { return 1; }
|
||||
void dm_touch_set(const dm_touch *t, int n) { (void)t; (void)n; }
|
||||
static void (*ui_cb)(const char *, const char *, const char *);
|
||||
void uimsg_subscribe(void (*f)(const char *, const char *, const char *)) { ui_cb = f; }
|
||||
static int checks, fails;
|
||||
#define CHECK(c, s) do { checks++; int ok = !!(c); fails += !ok; printf("%s %s\n", ok ? "✓" : "✗", s); } while (0)
|
||||
static void setup(const char *script) {
|
||||
memset(g_steps, 0, sizeof g_steps); memset(g_keys, 0, sizeof g_keys);
|
||||
g_nsteps = g_nkeys = g_kcur = g_ktries = g_kbeg = g_kend = 0; g_kstate = KS_PRE; g_krel = 1;
|
||||
clock_ns = 1000000000ull; guest_frame = 0; server_tick = 0; server_available = 1; setenv("DM_KEYS", script, 1); keys_parse();
|
||||
}
|
||||
static void setup_pregame(const char *script) {
|
||||
memset(g_steps, 0, sizeof g_steps); memset(g_keys, 0, sizeof g_keys);
|
||||
g_nsteps = g_nkeys = g_kcur = g_ktries = g_kbeg = g_kend = 0; g_kstate = KS_PRE; g_krel = 1;
|
||||
clock_ns = 1000000000ull; guest_frame = 0; server_tick = 0; server_available = 0; setenv("DM_KEYS", script, 1); keys_parse();
|
||||
}
|
||||
static void ui(const char *act) { ui_cb("InputMessage", act, ""); }
|
||||
static NpadState read_state(void) { NpadState s; fill(&s, 0, STYLE_FULLKEY); return s; }
|
||||
static int neutral(NpadState s) { return !s.buttons && !s.lx && !s.ly; }
|
||||
static void release(void) { guest_frame += ACTION_HOLD_TICKS; server_tick += ACTION_HOLD_TICKS; read_state(); }
|
||||
static void frames(uint64_t n) { guest_frame += n; server_tick += n; read_state(); }
|
||||
int main(int argc, char **argv) {
|
||||
unsetenv("DM_KEYS"); hid_keys_init();
|
||||
setup("LSL@+0.05,LSU@+0.05");
|
||||
NpadState s = read_state(); CHECK(s.lx == -32767 && s.ly == 0 && s.buttons == 0, "首步LSL送入真手柄布局,不进按钮位");
|
||||
ui("ControllerActionBegin"); ui("ControllerActionBegin"); release();
|
||||
CHECK(neutral(read_state()), "两个Begin尚未End时,下一步仍不放行");
|
||||
ui("ControllerActionEnd"); s = read_state();
|
||||
CHECK(s.ly == 32767 && s.lx == 0, "两个重复Begin/一次End后,下一步LSU放行");
|
||||
|
||||
setup("A@+0.05,B@+0.05"); CHECK(read_state().buttons == DM_BTN_A, "普通A按下");
|
||||
ui("ControllerActionBegin"); release();
|
||||
CHECK(neutral(read_state()), "单次Begin未End不放下一键");
|
||||
ui("ControllerActionEnd"); CHECK(read_state().buttons == DM_BTN_B, "End后才发B,不吞键");
|
||||
|
||||
setup("A@+0.6"); CHECK(read_state().buttons == DM_BTN_A, "按住时长测试先按下A");
|
||||
clock_ns += 60000000000ull; guest_frame += 15 - 1; server_tick += 15 - 1; // +0.6 秒 = 0.6×25 = 15 拍 | +0.6 seconds = 0.6*25 = 15 ticks
|
||||
CHECK(read_state().buttons == DM_BTN_A, "墙钟跳跃但客体帧未到点时A仍按住");
|
||||
guest_frame++; server_tick++; CHECK(neutral(read_state()), "服务端拍到点后A才松开");
|
||||
|
||||
setup("LSL@+0.05,LSU@+0.05"); read_state(); release();
|
||||
CHECK(read_state().ly == 32767, "局内未出现Begin:松开即空闲,不等不存在的End");
|
||||
|
||||
setup("A@+0.05,B@+0.05"); read_state(); ui("ControllerActionBegin"); ui("ControllerActionEnd"); ui("ControllerActionBegin"); release();
|
||||
CHECK(neutral(read_state()), "End后又有新Begin:重新忙,旧End不替新动作放行");
|
||||
ui("ControllerActionEnd"); CHECK(read_state().buttons == DM_BTN_B, "新动作自己的End后放行");
|
||||
|
||||
setup("A@+0.05,B@+0.05"); read_state(); ui("ControllerActionEnd"); ui("ControllerActionEnd"); ui("ControllerActionBegin"); release();
|
||||
CHECK(neutral(read_state()), "先到的多余End不能抵消后来Begin");
|
||||
ui("ControllerActionEnd"); CHECK(read_state().buttons == DM_BTN_B, "后来Begin结束后可继续");
|
||||
|
||||
setup("A@>OpenPanel:Done,B@+0.05"); read_state(); ui("ControllerActionBegin"); ui("ControllerActionBegin");
|
||||
ui_cb("PanelManager", "OpenPanel", "Done");
|
||||
CHECK(neutral(read_state()), "按住期间确认会松开,但动作未End仍等空闲");
|
||||
ui("ControllerActionEnd"); CHECK(read_state().buttons == DM_BTN_B, "确认后的重复Begin只需一End,再放B");
|
||||
|
||||
setup("A@+0.05,B@%0.2+0.05"); read_state(); ui("ControllerActionBegin"); ui("ControllerActionBegin"); release(); ui("ControllerActionEnd");
|
||||
CHECK(neutral(read_state()), "End不跳过脚本原定延时");
|
||||
frames(4); CHECK(neutral(read_state()), "服务端延时 4 拍未到 5 拍时不放下一键");
|
||||
frames(1); CHECK(read_state().buttons == DM_BTN_B, "服务端延时到 5 拍且动作结束才放下一键");
|
||||
release(); CHECK(neutral(read_state()), "末步松开后无额外按键");
|
||||
|
||||
setup("A@>Never"); read_state(); release();
|
||||
frames(OK_WAIT_TICKS - ACTION_HOLD_TICKS - 1); CHECK(g_ktries == 1 && neutral(read_state()), "确认等待 150 服务端拍前不重按");
|
||||
frames(1); CHECK(g_ktries == 2 && read_state().buttons == DM_BTN_A, "确认等待满 150 服务端拍才重按");
|
||||
|
||||
setup_pregame("A@%0.2"); read_state(); frames(11); CHECK(neutral(read_state()), "主菜单出图帧延时 11/12 帧不提前按键");
|
||||
frames(1); CHECK(read_state().buttons == DM_BTN_A, "主菜单出图帧延时满 12 帧才按键");
|
||||
|
||||
pid_t short_hold = fork();
|
||||
if (!short_hold) { setup("A@+0.01"); _exit(read_state().buttons == 0 ? 0 : 99); }
|
||||
int short_status; waitpid(short_hold, &short_status, 0);
|
||||
CHECK(WIFEXITED(short_status) && WEXITSTATUS(short_status) == 0, "反例:按住不足 1 服务端拍,真实读数越线为未采到");
|
||||
|
||||
pid_t child = fork();
|
||||
if (!child) { setup("A@>Never"); read_state(); release(); clock_ns += 60000000000ull; read_state(); _exit(99); }
|
||||
int status; waitpid(child, &status, 0);
|
||||
CHECK(WIFSIGNALED(status) && WTERMSIG(status) == SIGABRT, "客体帧不动但墙钟 60 秒只走兜底报红");
|
||||
|
||||
setup("A@Start>OpenPanel:Done,B@>OpenPanel:Next");
|
||||
ui_cb("PanelManager", "OpenPanel", "Done"); ui_cb("PanelManager", "OpenPanel", "Start");
|
||||
CHECK(read_state().buttons == DM_BTN_A && g_kcur == 0, "按下前的旧确认不完成当前步");
|
||||
ui("ControllerActionBegin"); ui("ControllerActionBegin"); ui_cb("PanelManager", "OpenPanel", "Done");
|
||||
ui_cb("PanelManager", "OpenPanel", "Next");
|
||||
CHECK(neutral(read_state()), "下一步尚未按下时的旧确认不能跳步,仍等前一动作End");
|
||||
ui("ControllerActionEnd");
|
||||
CHECK(read_state().buttons == DM_BTN_B && g_kcur == 1, "前一End后下一步真按B,旧Next确认不算完成");
|
||||
ui_cb("PanelManager", "OpenPanel", "Next");
|
||||
CHECK(neutral(read_state()) && g_kcur == 2, "下一步按下后的新鲜确认才完成并松手");
|
||||
if (argc > 1) {
|
||||
FILE *f = fopen(argv[1], "r"); if (!f) { perror("trace"); return 2; }
|
||||
setup("LSL@+8,LSU@+8"); read_state(); char line[2048]; int entered = 0, nb = 0, ne = 0;
|
||||
while (fgets(line, sizeof line, f)) {
|
||||
if (strstr(line, "hid 脚本步 3 按下")) entered = 1;
|
||||
if (!entered) continue;
|
||||
double t;
|
||||
if (sscanf(line, "[dm] UIMSG [%lfs]", &t) != 1) continue;
|
||||
int beg = strstr(line, "InputMessage ControllerActionBegin") != NULL;
|
||||
int end = strstr(line, "InputMessage ControllerActionEnd") != NULL;
|
||||
if (!beg && !end) continue;
|
||||
clock_ns = 1000000000ull + (uint64_t)((t - 16.13) * 1e9); read_state();
|
||||
ui(beg ? "ControllerActionBegin" : "ControllerActionEnd"); nb += beg; ne += end;
|
||||
if (end) break;
|
||||
}
|
||||
fclose(f); s = read_state();
|
||||
CHECK(nb == 73 && ne == 1 && s.ly == 32767, "iOS原始步3轨迹73 Begin/1 End回放后进入LSU(假时钟按消息时间推进)");
|
||||
}
|
||||
// 冻结拍(DM_TICK_HOLD)期间拍号不前进:前置在局内拍时钟下见到,随后宿主报「无拍」,%1 须改按出图帧 60 帧走完(host_savecmp 死等 451 s)
|
||||
// During a tick freeze (DM_TICK_HOLD) the tick number does not advance: the precondition was seen under the in-game tick clock, then the host reports "no tick", and %1 must be finished by presented frames instead, 60 frames (host_savecmp waited 451 s dead)
|
||||
setup("A@OpenPanel:PauseLayout%1>PausePanelMessage:ExitGame"); server_tick = 401; guest_frame = 1000;
|
||||
ui_cb("PanelManager", "OpenPanel", "PauseLayout"); CHECK(neutral(read_state()), "冻结前见到前置,延时未到不按");
|
||||
server_available = 0; read_state();
|
||||
guest_frame += 59; CHECK(neutral(read_state()), "冻结后按帧计:59 帧未到 1 秒不按");
|
||||
guest_frame += 1; CHECK(read_state().buttons == DM_BTN_A, "冻结后按帧计:满 60 帧(1 秒)按下A,不因拍号停住死等");
|
||||
// 读取画面还开着时到点的局内按键:不按、请求冻结拍;撤下后才按(画面闸门 NPC 页:拍 84 的 A 被读取画面吃掉)
|
||||
// An in-game key press that comes due while the loading screen is still up: do not press, request a tick freeze; press only after it is down (screenshot gate NPC page: the A at tick 84 was swallowed by the loading screen)
|
||||
setup("A@DM:Tick:84#>OpenPanel:NpcDialogPanel"); server_tick = 84; test_loadscreen_up = 1; hold_requests = 0;
|
||||
ui_cb("DM", "Tick", "84#"); CHECK(neutral(read_state()) && hold_requests == 1, "读取画面开着:前置到了也不按 A,并请求冻结拍");
|
||||
frames(30); CHECK(neutral(read_state()) && hold_requests >= 2, "读取画面仍开着:继续不按");
|
||||
test_loadscreen_up = 0; hold_requests = 0; CHECK(read_state().buttons == DM_BTN_A && hold_requests == 0, "读取画面撤下:按下 A,不再请求冻结");
|
||||
setup("A@DM:Tick:84#>OpenPanel:NpcDialogPanel"); server_tick = 84; test_loadscreen_up = 0; hold_requests = 0;
|
||||
ui_cb("DM", "Tick", "84#"); CHECK(read_state().buttons == DM_BTN_A && hold_requests == 0, "读取画面本来就撤了:到点即按,不请求冻结(时序不变)");
|
||||
printf("== HID脚本 %d 项,失败 %d ==\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// 底栏死亡隐藏单测:模式 → 已死、底栏显隐判定(dm_hud.h)。期望值按游戏代码手写:main+0x6e5c48 玩家模式 0 / 0x11 即已死
|
||||
// Unit test for hiding the bottom bar on death: mode -> dead, bottom bar show/hide decision (dm_hud.h). Expected values are hand-written from the game code: main+0x6e5c48 player mode 0 / 0x11 means dead
|
||||
#include <stdio.h>
|
||||
#include "dm_hud.h"
|
||||
static int fails, cases;
|
||||
static void expect(const char *what, int got, int want) {
|
||||
cases++; if (got == want) printf("✓ %s\n", what); else { fails++; printf("✗ %s:得 %d,期望 %d\n", what, got, want); }
|
||||
}
|
||||
int main(void) {
|
||||
char buf[64];
|
||||
for (unsigned m = 0; m <= 19; m++) { // D2 玩家模式 0..19(DEATH … KNOCKBACK) | D2 player modes 0..19 (DEATH ... KNOCKBACK)
|
||||
snprintf(buf, sizeof buf, "模式 %u %s", m, (m == 0 || m == 17) ? "→ 已死" : "→ 活着");
|
||||
expect(buf, dm_hud_player_mode_dead(m), m == 0 || m == 17);
|
||||
}
|
||||
expect("模式 0xffffffff(越界)→ 活着", dm_hud_player_mode_dead(0xffffffffu), 0);
|
||||
dm_hud_info h = {0}; h.valid = 1;
|
||||
for (unsigned m = 0; m <= 19; m++) {
|
||||
h.dead = dm_hud_player_mode_dead(m);
|
||||
snprintf(buf, sizeof buf, "局内常态 模式 %u → 底栏%s", m, (m == 0 || m == 17) ? "隐藏" : "显示");
|
||||
expect(buf, dm_hud_bar_visible(&h, 0, 0), !(m == 0 || m == 17));
|
||||
}
|
||||
h.dead = 0;
|
||||
expect("活着但导航态 → 隐藏", dm_hud_bar_visible(&h, 1, 0), 0);
|
||||
expect("活着但面板挡住 → 隐藏", dm_hud_bar_visible(&h, 0, 1), 0);
|
||||
h.valid = 0; expect("未读到玩家 → 隐藏", dm_hud_bar_visible(&h, 0, 0), 0);
|
||||
printf("%s t_hud_dead %d/%d\n", fails ? "FAIL" : "OK", cases - fails, cases);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// dm_i18n.c 的语言来源(UIKit 文字用):游戏设过语言(SetLanguage 观测门写 g_dm_lang)以它为准;没设过读存档 Settings/Settings.json 的 "Language";
|
||||
// 没有设置文件 = 首次安装,按系统语言(测试用 DM_LANG 模拟)。我们的字:zhCN、zhTW 用中文,其余英文。
|
||||
// 期望值来自规则本身(8 zhCN / 9 zhTW 中文,其余英文;语言号表见 diag.c 名表 main+0x20ae478),不跑游戏。每个情形单独起进程(文件读一次就缓存),所以本程序按 argv 跑一个情形,Makefile 逐个调。
|
||||
// Language source of dm_i18n.c (for UIKit text): once the game has set the language (the SetLanguage observation gate writes g_dm_lang), that value
|
||||
// wins; if not, read "Language" from Settings/Settings.json in the save data;
|
||||
// no settings file = first install, use the system language (simulated in tests with DM_LANG). Our text: Chinese for zhCN and zhTW, English for
|
||||
// everything else.
|
||||
// Expected values come from the rule itself (8 zhCN / 9 zhTW are Chinese, everything else is English; for the language index table see the name table at
|
||||
// main+0x20ae478 in diag.c), without running the game. Each case needs its own process (the file is read once and then cached), so this program runs one
|
||||
// case per argv and the Makefile invokes them one by one.
|
||||
#include "../dm_i18n.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
static int fails;
|
||||
static void expect(const char *what, const char *got, const char *want) { int ok = !strcmp(got, want); if (!ok) fails++; printf("%s %s:期望「%s」→ 真结果「%s」\n", ok ? "✓" : "✗", what, want, got); }
|
||||
int main(int argc, char **argv) {
|
||||
const char *mode = argc > 1 ? argv[1] : "";
|
||||
char dir[512]; snprintf(dir, sizeof dir, "%s/i18n_%s", getenv("TMPDIR") ? getenv("TMPDIR") : "/tmp", mode);
|
||||
char sd[600], f[700]; snprintf(sd, sizeof sd, "%s/Settings", dir); snprintf(f, sizeof f, "%s/Settings.json", sd);
|
||||
mkdir(dir, 0755); mkdir(sd, 0755); remove(f); setenv("DM_SAVE", dir, 1);
|
||||
if (!strcmp(mode, "en") || !strcmp(mode, "game")) { FILE *o = fopen(f, "w"); fputs("{\n \"Item Name Display\": 1,\n \"Language\": 0,\n \"AutoMapMode\": 2\n}\n", o); fclose(o); }
|
||||
if (!strcmp(mode, "zh")) { FILE *o = fopen(f, "w"); fputs("{ \"Language\": 8 }", o); fclose(o); }
|
||||
if (!strcmp(mode, "en")) expect("设置文件 Language 0、游戏还没设", dm_ui("dmConfirm"), "OK");
|
||||
else if (!strcmp(mode, "zh")) expect("设置文件 Language 8", dm_ui("dmConfirm"), "确定");
|
||||
else if (!strcmp(mode, "none")) { unsetenv("DM_LANG"); expect("没有设置文件、没给系统语言(Mac 缺省 zh-Hans)", dm_ui("dmConfirm"), "确定"); }
|
||||
else if (!strcmp(mode, "sysen")) { setenv("DM_LANG", "en-US", 1); expect("没有设置文件(首次安装)、系统语言 en-US", dm_ui("dmConfirm"), "OK"); }
|
||||
else if (!strcmp(mode, "systw")) { setenv("DM_LANG", "zh-Hant-TW", 1); expect("没有设置文件、系统语言 zh-Hant-TW(繁体用中文)", dm_ui("dmConfirm"), "确定"); }
|
||||
else if (!strcmp(mode, "tags")) { // 语言标记 → 原版语言号 | language tag → the original game's language index
|
||||
static const struct { const char *t; int want; } c[] = { { "en-US", 0 }, { "en-GB", 0 }, { "zh-Hans-CN", 8 }, { "zh-Hans", 8 }, { "zh", 8 }, { "zh-Hans-HK", 8 }, { "zh-Hans-TW", 8 }, { "zh-Hans-MO", 8 },
|
||||
{ "zh-Hant-TW", 8 }, { "zh-Hant-HK", 8 }, { "zh-Hant", 8 }, { "zh-HK", 8 }, { "zh_TW", 8 }, { "yue-Hant-HK", 8 }, { "yue-Hans-CN", 8 }, { "yue", 8 }, { "wuu-Hans-CN", 8 },
|
||||
{ "de-DE", 0 }, { "es-ES", 0 }, { "es-419", 0 }, { "fr-CA", 0 }, { "it-IT", 0 }, { "ko-KR", 0 }, { "pl-PL", 0 }, { "ru-RU", 0 }, { "ja-JP", 0 }, { "pt-BR", 0 }, { "nl-NL", 0 }, { "ar", 0 }, { "zu-ZA", 0 } };
|
||||
for (unsigned i = 0; i < sizeof c / sizeof *c; i++) { char w[8], g[8]; snprintf(w, sizeof w, "%d", c[i].want); snprintf(g, sizeof g, "%d", dm_lang_from_tag(c[i].t)); expect(c[i].t, g, w); } }
|
||||
else if (!strcmp(mode, "game")) { // 设置文件写的英文,游戏随后切回简中:以游戏为准;再切到 zhTW(9):简中以外一律英文 | the settings file says English, then the game switches back to Simplified Chinese: the game wins; then switch to zhTW (9): everything other than Simplified Chinese is English
|
||||
expect("游戏没设前按设置文件", dm_ui("dmConfirm"), "OK");
|
||||
atomic_store(&g_dm_lang, 8); expect("游戏切到 zhCN", dm_ui("dmConfirm"), "确定");
|
||||
atomic_store(&g_dm_lang, 9); expect("游戏切到 zhTW(繁体用中文)", dm_ui("dmConfirm"), "确定");
|
||||
atomic_store(&g_dm_lang, 1); expect("游戏切到 deDE(按英文)", dm_ui("dmConfirm"), "OK");
|
||||
expect("表里没有的键原样返回", dm_ui("dmNoSuchKey"), "dmNoSuchKey"); }
|
||||
else { fprintf(stderr, "用法:t_i18n en|zh|none|sysen|systw|tags|game\n"); return 2; }
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// 手柄 / 触屏切换事务单测(秒级):dm_modetx.h 的状态机与输入闸,不碰游戏。期望值都从规则手算:
|
||||
// 重建完成 = 提示面板重开次数动过之后连续 SETTLE 帧不动;TIMEOUT 帧没等到按超时往下走;冻结期间按着过的键放开后要松开过一次才交。
|
||||
// Unit test of the controller / touch switch transaction (takes seconds): the state machine and input gate of dm_modetx.h, without touching the game. Expected values are all computed by hand from the rules:
|
||||
// rebuild complete = SETTLE consecutive frames without movement after the hint panel reopen count has moved; if that has not happened within TIMEOUT frames, proceed as a timeout; keys that were held during the freeze are passed to the game only after they have been released once following the unfreeze.
|
||||
#include <stdio.h>
|
||||
#include "../dm_modetx.h"
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
int main(void) {
|
||||
{ dm_modetx t = {0}; uint64_t f = 100; // 一次正常切换:触屏(0) → 手柄(1) | One normal switch: touch (0) → controller (1)
|
||||
CHECK(dm_modetx_step(&t, f, -1, 0, 7) == DM_TXA_NONE, "没请求不该动");
|
||||
CHECK(dm_modetx_step(&t, f, 0, 0, 7) == DM_TXA_NONE, "想要的就是当前模式不该动");
|
||||
CHECK(dm_modetx_step(&t, f, 1, 0, 7) == DM_TXA_BEGIN && t.st == DM_TX_REBUILD1, "请求另一模式应开始");
|
||||
for (int i = 1; i <= 10; i++) CHECK(dm_modetx_step(&t, f + i, 1, 0, 7) == DM_TXA_NONE, "提示面板没重开前不该往下走(第 %d 帧)", i);
|
||||
CHECK(dm_modetx_step(&t, f + 11, 1, 0, 8) == DM_TXA_NONE, "刚重开那一帧不算完成");
|
||||
CHECK(dm_modetx_step(&t, f + 13, 1, 0, 9) == DM_TXA_NONE, "又重开一次:重新计稳定");
|
||||
CHECK(dm_modetx_step(&t, f + 16, 1, 0, 9) == DM_TXA_NONE, "稳定 3 帧不够");
|
||||
CHECK(dm_modetx_step(&t, f + 17, 1, 0, 9) == DM_TXA_REPORT_BACK && t.st == DM_TX_REBUILD2, "稳定 4 帧 → 报回原运行模式");
|
||||
CHECK(dm_modetx_step(&t, f + 30, 0, 1, 9) == DM_TXA_NONE, "事务中来的反向请求不打断");
|
||||
CHECK(dm_modetx_step(&t, f + 31, 0, 1, 10) == DM_TXA_NONE, "第二次重建刚开始");
|
||||
CHECK(dm_modetx_step(&t, f + 35, 0, 1, 10) == DM_TXA_DONE && t.st == DM_TX_IDLE && !t.timeouts, "第二次重建稳定 → 完成、无超时");
|
||||
CHECK(dm_modetx_step(&t, f + 36, 0, 1, 10) == DM_TXA_BEGIN, "完成后下一帧处理排着的反向请求"); }
|
||||
{ dm_modetx t = {0}; // 超时:提示面板一直没重开 | Timeout: the hint panel never reopens
|
||||
CHECK(dm_modetx_step(&t, 0, 1, 0, 0) == DM_TXA_BEGIN, "开始");
|
||||
CHECK(dm_modetx_step(&t, DM_MODETX_TIMEOUT - 1, 1, 0, 0) == DM_TXA_NONE, "差 1 帧不超时");
|
||||
CHECK(dm_modetx_step(&t, DM_MODETX_TIMEOUT, 1, 0, 0) == DM_TXA_REPORT_BACK && t.timeouts == 1, "到点按超时往下走并记数");
|
||||
CHECK(dm_modetx_step(&t, 2 * DM_MODETX_TIMEOUT - 1, 1, 0, 0) == DM_TXA_NONE, "第二段重新计时");
|
||||
CHECK(dm_modetx_step(&t, 2 * DM_MODETX_TIMEOUT, 1, 0, 0) == DM_TXA_DONE && t.timeouts == 2 && t.st == DM_TX_IDLE, "第二段也超时 → 完成、记 2 次"); }
|
||||
{ dm_modegate g = {0}; uint64_t b; // 输入闸:A=0x1 触发切换并一直按着,途中又按了 B=0x2,松开 B 后再按 | Input gate: A=0x1 triggers the switch and stays held, B=0x2 is also pressed along the way, and after releasing B it is pressed again
|
||||
b = 0x1; CHECK(dm_modegate_apply(&g, 1, &b) == 1 && b == 0, "冻结:键清零、摇杆也清");
|
||||
b = 0x3; CHECK(dm_modegate_apply(&g, 1, &b) == 1 && b == 0, "冻结中新按的键也不交");
|
||||
b = 0x3; CHECK(dm_modegate_apply(&g, 0, &b) == 0 && b == 0, "放开后还按着的 A、B 不交");
|
||||
b = 0x5; CHECK(dm_modegate_apply(&g, 0, &b) == 0 && b == 0x4, "B 松了、A 还按着:新按的 X=0x4 照常交,A 仍不交");
|
||||
b = 0x0; CHECK(dm_modegate_apply(&g, 0, &b) == 0 && b == 0, "全松开");
|
||||
b = 0x3; CHECK(dm_modegate_apply(&g, 0, &b) == 0 && b == 0x3, "松开过之后再按照常交"); }
|
||||
printf("t_modetx: %d 项,%d 失败\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// 过场空播的 WebM 时长解析单测(秒级):手工按 EBML 拼几段容器头,期望值全部手算,不调被测实现。
|
||||
// 编译运行:make -C dm/host/tests run
|
||||
// Unit test for WebM duration parsing of cutscene no-op playback (takes seconds): a few container headers are assembled by hand per EBML, and all expected values are computed by hand without calling the implementation under test.
|
||||
// Build and run: make -C dm/host/tests run
|
||||
#include "../hle.h"
|
||||
#include <stdio.h>
|
||||
|
||||
void *guest_sym(const char *n) { (void)n; return NULL; } // 被测文件里的客体调用桩(解析路径不用) | stub for the guest call in the file under test (not used by the parsing path)
|
||||
struct dm_flags g_flag; uint64_t g_t0_ns;
|
||||
uint64_t now_ns(void) { return 0; } // 日志时间戳桩(解析路径不用) | log timestamp stub (not used by the parsing path)
|
||||
typedef int64_t (*mv_read_fn)(void *ctx, int64_t off, void *buf, size_t n);
|
||||
int64_t mv_webm_duration_ns(mv_read_fn rd, void *ctx);
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } else { printf(" ✓ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
typedef struct { const uint8_t *p; size_t n; } mem;
|
||||
static int64_t rd_mem(void *c_, int64_t off, void *buf, size_t n) {
|
||||
mem *c = c_; if (off < 0 || (size_t)off >= c->n) return 0;
|
||||
size_t k = c->n - off < n ? c->n - off : n; memcpy(buf, c->p + off, k); return (int64_t)k;
|
||||
}
|
||||
static int64_t dur(const uint8_t *p, size_t n) { mem m = {p, n}; return mv_webm_duration_ns(rd_mem, &m); }
|
||||
|
||||
int main(void) {
|
||||
// ① 正常:EBML 头(空体) + Segment(已知长度) { SeekHead(空) , Info { TimecodeScale=1000000, Duration=float64 6633.0 } }
|
||||
// 6633.0 的 IEEE754 双精度 = 0x40B9E90000000000;期望 6633.0 × 1000000 ns = 6,633,000,000 ns(= ffprobe 测 logoloop 的 6.633 s)
|
||||
// (1) Normal: EBML header (empty body) + Segment (known length) { SeekHead (empty) , Info { TimecodeScale=1000000, Duration=float64 6633.0 } }
|
||||
// IEEE754 double of 6633.0 = 0x40B9E90000000000; expected 6633.0 * 1000000 ns = 6,633,000,000 ns (= the 6.633 s ffprobe measures for logoloop)
|
||||
static const uint8_t a[] = {
|
||||
0x1A,0x45,0xDF,0xA3, 0x80, // EBML,长 0 | EBML, length 0
|
||||
0x18,0x53,0x80,0x67, 0x9C, // Segment,长 28 = 5 + 5 + 18 | Segment, length 28 = 5 + 5 + 18
|
||||
0x11,0x4D,0x9B,0x74, 0x80, // SeekHead,长 0 | SeekHead, length 0
|
||||
0x15,0x49,0xA9,0x66, 0x92, // Info,长 18 = 7 + 11 | Info, length 18 = 7 + 11
|
||||
0x2A,0xD7,0xB1, 0x83, 0x0F,0x42,0x40, // TimecodeScale = 0x0F4240 = 1000000
|
||||
0x44,0x89, 0x88, 0x40,0xB9,0xE9,0x00,0x00,0x00,0x00,0x00 // Duration float64 6633.0
|
||||
};
|
||||
CHECK(dur(a, sizeof a) == 6633000000ll, "float64 时长 6633 × 1ms = 6.633 s(读到 %lld)", (long long)dur(a, sizeof a));
|
||||
// ② float32 + 非缺省 TimecodeScale:Duration=float32 2000.0(0x44FA0000),Scale=500000 ⇒ 1,000,000,000 ns;Segment 未知长度(0x01FFFFFFFFFFFFFF)
|
||||
// (2) float32 + non-default TimecodeScale: Duration=float32 2000.0 (0x44FA0000), Scale=500000 => 1,000,000,000 ns; Segment of unknown length (0x01FFFFFFFFFFFFFF)
|
||||
static const uint8_t b[] = {
|
||||
0x1A,0x45,0xDF,0xA3, 0x80,
|
||||
0x18,0x53,0x80,0x67, 0x01,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
|
||||
0x15,0x49,0xA9,0x66, 0x8E, // Info,长 14 = 7 + 7 | Info, length 14 = 7 + 7
|
||||
0x2A,0xD7,0xB1, 0x83, 0x07,0xA1,0x20, // 0x07A120 = 500000
|
||||
0x44,0x89, 0x84, 0x44,0xFA,0x00,0x00 // float32 2000.0
|
||||
};
|
||||
CHECK(dur(b, sizeof b) == 1000000000ll, "float32 2000 × 0.5ms + 未知长度 Segment = 1.000 s(读到 %lld)", (long long)dur(b, sizeof b));
|
||||
// ③ 缺省 TimecodeScale(Info 里没有):Duration=float64 10033.0(0x40C3988000000000)⇒ 10,033,000,000 ns
|
||||
// (3) Default TimecodeScale (absent from Info): Duration=float64 10033.0 (0x40C3988000000000) => 10,033,000,000 ns
|
||||
static const uint8_t c[] = {
|
||||
0x1A,0x45,0xDF,0xA3, 0x80,
|
||||
0x18,0x53,0x80,0x67, 0x90,
|
||||
0x15,0x49,0xA9,0x66, 0x8B,
|
||||
0x44,0x89, 0x88, 0x40,0xC3,0x98,0x80,0x00,0x00,0x00,0x00
|
||||
};
|
||||
CHECK(dur(c, sizeof c) == 10033000000ll, "缺省 TimecodeScale = 1ms,10033 ⇒ 10.033 s(读到 %lld)", (long long)dur(c, sizeof c));
|
||||
// ④ 先遇到 Cluster、没有 Info ⇒ -1(调用方据此报红,不给缺省值)
|
||||
// (4) Cluster encountered first, no Info => -1 (the caller reports a failure on this and gives no default)
|
||||
static const uint8_t d[] = { 0x1A,0x45,0xDF,0xA3, 0x80, 0x18,0x53,0x80,0x67, 0x85, 0x1F,0x43,0xB6,0x75, 0x80 };
|
||||
CHECK(dur(d, sizeof d) == -1, "无 Info 先到 Cluster ⇒ -1(读到 %lld)", (long long)dur(d, sizeof d));
|
||||
// ⑤ Info 里没有 Duration ⇒ -1
|
||||
// (5) No Duration in Info => -1
|
||||
static const uint8_t e[] = { 0x1A,0x45,0xDF,0xA3, 0x80, 0x18,0x53,0x80,0x67, 0x8C, 0x15,0x49,0xA9,0x66, 0x87, 0x2A,0xD7,0xB1, 0x83, 0x0F,0x42,0x40 };
|
||||
CHECK(dur(e, sizeof e) == -1, "无 Duration ⇒ -1(读到 %lld)", (long long)dur(e, sizeof e));
|
||||
// ⑥ 截断(Segment 头之后没数据)⇒ -1
|
||||
// (6) Truncated (no data after the Segment header) => -1
|
||||
CHECK(dur(a, 10) == -1, "截断 ⇒ -1");
|
||||
printf(fails ? "t_movie 失败 %d/%d\n" : "t_movie 全过:%d/%d\n", fails ? fails : checks, checks);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// 起名随机名单测(秒级):dm_namegen.c。判据:连续留空建 20 次角色,名字全不同、都合法。
|
||||
// 「建过的角色」用 taken 桩模拟:每抽出一个就记进已有名单,下一次抽到它算重名。合法 = 游戏起名规则(main+0x7fed78):2–15 字节、首尾是字母、- _ 至多一个;我们的名字只该含英文字母。
|
||||
// Unit test for random names at character naming (takes seconds): dm_namegen.c. Criterion: create a character 20 times in a row with the name left blank, and the names are all different and all valid.
|
||||
// "Characters already created" are simulated with the taken stub: each name drawn is recorded in the existing list, and drawing it the next time counts as a duplicate. Valid = the game's naming rule (main+0x7fed78): 2–15 bytes, first and last are letters, at most one of - _; our names should contain only English letters.
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
int dm_name_gen(char *out, int cap, int (*taken)(const char *));
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
static char have[20][32]; static int nhave;
|
||||
static int taken(const char *n) { for (int i = 0; i < nhave; i++) if (!strcasecmp(have[i], n)) return 1; return 0; } // 存档目录在大小写不敏感的文件系统上 | the save directory is on a case-insensitive file system
|
||||
static int all_taken(const char *n) { (void)n; return 1; }
|
||||
static int legal(const char *n) { size_t l = strlen(n); if (l < 2 || l > 15) return 0; for (size_t i = 0; i < l; i++) if (!((n[i] >= 'A' && n[i] <= 'Z') || (n[i] >= 'a' && n[i] <= 'z'))) return 0; return 1; }
|
||||
|
||||
int main(void) {
|
||||
for (int i = 0; i < 20; i++) { char nm[32]; int ok = dm_name_gen(nm, sizeof nm, taken); CHECK(ok, "第 %d 次没抽到", i + 1); CHECK(legal(nm), "第 %d 次「%s」不合法", i + 1, nm); CHECK(!taken(nm), "第 %d 次「%s」与已建角色重名", i + 1, nm); strcpy(have[nhave++], nm); }
|
||||
printf(" 20 次:%s %s %s … %s\n", have[0], have[1], have[2], have[19]);
|
||||
int bad = 0; for (int i = 0; i < 100000; i++) { char nm[32]; dm_name_gen(nm, sizeof nm, NULL); bad += !legal(nm); } CHECK(!bad, "10 万次里 %d 个不合法", bad);
|
||||
char nm[32]; CHECK(!dm_name_gen(nm, sizeof nm, all_taken), "全部重名时应返回 0");
|
||||
printf("t_namegen: %d 项,%d 失败\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// oe状态通知单测:不消费时同一类型只留首次排位;弹出后新变化重新排队。
|
||||
// 三种消息仅通知「查询当前状态」,不携带历史值。期望顺序/状态手写,不由实现生成。
|
||||
// oe state notification unit test: when not consumed, each type keeps only its first queue position; after a pop a new change is queued again.
|
||||
// The three messages only signal "query the current state" and carry no historical value. Expected order/state are hand-written, not generated by the implementation.
|
||||
#ifndef HLE_OE_SOURCE
|
||||
#define HLE_OE_SOURCE "../hle_oe.c"
|
||||
#endif
|
||||
#include HLE_OE_SOURCE
|
||||
#include <signal.h>
|
||||
#include <sys/wait.h>
|
||||
uint64_t now_ns(void) { return 0; }
|
||||
// 3D 渲染比例(scale3d_tick)的外部依赖:单测里没有模块表与图形层,桩成「没有 main 模块」→ 该函数直接返回
|
||||
// External dependencies of the 3D render scale (scale3d_tick): the unit test has no module table or graphics layer, so they are stubbed as "no main module" -> the function returns immediately
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
void dm_guest_write_prepare(void *a, size_t n) { (void)a; (void)n; }
|
||||
uint64_t dm_nvn_frame_count(void) { return 0; }
|
||||
int dm_nvn_ruler_truth(void) { return 0; }
|
||||
int dm_ingame_now(void) { return 1; }
|
||||
int mtl_fps_target(void) { return 60; } // 目标帧率(nvn_mtl.m):单测里恒为 60,30 帧档的用例直接给 period_ms | target frame rate (nvn_mtl.m): always 60 in the unit test, and the 30 fps mode cases pass period_ms directly
|
||||
pthread_key_t g_keyres[2]; // 分辨率参数位(loader.c)的桩:没建键,取走 31 时不写线程槽 | stub for the resolution parameter slot (loader.c): no key created, so taking 31 does not write the thread slot
|
||||
uint64_t dm_game_res(int docked) { (void)docked; return 0; } // 出图分辨率(dm_uiscreen.c)的桩 | stub for the render resolution (dm_uiscreen.c)
|
||||
void dm_uiscreen_res_reread(void) {}
|
||||
static int checks, fails;
|
||||
#define CHECK(c, s) do { checks++; int ok = !!(c); fails += !ok; printf("%s %s\n", ok ? "✓" : "✗", s); } while (0)
|
||||
static void reset(void) { g_mqh = g_mqn = 0; g_focus = 1; g_opmode = 1; g_ntf_opmode = g_ntf_perfmode = 0; }
|
||||
static int pop_is(uint32_t want) { uint32_t m = 999; return h_oe_TryPopMsg(&m) && m == want; }
|
||||
static int empty(void) { uint32_t m = 999; return !h_oe_TryPopMsg(&m) && m == 999; }
|
||||
static int child_kind;
|
||||
static void abort_exit(int sig) { (void)sig; dprintf(2, "【红】t_oe child kind=%d:10 秒看门狗超时\n", child_kind); _exit(97); } // 子进程旧版die可核,避免产生崩溃报告或core | the old-version die in the child process can be checked, avoiding a crash report or core
|
||||
static void *focus_burst(void *p) { (void)p; for (int i = 0; i < 17; i++) { dm_focus_set(2); dm_focus_set(1); } return NULL; }
|
||||
static void *mode_burst(void *p) { (void)p; for (int i = 0; i < 17; i++) dm_set_opmode(i % 2); return NULL; }
|
||||
static pthread_mutex_t stage_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t stage_cond = PTHREAD_COND_INITIALIZER;
|
||||
static int stage, interleaved_ok;
|
||||
static void stage_set(int n) { pthread_mutex_lock(&stage_lock); stage = n; pthread_cond_broadcast(&stage_cond); pthread_mutex_unlock(&stage_lock); }
|
||||
static void stage_wait(int n) { pthread_mutex_lock(&stage_lock); while (stage < n) pthread_cond_wait(&stage_cond, &stage_lock); pthread_mutex_unlock(&stage_lock); }
|
||||
static void *consume_interleaved(void *p) {
|
||||
(void)p; stage_wait(1); int ok = pop_is(15); stage_set(2); // 已弹出,尚未查询:精确让生产者在此更新 | popped but not yet queried: let the producer update exactly here
|
||||
stage_wait(3); interleaved_ok = ok && h_oe_GetFocus() == 1 && pop_is(15) && pop_is(30) && pop_is(31) && empty() && h_oe_GetOpMode() == 0 && h_oe_GetPerfMode() == 0;
|
||||
return NULL;
|
||||
}
|
||||
static int child_burst(int kind) {
|
||||
fflush(stdout); pid_t p = fork(); if (p < 0) return 0;
|
||||
if (!p) {
|
||||
child_kind = kind; signal(SIGABRT, abort_exit); signal(SIGALRM, abort_exit); alarm(10); reset();
|
||||
g_ntf_opmode = g_ntf_perfmode = 1;
|
||||
if (kind == 0) { focus_burst(NULL); _exit(h_oe_GetFocus() == 1 && pop_is(15) && empty() ? 0 : 1); }
|
||||
if (kind == 1) { mode_burst(NULL); _exit(h_oe_GetOpMode() == 0 && h_oe_GetPerfMode() == 0 && pop_is(30) && pop_is(31) && empty() ? 0 : 1); }
|
||||
if (kind == 3) {
|
||||
pthread_t c; pthread_create(&c, NULL, consume_interleaved, NULL);
|
||||
dm_focus_set(2); stage_set(1); stage_wait(2);
|
||||
dm_focus_set(1); dm_set_opmode(0); stage_set(3); pthread_join(c, NULL);
|
||||
_exit(interleaved_ok ? 0 : 1);
|
||||
}
|
||||
pthread_t f, m; pthread_create(&f, NULL, focus_burst, NULL); pthread_create(&m, NULL, mode_burst, NULL);
|
||||
pthread_join(f, NULL); pthread_join(m, NULL);
|
||||
uint32_t msg; int nf = 0, no = 0, np = 0, order = 1;
|
||||
while (h_oe_TryPopMsg(&msg)) { if (msg == 15) nf++; else if (msg == 30) no++; else if (msg == 31) { order &= no == 1; np++; } else order = 0; }
|
||||
_exit(nf == 1 && no == 1 && np == 1 && order && h_oe_GetFocus() == 1 && h_oe_GetOpMode() == 0 ? 0 : 1);
|
||||
}
|
||||
int st; if (waitpid(p, &st, 0) != p) return 0;
|
||||
return WIFEXITED(st) && WEXITSTATUS(st) == 0;
|
||||
}
|
||||
// 动态 3D 比例控制器(scale3d_ctl_step,纯函数):期望值按规则手算,不由实现生成(规则见 hle_oe.c:2 秒窗帧率;连两窗 < 目标 ×0.92 降;连 10 窗 ≥ ×0.97 升;刚升 10 秒内掉 → 下次升要 30 窗)
|
||||
// Dynamic 3D scale controller (scale3d_ctl_step, a pure function): expected values are computed by hand from the rules, not generated by the implementation (rules in hle_oe.c: frame rate over 2-second windows; two consecutive windows < target *0.92 steps down; 10 consecutive windows >= *0.97 steps up; a drop within 10 seconds of stepping up -> the next step-up needs 30 windows)
|
||||
static uint64_t s3_now; static scale3d_ctl s3; static int s3_dm; // s3_dm:累计换级次数 | s3_dm: cumulative number of level changes
|
||||
static int s3_one(double iv) { int b = s3.level; s3_now += (uint64_t)((iv > 0 ? iv : 16.6667) * 1e6); int lv = scale3d_ctl_step(&s3, iv, s3_now); s3_dm += lv != b; return lv; }
|
||||
static int s3_n(int n, double iv) { int lv = s3.level; for (int i = 0; i < n; i++) lv = s3_one(iv); return lv; }
|
||||
#define F60 16.6667 // 60 帧:每窗 120 帧(120 × 16.6667 = 2000.004 ms) | 60 fps: 120 frames per window (120 * 16.6667 = 2000.004 ms)
|
||||
// 真机实玩第二段每 10 秒窗的「25 ms 档 / ≥33 ms 档」帧数(手抄自 perf 行)
|
||||
// Frame counts of the "25 ms bucket / >=33 ms bucket" for each 10-second window of the second section of real play on a real device (copied by hand from perf lines)
|
||||
static const int s3_rows[18][2] = {{0,1},{2,4},{3,3},{0,0},{10,12},{0,0},{0,0},{0,0},{2,1},{0,0},{6,8},{0,0},{0,0},{0,0},{2,3},{5,4},{0,0},{0,0}};
|
||||
static int s3_replay(int clustered) { // clustered = 1:每 10 秒的慢帧挤在开头连续出现(最坏情况);0:均匀散开。返回换级次数 | clustered = 1: the slow frames of each 10 seconds are packed consecutively at the start (worst case); 0: spread evenly. Returns the number of level changes
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 5000 * S3_SEC; s3_dm = 0;
|
||||
for (int r = 0; r < 18; r++) { int ns = s3_rows[r][0] + s3_rows[r][1], every = ns ? 600 / ns : 0;
|
||||
for (int i = 0; i < 600; i++) { int slow = clustered ? i < ns : (ns && i % every == 0 && i / every < ns); s3_one(slow ? (i % 2 ? 25.0 : 40.0) : F60); } }
|
||||
return s3_dm;
|
||||
}
|
||||
static void test_scale3d(void) {
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 1000 * S3_SEC;
|
||||
CHECK(s3_n(1200, F60) == 0, "动态比例:60 帧稳 20 秒 → 保持 0 级");
|
||||
CHECK(s3_n(199, 20.0) == 0, "动态比例:50 帧(< 55.2)第 1 个窗 + 第 2 个窗差 1 帧 → 还没降");
|
||||
CHECK(s3_n(1, 20.0) == 1, "动态比例:连续两个 2 秒窗都 50 帧 → 降到 1 级");
|
||||
CHECK(s3_n(100, 20.0) == 1, "动态比例:换级后 2 秒内的帧不计(照样 50 帧也不降)");
|
||||
CHECK(s3_n(200, 20.0) == 2, "动态比例:停判结束后再连两窗 50 帧 → 降到 2 级");
|
||||
CHECK(s3_n(1000, 25.0) == 2, "动态比例:已到下限,再掉也停在 2 级");
|
||||
s3 = (scale3d_ctl){.max_level = 2, .level = 2}; s3_now = 1500 * S3_SEC; // 从干净的 2 级起测升档(不带上一段留在窗里的半个差窗) | test stepping up from a clean level 2 (without the half bad window the previous section left in the window)
|
||||
CHECK(s3_n(1199, F60) == 2, "动态比例:60 帧连续 9 个窗多 → 还不升");
|
||||
CHECK(s3_n(1, F60) == 1, "动态比例:连续 10 个窗(20 秒)≥ 58.2 → 升到 1 级");
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 2000 * S3_SEC;
|
||||
for (int k = 0; k < 10; k++) { s3_n(100, 20.0); s3_n(120, F60); }
|
||||
CHECK(s3.level == 0, "动态比例:差窗与好窗交替(从不连两窗差)→ 不降");
|
||||
s3 = (scale3d_ctl){.max_level = 2, .level = 1}; s3_now = 2500 * S3_SEC;
|
||||
CHECK(s3_n(1200 * 3, 1000.0 / 57) == 1, "动态比例:57 帧(介于 55.2 与 58.2 之间)60 秒 → 不降也不升");
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 3000 * S3_SEC;
|
||||
s3_n(90, F60); s3_one(500.0); s3_n(120 * 3, F60);
|
||||
CHECK(s3.level == 0, "动态比例:窗里一次 500 ms 长卡顿(该窗约 45 帧)、下一窗正常 → 不降(要连两窗)");
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 3500 * S3_SEC; int lv = 0;
|
||||
for (int i = 0; i < 2000; i++) lv = s3_one(i % 4 == 0 ? -1 : F60);
|
||||
CHECK(lv == 0, "动态比例:被系统丢弃的帧(−1)不计数,其余照 60 帧 → 不降");
|
||||
for (int i = 0; i < 2000; i++) lv = s3_one(0);
|
||||
CHECK(lv == 0, "动态比例:全是无读数(0)的帧 → 不动");
|
||||
// 防抖:刚升上去 10 秒内又被打回 → 下次升要 30 窗(60 秒)
|
||||
// Debounce: knocked back down within 10 seconds of stepping up -> the next step-up needs 30 windows (60 seconds)
|
||||
s3 = (scale3d_ctl){.max_level = 2, .level = 1}; s3_now = 4000 * S3_SEC;
|
||||
CHECK(s3_n(1200, F60) == 0, "防抖:20 秒好窗 → 升到 0 级");
|
||||
s3_n(120, F60); // 换级后停判 2 秒 | judging is suspended for 2 seconds after a level change
|
||||
CHECK(s3_n(200, 20.0) == 1, "防抖:升上去后约 6 秒内连两窗 50 帧 → 打回 1 级");
|
||||
s3_n(120, F60);
|
||||
CHECK(s3_n(2400, F60) == 1, "防抖:刚升又掉,之后好窗 40 秒 → 不升(要 60 秒)");
|
||||
CHECK(s3_n(1200, F60) == 0, "防抖:好窗满 60 秒 → 升到 0 级");
|
||||
s3_n(120, F60); s3_n(120 * 6, F60); // 升上去 12 秒(> 10 秒)后才掉 | drops only 12 seconds (> 10 seconds) after stepping up
|
||||
CHECK(s3_n(200, 20.0) == 1, "防抖:升上去 12 秒后才掉 → 降到 1 级");
|
||||
s3_n(120, F60);
|
||||
CHECK(s3_n(1200, F60) == 0, "防抖:不算刚升又掉,20 秒好窗即升回");
|
||||
// 30 帧档:目标 30,降线 27.6、升线 29.1
|
||||
// 30 fps mode: target 30, step-down line 27.6, step-up line 29.1
|
||||
s3 = (scale3d_ctl){.max_level = 2, .period_ms = 1000.0 / 30}; s3_now = 6000 * S3_SEC;
|
||||
CHECK(s3_n(600, 33.34) == 0, "30 帧档:33.34 ms(每窗 60 帧)稳 20 秒 → 保持 0 级");
|
||||
CHECK(s3_n(100, 40.0) == 1, "30 帧档:25 帧(< 27.6)连两窗 → 降到 1 级");
|
||||
// 注入:rds 局把一段帧的间隔当 25 ms(40 帧)
|
||||
// Injection: the rds run treats the interval of a stretch of frames as 25 ms (40 fps)
|
||||
s3 = (scale3d_ctl){.max_level = 2}; s3_now = 7000 * S3_SEC;
|
||||
CHECK(s3_n(160, 25.0) == 1 && s3_n(80, 25.0) == 1 && s3_n(160, 25.0) == 2, "注入 25 ms:4 秒降到 1 级,停判 2 秒后再 4 秒降到 2 级");
|
||||
s3_n(120, F60);
|
||||
CHECK(s3_n(1200, F60) == 1 && (s3_n(120, F60), s3_n(1200, F60)) == 0, "注入结束:每 20 秒升一级,回到 0 级");
|
||||
int a = s3_replay(0), b = s3_replay(1);
|
||||
printf(" (实玩第二段回放:慢帧均匀散开换级 %d 次,挤在一起换级 %d 次;旧控制器真机上 12 次)\n", a, b);
|
||||
CHECK(a == 0 && b == 0, "动态比例:实玩第二段的慢帧序列(帧率 59+)不论散开还是挤在一起都不换级");
|
||||
}
|
||||
int main(void) {
|
||||
test_scale3d();
|
||||
unsetenv("DM_OE_SCRIPT"); reset();
|
||||
CHECK(empty(), "初始空队列:返回false且不改输出");
|
||||
dm_focus_set(1); dm_set_opmode(1); CHECK(empty(), "相同状态不发通知");
|
||||
dm_focus_set(3); CHECK(h_oe_GetFocus() == 3, "消费前即可查询后台状态3");
|
||||
CHECK(pop_is(15) && empty(), "后台变化通知15恰一次");
|
||||
dm_focus_set(2); dm_focus_set(1);
|
||||
CHECK(pop_is(15) && empty() && h_oe_GetFocus() == 1, "未消费的失焦/恢复合并,查询最终焦点1");
|
||||
reset(); g_ntf_opmode = g_ntf_perfmode = 1;
|
||||
dm_focus_set(2); dm_set_opmode(0); dm_focus_set(3); dm_set_opmode(1);
|
||||
CHECK(pop_is(15) && pop_is(30) && pop_is(31) && empty(), "三类首次排位FIFO=15,30,31,重复不挪位");
|
||||
CHECK(h_oe_GetFocus() == 3 && h_oe_GetOpMode() == 1 && h_oe_GetPerfMode() == 1, "重复通知不保存陈旧值,查询最新3/1/1");
|
||||
reset(); g_ntf_opmode = g_ntf_perfmode = 1;
|
||||
dm_set_opmode(0); dm_focus_set(2); dm_set_opmode(1);
|
||||
CHECK(pop_is(30) && pop_is(31) && pop_is(15) && empty(), "模式先变化时FIFO=30,31,15,成对顺序不变");
|
||||
reset(); g_ntf_opmode = g_ntf_perfmode = 1;
|
||||
dm_focus_set(2); CHECK(pop_is(15), "先弹出焦点通知");
|
||||
dm_set_opmode(0); dm_focus_set(1);
|
||||
CHECK(pop_is(30) && pop_is(31) && pop_is(15) && empty(), "弹出后的恢复再次通知并排在待取模式消息之后");
|
||||
CHECK(h_oe_GetFocus() == 1, "恢复后的当前焦点=1");
|
||||
reset(); dm_set_opmode(0);
|
||||
CHECK(empty() && h_oe_GetOpMode() == 0, "通知关闭只更新状态、不入队");
|
||||
h_oe_SetOpModeNtf(0x100); h_oe_SetPerfModeNtf(0x101); dm_set_opmode(1);
|
||||
CHECK(pop_is(31) && empty(), "通知bool只读低8位,性能单开只发31");
|
||||
h_oe_SetOpModeNtf(0x101); h_oe_SetPerfModeNtf(0x100); dm_set_opmode(0);
|
||||
CHECK(pop_is(30) && empty(), "运行模式单开只发30");
|
||||
reset(); mq_push(16); mq_push(16);
|
||||
CHECK(pop_is(16) && pop_is(16) && empty(), "逐次事件16不合并,保留两次FIFO");
|
||||
reset(); g_ntf_opmode = g_ntf_perfmode = 1; dm_set_opmode(0);
|
||||
CHECK(pop_is(30), "模式对中先消费30,31尚未消费");
|
||||
dm_set_opmode(1);
|
||||
CHECK(pop_is(31) && pop_is(30) && empty() && h_oe_GetOpMode() == 1, "消费跨新变化:旧31保留排位,已弹30重新排队,最终模式1");
|
||||
CHECK(child_burst(0), "34次焦点变化跨旧32槽,不终止且最终恢复1/一条15");
|
||||
CHECK(child_burst(1), "17次模式变化跨旧32槽,不终止且最终0/30,31");
|
||||
CHECK(child_burst(2), "两生产者并发,各类恰一条、30先于31、最终焦点1/模式0");
|
||||
reset(); g_ntf_opmode = g_ntf_perfmode = 1; int rotated = 1;
|
||||
for (int i = 0; i < 31; i++) { dm_focus_set(2 - i % 2); rotated &= pop_is(15) && empty(); }
|
||||
CHECK(rotated, "31次逐条消费,把环头推进到尾槽");
|
||||
dm_focus_set(1); dm_set_opmode(0); dm_focus_set(3); dm_set_opmode(1);
|
||||
CHECK(pop_is(15) && pop_is(30) && pop_is(31) && empty(), "跨32槽回绕后仍按15,30,31去重并保持首次顺序");
|
||||
CHECK(child_burst(3), "消费者弹出后、查询前发生新变化:新恢复不漏通知,最终焦点1/模式0");
|
||||
printf("== oe %d 项,失败 %d ==\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// 实体手柄面键映射(dm_padmap.h):各类型 × 四个面键 → 游戏键。期望值按规则手写:印什么字母就是游戏的什么键;任天堂键帽 右 A 下 B 上 X 左 Y,Xbox 键帽 下 A 右 B 左 X 上 Y;别的按 Xbox 排。
|
||||
// Physical controller face button mapping (dm_padmap.h): each type x four face buttons -> game keys. Expected values are hand-written from
|
||||
// the rule: whatever letter is printed is that game key; Nintendo glyphs are right A, bottom B, top X, left Y, Xbox glyphs are bottom A,
|
||||
// right B, left X, top Y; everything else is laid out as Xbox.
|
||||
#include <stdio.h>
|
||||
#include "../dm_padmap.h"
|
||||
static int checks, fails;
|
||||
#define CHECK(c, ...) do { checks++; if (c) printf(" ✓ "); else { fails++; printf(" ✗ "); } printf(__VA_ARGS__); printf("\n"); } while (0)
|
||||
int main(void) {
|
||||
struct { const char *cat, *ven; int kind; } id[] = {
|
||||
{ "Switch Pro Controller", "Pro Controller", DM_PADKIND_NINTENDO }, { "Nintendo Switch Joy-Con (L/R)", "Joy-Con (L/R)", DM_PADKIND_NINTENDO },
|
||||
{ "Nintendo Switch Joy-Con (L)", "Joy-Con (L)", DM_PADKIND_NINTENDO }, { "MFi", "NINTENDO compatible pad", DM_PADKIND_NINTENDO },
|
||||
{ "Xbox One", "Xbox Wireless Controller", DM_PADKIND_XBOX }, { "DualSense", "DualSense Wireless Controller", DM_PADKIND_XBOX },
|
||||
{ "DualShock 4", "DUALSHOCK 4 Wireless Controller", DM_PADKIND_XBOX }, { "MFi", "SteelSeries Nimbus", DM_PADKIND_XBOX }, { NULL, NULL, DM_PADKIND_XBOX }, { "", "", DM_PADKIND_XBOX } };
|
||||
for (unsigned i = 0; i < sizeof id / sizeof *id; i++) CHECK(dm_padmap_kind(id[i].cat, id[i].ven) == id[i].kind, "类别「%s」厂商名「%s」→ %s 排法", id[i].cat ? id[i].cat : "(空)", id[i].ven ? id[i].ven : "(空)", id[i].kind ? "任天堂" : "Xbox");
|
||||
// 下 右 左 上
|
||||
// bottom right left top
|
||||
CHECK(dm_padmap_face(DM_PADKIND_NINTENDO, 1, 0, 0, 0) == DM_BTN_B, "任天堂:下 = B"); CHECK(dm_padmap_face(DM_PADKIND_NINTENDO, 0, 1, 0, 0) == DM_BTN_A, "任天堂:右 = A");
|
||||
CHECK(dm_padmap_face(DM_PADKIND_NINTENDO, 0, 0, 1, 0) == DM_BTN_Y, "任天堂:左 = Y"); CHECK(dm_padmap_face(DM_PADKIND_NINTENDO, 0, 0, 0, 1) == DM_BTN_X, "任天堂:上 = X");
|
||||
CHECK(dm_padmap_face(DM_PADKIND_XBOX, 1, 0, 0, 0) == DM_BTN_A, "Xbox:下 = A"); CHECK(dm_padmap_face(DM_PADKIND_XBOX, 0, 1, 0, 0) == DM_BTN_B, "Xbox:右 = B");
|
||||
CHECK(dm_padmap_face(DM_PADKIND_XBOX, 0, 0, 1, 0) == DM_BTN_X, "Xbox:左 = X"); CHECK(dm_padmap_face(DM_PADKIND_XBOX, 0, 0, 0, 1) == DM_BTN_Y, "Xbox:上 = Y");
|
||||
CHECK(dm_padmap_face(DM_PADKIND_XBOX, 1, 1, 0, 0) == (DM_BTN_A | DM_BTN_B), "两颗同时按:各算各的"); CHECK(dm_padmap_face(DM_PADKIND_NINTENDO, 0, 0, 0, 0) == 0, "都没按 = 0");
|
||||
printf("== %d 项,失败 %d ==\n", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#include "../romfs_validate.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
static int check(int ok, const char *s) { if (!ok) fprintf(stderr, "失败:%s\n", s); return ok; }
|
||||
int main(void) {
|
||||
const char *src = getenv("DM_ROMFS"); if (!src) src = getenv("HOME");
|
||||
if (!src) return 1;
|
||||
char cmd[4096], why[512], rep[2048], sd[4096]; snprintf(sd, sizeof sd, "%s/data", src);
|
||||
if (!check(dm_romfs_validate(sd, why, sizeof why), "原版 RomFS 合格")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
if (!check(dm_romfs_report(sd, rep, sizeof rep) == 0, "完整清单:原版 RomFS 无缺")) return 1;
|
||||
{ // 空目录:18 个档案一个都没有。期望值取自 romfs_validate.c 的 need / size 两张表:00-00000001.data 1073741824 字节 = 1.00 GB、17-00000002.data 4496514 字节 = 4 MB | Empty directory: none of the 18 archives is present. Expected values come from the need / size tables in romfs_validate.c: 00-00000001.data 1073741824 bytes = 1.00 GB, 17-00000002.data 4496514 bytes = 4 MB
|
||||
char r1[] = "/tmp/dm-romfs-test.XXXXXX"; if (!mkdtemp(r1)) return 1;
|
||||
if (!check(!dm_romfs_validate(r1, why, sizeof why) && !strcmp(why, "缺少 00-00000001.data"), "空目录被拒,报第一个档案")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
int bad = dm_romfs_report(r1, rep, sizeof rep);
|
||||
if (!check(bad == 18 && strstr(rep, "已有 0 / 18") && strstr(rep, "00-00000001.data(1.00 GB)") && strstr(rep, "17-00000002.data(4 MB)") && !strstr(rep, "没拷完"), "完整清单:缺 18 个逐个列出")) { fprintf(stderr, "%s\n", rep); return 1; }
|
||||
// 配置、密钥、清单这些小文件不在核对范围里:放一份内容不对的进去,结论与给玩家的清单都不变,清单里不出现它们的名字
|
||||
// Small files such as the config, key and manifests are outside the scope of the check: put in a copy with wrong contents, and neither the verdict nor
|
||||
// the list shown to the player changes, and their names do not appear in the list
|
||||
snprintf(cmd, sizeof cmd, "printf bad > '%s/.build.config' && printf x > '%s/build_key.txt' && printf x > '%s/archive_manifest.psv'", r1, r1, r1); if (system(cmd)) return 1;
|
||||
bad = dm_romfs_report(r1, rep, sizeof rep);
|
||||
if (!check(bad == 18 && !strstr(rep, "build") && !strstr(rep, "psv"), "完整清单:不提小文件")) { fprintf(stderr, "%s\n", rep); return 1; }
|
||||
snprintf(cmd, sizeof cmd, "rm -rf '%s'", r1); system(cmd);
|
||||
}
|
||||
{ // 只有档案文件(没有配置、密钥、任何清单)就合格;再核字节数与剔零档案:用符号链接搭一份,把一个小档案截短 / 换成「剔零 + 区段表」 | Archive files alone (no config, key or any manifest) are enough to pass; then check byte counts and zero-stripped archives: build a copy with symlinks, then truncate one small archive / replace it with "zero-stripped + extent table"
|
||||
char r2[] = "/tmp/dm-romfs-size.XXXXXX"; if (!mkdtemp(r2)) return 1;
|
||||
snprintf(cmd, sizeof cmd, "for f in '%s'/data/*.data; do ln -s \"$f\" '%s/' || exit 1; done", src, r2); if (system(cmd)) return 1;
|
||||
if (!check(dm_romfs_validate(r2, why, sizeof why), "只有档案文件的目录合格")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
snprintf(cmd, sizeof cmd, "rm '%s/04-00000002.data' && head -c 1000000 '%s/data/04-00000002.data' > '%s/04-00000002.data'", r2, src, r2); if (system(cmd)) return 1;
|
||||
if (!check(!dm_romfs_validate(r2, why, sizeof why) && strstr(why, "还没拷完"), "拷到一半的档案被拒")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
int bad = dm_romfs_report(r2, rep, sizeof rep);
|
||||
if (!check(bad == 1 && strstr(rep, "已有 17 / 18") && strstr(rep, "没拷完:04-00000002.data(1 MB / 9 MB)"), "完整清单:没拷完的单列,带现有 / 应有(1000000 字节 = 1 MB、8915855 字节 = 9 MB,按 1048576 折算取整)")) { fprintf(stderr, "%s\n", rep); return 1; }
|
||||
snprintf(cmd, sizeof cmd, "printf 'size 8915855\\n1000000 7915855\\n' > '%s/04-00000002.data.holes'", r2); if (system(cmd)) return 1;
|
||||
if (!check(dm_romfs_validate(r2, why, sizeof why), "剔零档案(前 1000000 字节 + 区段表)合格")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
snprintf(cmd, sizeof cmd, "printf 'size 8915855\\n1000000 100\\n' > '%s/04-00000002.data.holes'", r2); if (system(cmd)) return 1;
|
||||
if (!check(!dm_romfs_validate(r2, why, sizeof why) && strstr(why, "还没拷完"), "区段表与实际长度对不上被拒")) { fprintf(stderr, "%s\n", why); return 1; }
|
||||
snprintf(cmd, sizeof cmd, "rm -rf '%s'", r2); system(cmd);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// swkbd 单测(秒级):按 SDK 布局手工摆一个 ShowKeyboardArg,经 swkbd_show 回写 String,期望字节全部手算。
|
||||
// 编译运行:cd dm/host/tests && clang -O1 -I.. -o /tmp/t_swkbd t_swkbd.c ../hle_swkbd.c && /tmp/t_swkbd
|
||||
// swkbd unit test (takes seconds): lay out a ShowKeyboardArg by hand following the SDK layout, have swkbd_show write back the String, and all expected bytes are computed by hand.
|
||||
// Build and run: cd dm/host/tests && clang -O1 -I.. -o /tmp/t_swkbd t_swkbd.c ../hle_swkbd.c && /tmp/t_swkbd
|
||||
#include "../hle.h"
|
||||
#include <stdio.h>
|
||||
|
||||
Result swkbd_show(void *out, const void *arg, int (*input)(const char *, const char *, const char *, const char *, int, char *, int));
|
||||
void dm_ui_text_entered(const char *text) { (void)text; } // 真实现在 dm_cursor.c(起名页输完自动接受) | the real implementation is in dm_cursor.c (the naming page auto-accepts once input is finished)
|
||||
int front_text_input(const char *t, const char *s, const char *g, const char *i, int m, char *o, int c) { (void)t; (void)s; (void)g; (void)i; (void)m; (void)o; (void)c; return -1; }
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
// 输入桩:记下收到的参数,按设定返回
|
||||
// Input stub: record the arguments received and return as configured
|
||||
static const char *g_reply; static int g_ret, g_called; static char g_title[256], g_init[256]; static int g_max;
|
||||
static int stub(const char *t, const char *s, const char *g, const char *i, int m, char *o, int c) {
|
||||
(void)s; (void)g; g_called++; snprintf(g_title, sizeof g_title, "%s", t); snprintf(g_init, sizeof g_init, "%s", i); g_max = m;
|
||||
if (g_ret > 0) snprintf(o, c, "%s", g_reply);
|
||||
return g_ret;
|
||||
}
|
||||
|
||||
static uint8_t arg[0x500], work[0x1000], sbuf[0x7d4];
|
||||
static struct { uint8_t *p; uint64_t n; } str = {sbuf, sizeof sbuf};
|
||||
static void mkarg(int utf8, int maxlen, const uint16_t *init, int ilen) {
|
||||
memset(arg, 0, sizeof arg); memset(work, 0, sizeof work); memset(sbuf, 0xAA, sizeof sbuf);
|
||||
static const uint16_t title[] = {0x8D77, 0x540D, 0}; // 「起名」 | 「起名」(Name your character)
|
||||
memcpy(arg + 0x24, title, sizeof title);
|
||||
memcpy(arg + 0x3ac, &maxlen, 4); arg[0x3bd] = (uint8_t)utf8;
|
||||
int off = 0x14; memcpy(arg + 0x3c0, &off, 4); memcpy(arg + 0x3c4, &ilen, 4); // SetInitialTextUtf8 的写法 | the way SetInitialTextUtf8 writes it
|
||||
memcpy(work + off, init, (size_t)ilen * 2);
|
||||
uint8_t *w = work; memcpy(arg + 0x4d0, &w, 8);
|
||||
g_called = 0;
|
||||
}
|
||||
static int bytes_eq(const uint8_t *want, size_t n) { // 前 n 字节等于期望,其后到缓冲末尾全 0 | the first n bytes equal the expectation, and everything after to the end of the buffer is 0
|
||||
if (memcmp(sbuf, want, n)) return 0;
|
||||
for (size_t i = n; i < sizeof sbuf; i++) if (sbuf[i]) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
void guest_clock_freeze_for(int reason, int on) { (void)reason; (void)on; } // 真实现在 hle_os.c;单测不关心时钟 | the real implementation is in hle_os.c; the unit test does not care about the clock
|
||||
int main(void) {
|
||||
unsetenv("DM_KBD");
|
||||
static const uint16_t hero[] = {'H', 'e', 'r', 'o'};
|
||||
|
||||
printf("1 确定、UTF-8 输出(游戏实际用法)\n");
|
||||
mkarg(1, 16, hero, 4); g_ret = 1; g_reply = "Ünï名";
|
||||
Result r = swkbd_show(&str, arg, stub);
|
||||
static const uint8_t w1[] = {0xC3, 0x9C, 0x6E, 0xC3, 0xAF, 0xE5, 0x90, 0x8D, 0x00}; // Ü n ï 名 + 结尾 0 | U+00DC n U+00EF U+540D + terminating 0
|
||||
CHECK(r == 0, "Result %#x 期望 0", r);
|
||||
CHECK(bytes_eq(w1, sizeof w1), "UTF-8 回写字节不符");
|
||||
CHECK(!strcmp(g_title, "\xE8\xB5\xB7\xE5\x90\x8D"), "标题解出「%s」期望「起名」", g_title);
|
||||
CHECK(!strcmp(g_init, "Hero"), "初始文本解出「%s」期望 Hero", g_init);
|
||||
CHECK(g_max == 16, "上限 %d 期望 16", g_max);
|
||||
|
||||
printf("2 取消 → 0x29F,缓冲不动\n");
|
||||
mkarg(1, 16, hero, 4); g_ret = 0;
|
||||
r = swkbd_show(&str, arg, stub);
|
||||
CHECK(r == 0x29F, "Result %#x 期望 0x29F", r);
|
||||
CHECK(sbuf[0] == 0xAA && sbuf[sizeof sbuf - 1] == 0xAA, "取消时改了缓冲");
|
||||
|
||||
printf("3 无窗口(输入返回 -1)→ 按取消 0x29F\n");
|
||||
mkarg(1, 16, hero, 4); g_ret = -1;
|
||||
CHECK(swkbd_show(&str, arg, stub) == 0x29F, "无窗口未按取消返回");
|
||||
|
||||
printf("4 UTF-16 输出(isUseUtf8 = 0)\n");
|
||||
mkarg(0, 16, hero, 0); g_ret = 1; g_reply = "A名";
|
||||
r = swkbd_show(&str, arg, stub);
|
||||
static const uint8_t w4[] = {0x41, 0x00, 0x0D, 0x54, 0x00, 0x00}; // 'A' U+540D 结尾 0(小端) | 'A' U+540D terminating 0 (little endian)
|
||||
CHECK(r == 0 && bytes_eq(w4, sizeof w4), "UTF-16 回写字节不符");
|
||||
CHECK(g_init[0] == 0, "初始长度 0 时应无初始文本");
|
||||
|
||||
printf("5 最大长度截断(3 字)\n");
|
||||
mkarg(1, 3, hero, 4); g_ret = 1; g_reply = "ABCDE";
|
||||
swkbd_show(&str, arg, stub);
|
||||
static const uint8_t w5[] = {'A', 'B', 'C', 0};
|
||||
CHECK(bytes_eq(w5, sizeof w5), "截断结果不符");
|
||||
|
||||
printf("6 截断不拆代理对(上限 2 单元,a + U+1F600 需 3 单元)\n");
|
||||
mkarg(1, 2, hero, 4); g_ret = 1; g_reply = "a\xF0\x9F\x98\x80";
|
||||
swkbd_show(&str, arg, stub);
|
||||
static const uint8_t w6[] = {'a', 0};
|
||||
CHECK(bytes_eq(w6, sizeof w6), "代理对被拆或未截断");
|
||||
|
||||
printf("7 DM_KBD 直给文本:不调输入框\n");
|
||||
setenv("DM_KBD", "Kbd", 1);
|
||||
mkarg(1, 16, hero, 4); g_ret = 0;
|
||||
r = swkbd_show(&str, arg, stub);
|
||||
static const uint8_t w7[] = {'K', 'b', 'd', 0};
|
||||
CHECK(r == 0 && bytes_eq(w7, sizeof w7) && g_called == 0, "DM_KBD 路径不符(调用输入框 %d 次)", g_called);
|
||||
unsetenv("DM_KBD");
|
||||
|
||||
printf("%s:%d/%d\n", fails ? "红" : "全过", checks - fails, checks);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// 自动选怪单测:在本进程内存里摆假单位 / 假怪物数据,调观测门回调,核分数调整(期望值手算,不调被测实现算)。
|
||||
// 布局:单位 +0 类型、+4 类号、+0x10 → 怪物数据(+0x1A TypeFlag:0x02 超级独特 / 0x04 冠军 / 0x08 独特 / 0x10 随从)。
|
||||
// Automatic monster targeting unit test: lay out fake units / fake monster data in this process's memory, call the observation gate callback, and check the score adjustment (expected values computed by hand, not by calling the implementation under test).
|
||||
// Layout: unit +0 type, +4 class number, +0x10 -> monster data (+0x1A TypeFlag: 0x02 super unique / 0x04 champion / 0x08 unique / 0x10 minion).
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
int gate_obs_present(int id) { (void)id; return 1; }
|
||||
static void (*g_fn)(const uint64_t *);
|
||||
void gate_obs_set(int id, void (*fn)(const uint64_t *)) { (void)id; g_fn = fn; }
|
||||
void target_rank_install(void);
|
||||
static int fails, cases;
|
||||
static float run(const void *unit, float score) {
|
||||
uint64_t frame[100] = {0}; frame[1] = (uint64_t)(uintptr_t)unit; frame[2] = 1;
|
||||
memcpy(&frame[32], &score, 4); g_fn(frame);
|
||||
float out; memcpy(&out, &frame[32], 4); return out;
|
||||
}
|
||||
static void expect(const char *what, float got, float want) {
|
||||
cases++; if (got == want) printf("✓ %s(%g)\n", what, got); else { fails++; printf("✗ %s:得 %g,期望 %g\n", what, got, want); }
|
||||
}
|
||||
int main(void) {
|
||||
target_rank_install();
|
||||
uint8_t data[0x40] = {0};
|
||||
struct { uint32_t type, cls, id, mode; uint64_t data; } unit = {1, 5, 77, 0, (uint64_t)(uintptr_t)data};
|
||||
expect("普通僵尸(类 5、TypeFlag 0)分数不变", run(&unit, 0.5f), 0.5f);
|
||||
data[0x1a] = 0x10; expect("随从(0x10)算普通", run(&unit, 0.5f), 0.5f);
|
||||
data[0x1a] = 0x04; expect("冠军(0x04)+1000", run(&unit, 0.5f), 1000.5f);
|
||||
data[0x1a] = 0x08; expect("独特(0x08)+1000", run(&unit, 0.25f), 1000.25f);
|
||||
data[0x1a] = 0x02; expect("超级独特(0x02)+1000", run(&unit, 0.75f), 1000.75f);
|
||||
data[0x1a] = 0; unit.cls = 156; expect("安达利尔(类 156,boss=1)+2000", run(&unit, 0.5f), 2000.5f);
|
||||
unit.cls = 745; expect("3.3 新 Boss 巨像(类 745)+2000", run(&unit, 0.125f), 2000.125f);
|
||||
unit.cls = 5; unit.type = 0; data[0x1a] = 0x08; expect("玩家单位(类型 0)不动", run(&unit, 0.5f), 0.5f);
|
||||
unit.type = 1; unit.data = 0; data[0x1a] = 0; expect("怪物数据指针空:读不到,不动", run(&unit, 0.5f), 0.5f);
|
||||
expect("候选单位空指针不动", run(NULL, 0.5f), 0.5f);
|
||||
// 跨档:精英最差分(0.01+1000)仍高于普通最好分(0.99);Boss 最差分高于精英最好分
|
||||
// Across tiers: the worst elite score (0.01+1000) is still higher than the best normal score (0.99); the worst Boss score is higher than the best elite score
|
||||
unit.data = (uint64_t)(uintptr_t)data; data[0x1a] = 0x04; float elite = run(&unit, 0.01f);
|
||||
data[0x1a] = 0; unit.cls = 211; float boss = run(&unit, 0.01f);
|
||||
cases++; if (elite > 0.99f && boss > 1000.99f) printf("✓ 跨档优先:精英 %g > 普通 0.99,Boss %g > 精英 1000.99\n", elite, boss); else { fails++; printf("✗ 跨档优先\n"); }
|
||||
printf("%s:%d/%d\n", fails ? "【红】自动选怪" : "自动选怪 全绿", cases - fails, cases);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// dm_textbox_core 单测:期望全部手写。U+E07E = EE 81 BE。
|
||||
// 判据:表里的注释版整串 / 子串换成文字框版;表外的串(含原版自带的带码串、不带码的串)逐字节不动;没有表时一律不动。
|
||||
// dm_textbox_core unit test: all expectations are hand-written. U+E07E = EE 81 BE.
|
||||
// Criterion: whole strings / substrings of the annotated version found in the table are replaced by the text box version; strings outside the table (including the original game's own coded strings and strings without codes) are untouched byte for byte; with no table nothing is touched.
|
||||
#include "../dm_textbox_core.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define C "\xee\x81\xbe"
|
||||
static int fails, checks;
|
||||
static void expect(const char *what, const char *in, int want_k, const char *want) {
|
||||
char *o; size_t on; int k = dm_textbox_rewrite(in, strlen(in), &o, &on); checks++;
|
||||
int ok = k == want_k && (want ? (o && on == strlen(want) && !memcmp(o, want, on)) : !o);
|
||||
if (!ok) { fails++; printf("✗ %s:得到 k=%d「%.*s」\n", what, k, o ? (int)on : 0, o ? o : ""); } else printf("✓ %s\n", what);
|
||||
free(o);
|
||||
}
|
||||
int main(void) {
|
||||
char path[] = "/tmp/t_textbox_XXXXXX"; int fd = mkstemp(path); FILE *f = fdopen(fd, "w");
|
||||
fprintf(f, "# 注释版\t文字框版\n");
|
||||
fprintf(f, "%s\t%s\n", C "5[强伤60-70%]\\n" C "4死亡之铲", "死亡之铲"); // 范围行 + 名字 | range line + name
|
||||
fprintf(f, "%s\t%s\n", C "1怀特之脚", "怀特之脚"); // 红叶名字色 | Hongye mod name color
|
||||
fclose(f);
|
||||
expect("没有表:带码串不动", C "1怀特之脚", 0, NULL);
|
||||
if (dm_textbox_load(path) != 2) { printf("✗ 读表条数不是 2\n"); return 1; }
|
||||
expect("表里的注释版整串 → 文字框版", C "5[强伤60-70%]\n" C "4死亡之铲", 1, "死亡之铲");
|
||||
expect("红叶名字色整串 → 原名", C "1怀特之脚", 1, "怀特之脚");
|
||||
expect("被拼进长句的注释版只换那一段", "发现编年史物品:" C "1怀特之脚" "!", 2, "发现编年史物品:怀特之脚!");
|
||||
expect("同一句里出现两次都换", C "1怀特之脚" "和" C "1怀特之脚", 2, "怀特之脚和怀特之脚");
|
||||
expect("原版自带的带码串(悄悄话)不在表里:不动", C "0你悄悄地对" C "1某人" C "0说: 你好", 0, NULL);
|
||||
expect("不带码的串:不动", "死亡之铲", 0, NULL);
|
||||
expect("多行原版文字(不带码):不动", "第一行\n第二行", 0, NULL);
|
||||
expect("像注释但表里没有的:不动", C "5[强伤1-2%]\n" C "4死亡之铲", 0, NULL);
|
||||
unlink(path); dm_textbox_reset();
|
||||
expect("清表后:不动", C "1怀特之脚", 0, NULL);
|
||||
printf("TEXTBOX %s checks=%d failures=%d\n", fails ? "FAIL" : "PASS", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// 触屏单测:dm_touch_set → touch_fill,写出的 TouchScreenState<16>(0x290 字节)与手算的期望逐字节对上。
|
||||
// 期望值按布局手写(采样号 / 触点数 / 每点 delta_time 属性 finger_id x y 直径 转角),不调被测实现算。
|
||||
// Touchscreen unit test: dm_touch_set -> touch_fill, and the TouchScreenState<16> written out (0x290 bytes) matches the hand-computed expectation byte for byte.
|
||||
// Expected values are hand-written by layout (sample number / touch count / per point delta_time attribute finger_id x y diameter rotation angle), not computed by calling the implementation under test.
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdint.h>
|
||||
typedef struct { uint32_t id; float x, y; } dm_touch;
|
||||
void dm_touch_set(const dm_touch *t, int n);
|
||||
int touch_fill(void *out, uint64_t now_ns);
|
||||
static int fails, cases;
|
||||
typedef struct { int64_t dt; uint32_t attr; int32_t fid, x, y; } want_pt;
|
||||
static void expect(const char *what, uint64_t now, int64_t samp, int n, const want_pt *w) {
|
||||
uint8_t got[0x290], exp[0x290]; memset(exp, 0, sizeof exp);
|
||||
int r = touch_fill(got, now);
|
||||
int32_t cnt = n; memcpy(exp, &samp, 8); memcpy(exp + 8, &cnt, 4);
|
||||
for (int i = 0; i < n; i++) {
|
||||
uint8_t *s = exp + 0x10 + 0x28 * i; int32_t d = 30;
|
||||
memcpy(s, &w[i].dt, 8); memcpy(s + 8, &w[i].attr, 4); memcpy(s + 0xc, &w[i].fid, 4);
|
||||
memcpy(s + 0x10, &w[i].x, 4); memcpy(s + 0x14, &w[i].y, 4); memcpy(s + 0x18, &d, 4); memcpy(s + 0x1c, &d, 4);
|
||||
}
|
||||
cases++;
|
||||
int ok = r == n && !memcmp(got, exp, sizeof exp);
|
||||
if (!ok) { fails++; int k = 0; while (k < 0x290 && got[k] == exp[k]) k++; printf("✗ %s:返回 %d(期望 %d),首个不同字节 +%#x(实际 %02x 期望 %02x)\n", what, r, n, k, k < 0x290 ? got[k] : 0, k < 0x290 ? exp[k] : 0); }
|
||||
else printf("✓ %s\n", what);
|
||||
}
|
||||
int main(void) {
|
||||
const uint64_t T0 = 1000000000ull;
|
||||
// 1 按下:id 2 在 (0.5, 0.25) → Start,x = 0.5·1280 = 640,y = 0.25·720 = 180,首读 delta_time = 0
|
||||
// 1 Down: id 2 at (0.5, 0.25) -> Start, x = 0.5*1280 = 640, y = 0.25*720 = 180, delta_time = 0 on the first read
|
||||
dm_touch a = {2, 0.5f, 0.25f}; dm_touch_set(&a, 1);
|
||||
expect("按下报 Start(640, 180)", T0, 1, 1, (want_pt[]){{0, 1, 2, 640, 180}});
|
||||
// 2 移动到 (0.75, 0.5) → 属性 0,x = 960,y = 360,delta_time = 16,666,667 ns
|
||||
// 2 Move to (0.75, 0.5) -> attribute 0, x = 960, y = 360, delta_time = 16,666,667 ns
|
||||
a.x = 0.75f; a.y = 0.5f; dm_touch_set(&a, 1);
|
||||
expect("移动属性 0(960, 360),delta_time 为两次读的间隔", T0 + 16666667, 2, 1, (want_pt[]){{16666667, 0, 2, 960, 360}});
|
||||
// 3 抬起 → End 报在最后位置,下一次读 0 个触点
|
||||
// 3 Lifted -> End reported at the last position, and the next read has 0 touch points
|
||||
dm_touch_set(NULL, 0);
|
||||
expect("抬起报 End(960, 360)", T0 + 33333334, 3, 1, (want_pt[]){{16666667, 2, 2, 960, 360}});
|
||||
expect("End 之后 0 个触点", T0 + 50000001, 4, 0, NULL);
|
||||
// 4 两次读之间按下又抬起(id 0 在 (0.1, 0.1))→ 这次 Start(128, 72),下次 End,再下次空
|
||||
// 4 Down and up between two reads (id 0 at (0.1, 0.1)) -> Start (128, 72) this time, End next time, empty the time after
|
||||
dm_touch b = {0, 0.1f, 0.1f}; dm_touch_set(&b, 1); dm_touch_set(NULL, 0);
|
||||
expect("短按锁存:先报 Start(128, 72)", T0 + 66666668, 5, 1, (want_pt[]){{16666667, 1, 0, 128, 72}});
|
||||
expect("短按锁存:再报 End", T0 + 83333335, 6, 1, (want_pt[]){{16666667, 2, 0, 128, 72}});
|
||||
expect("短按锁存后空", T0 + 100000002, 7, 0, NULL);
|
||||
// 5 夹取:(0.9999, 1.5) → x = min(1279, ⌊0.9999·1280⌋ = 1279),y = min(719, 1080) = 719;(-0.2, -1) → 0, 0
|
||||
// 5 Clamping: (0.9999, 1.5) -> x = min(1279, ⌊0.9999*1280⌋ = 1279), y = min(719, 1080) = 719; (-0.2, -1) -> 0, 0
|
||||
dm_touch c[2] = {{3, 0.9999f, 1.5f}, {4, -0.2f, -1.0f}}; dm_touch_set(c, 2);
|
||||
expect("坐标夹到 [0,1279]×[0,719]", T0 + 116666669, 8, 2, (want_pt[]){{16666667, 1, 3, 1279, 719}, {16666667, 1, 4, 0, 0}});
|
||||
dm_touch_set(NULL, 0); touch_fill((uint8_t[0x290]){0}, T0 + 133333336); // 采样 9:两根 End | sample 9: two End
|
||||
expect("两根 End 之后空", T0 + 150000003, 10, 0, NULL);
|
||||
// 6 两根手指 id 5、1(推送顺序 5 在前)→ 按 id 升序:1 在前
|
||||
// 6 Two fingers id 5 and 1 (pushed with 5 first) -> ascending by id: 1 comes first
|
||||
dm_touch d[2] = {{5, 0.25f, 0.5f}, {1, 0.5f, 0.75f}}; dm_touch_set(d, 2);
|
||||
expect("多指按 id 升序(1:(640,540) 5:(320,360))", T0 + 166666670, 11, 2, (want_pt[]){{16666667, 1, 1, 640, 540}, {16666667, 1, 5, 320, 360}});
|
||||
dm_touch_set(NULL, 0); touch_fill((uint8_t[0x290]){0}, T0 + 183333337); // 采样 12:两根 End | sample 12: two End
|
||||
touch_fill((uint8_t[0x290]){0}, T0 + 200000004); // 采样 13:空 | sample 13: empty
|
||||
// 7 同 id 在 End 报出前重按:id 3 按下(Start)→ 抬起 → 立刻又在 (0.5, 0.5) 按下 → 这次报 End(旧位置),下次报新的 Start
|
||||
// 7 Same id pressed again before End is reported: id 3 down (Start) -> lifted -> immediately down again at (0.5, 0.5) -> this read reports End (old position), the next reports a new Start
|
||||
dm_touch e = {3, 0.25f, 0.25f}; dm_touch_set(&e, 1);
|
||||
expect("重按前:Start(320, 180)", T0 + 216666671, 14, 1, (want_pt[]){{16666667, 1, 3, 320, 180}});
|
||||
dm_touch_set(NULL, 0); e.x = 0.5f; e.y = 0.5f; dm_touch_set(&e, 1);
|
||||
expect("重按:先报旧的 End(320, 180)", T0 + 233333338, 15, 1, (want_pt[]){{16666667, 2, 3, 320, 180}});
|
||||
expect("重按:再报新的 Start(640, 360)", T0 + 250000005, 16, 1, (want_pt[]){{16666667, 1, 3, 640, 360}});
|
||||
printf("== %d 项,失败 %d ==\n", cases, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "../dm.h"
|
||||
#include "../touch_mac.c"
|
||||
#include "../../ios/Sources/dm_touch_controls.c"
|
||||
|
||||
uint64_t now_ns(void) { return 0; }
|
||||
void (*dm_pad_hook)(uint64_t, uint64_t *, int32_t *, int32_t *, int32_t *, int32_t *);
|
||||
uint64_t guest_ns(void) { return 0; }
|
||||
uint64_t dm_guest_frame(void) { return 0; } // 界面鼠标 / 前端路径按出图帧节拍走;本单测不测它们 | the UI mouse / front-end paths run on the presented-frame cadence; this unit test does not test them
|
||||
int dm_world_has_target(void) { return 1; } // 点世界(dm_world.c)的桩:有目标 = 主按钮照常发键 | stub for world tapping (dm_world.c): has a target = the primary button sends its key as usual
|
||||
unsigned dm_world_tap(float nx, float ny) { (void)nx; (void)ny; return 0; }
|
||||
int dm_shop_open(void) { return 0; } // 商人页(dm_actions.c)的桩:没开 | stub for the vendor page (dm_actions.c): not open
|
||||
int dm_padmode_current(void) { return 0; } // 手柄 / 触屏模式(dm_padmode.c)的桩:触屏 | Stub for controller / touch mode (dm_padmode.c): touch
|
||||
uint64_t dm_padmode_page_keys(uint64_t m) { (void)m; return 0; } void dm_padmode_legend_hide(const char *l, int a) { (void)l; (void)a; } int dm_padmode_busy(void) { return 0; } uint64_t dm_padmode_page_held(void) { return 0; } void dm_padmode_page_pulse(uint64_t m) { (void)m; } void dm_padmode_ident_hint(int on) { (void)on; } void dm_padmode_legend(int a, const char *t) { (void)a; (void)t; } const char *dm_str(uint8_t *b, const char *k) { (void)b; return k; } // 手柄页键 / 提示条 / 取串的桩(个人仓库手柄翻页用,触屏下不走) | Stubs for controller page keys / button legend / string fetch (used by controller paging of the personal stash, not reached under touch)
|
||||
int dm_swapskill_wset(void) { return -1; }
|
||||
int dm_pages_cur(void) { return 0; } int dm_pages_count(void) { return 5; } void dm_pages_request_flip(int d) { (void)d; } // 个人仓库多页(dm_pages.c)桩 | stubs for the multi-page personal stash (dm_pages.c)
|
||||
void dm_vault_ui_flip(int dir) { (void)dir; }
|
||||
int dm_vault_ui_pager_hit(int x, int y) { (void)x; (void)y; return 0; }
|
||||
void dm_vault_request_deposit(uint32_t id) { (void)id; }
|
||||
uint32_t dm_vault_ui_held(void) { return 0; }
|
||||
int dm_vault_ui_over(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_tip_gate(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_pouch_tip_gate(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_blocks(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_tap(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_drag(int phase, int x, int y) { (void)phase; (void)x; (void)y; return 0; }
|
||||
uint32_t dm_swapskill_itemsig(void) { return 0; } // 副手组技能当前武器组(dm_actions.c)的桩:读不到 | stub for the current weapon set of the swap-set skill (dm_actions.c): cannot be read
|
||||
_Atomic int g_dm_frz_want, g_dm_frozen; void dm_freeze_frame(int want) { (void)want; } // 面板冻结(diag.c)的桩 | stub for the panel freeze (diag.c)
|
||||
void dm_elysium_arm(int on) { (void)on; } // 极乐世界勾选(dm_elysium.c)的桩 | stub for the Elysium checkbox (dm_elysium.c)
|
||||
void dm_custom_on_uimsg(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; } // 「自定义」设置(dm_custom.c)的桩 | stub for the "Custom" settings (dm_custom.c)
|
||||
void dm_belt_put(unsigned id) { (void)id; }
|
||||
void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; }
|
||||
int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
int dm_uiscreen_ingame(void) { return 0; }
|
||||
void dm_uiscreen_set_ingame(int on) { (void)on; } // 界面矩形(dm_uiscreen.c)的桩:没开真全屏 | stub for the UI rectangle (dm_uiscreen.c): true full screen not enabled
|
||||
void dm_inv_sort(int page) { (void)page; }
|
||||
int dm_diag_difficulty(void) { return -1; }
|
||||
uint64_t dm_fs_commit_count(void) { return 0; }
|
||||
void dm_held_equip(int bodyloc) { (void)bodyloc; }
|
||||
int dm_rift_merc_unlocked(void) { return 1; }
|
||||
int dm_rift_merc_slot_empty(int loc) { (void)loc; return 0; }
|
||||
void dm_rift_merc_locked_hint(void) {}
|
||||
void dm_stash_take(int count) { (void)count; }
|
||||
void dm_shop_buy(void) {}
|
||||
int dm_cursor_item(void *out) { (void)out; return 0; }
|
||||
void dm_shop_sell_cursor(void) {}
|
||||
module_t g_mod[MAX_MOD]; int g_nmod;
|
||||
static void (*ui_cb)(const char *, const char *, const char *);
|
||||
static uint32_t test_tick;
|
||||
uint32_t dm_cur_tick(void) { return test_tick; }
|
||||
static int test_loadscreen_down;
|
||||
int dm_loadscreen_down(void) { return test_loadscreen_down; } // 真判定在 diag.c;单测随读取画面消息手动置位 | the real check is in diag.c; the unit test sets it by hand following the loading screen messages
|
||||
int dm_loadscreen_up(void) { return 0; } // 单测里读取画面不挡起局:不触发冻结 | in the unit test the loading screen does not block starting a run: the freeze is not triggered
|
||||
void dm_hold_for_loadscreen(void) {}
|
||||
void uimsg_subscribe(void (*f)(const char *, const char *, const char *)) { ui_cb = f; }
|
||||
static int checks, fails;
|
||||
#define CHECK(c, s) do { checks++; if (!(c)) { fails++; printf("FAIL %s\n", s); } else printf("PASS %s\n", s); } while (0)
|
||||
|
||||
int main(void) {
|
||||
const char *path = "build/touch_host.script";
|
||||
FILE *f = fopen(path, "w"); if (!f) return 2;
|
||||
fputs("0 down 0 90,1220\n0.1 move 0 150,1220\n2.1 up 0\n", f); fclose(f);
|
||||
setenv("DM_TOUCH_SCRIPT", path, 1); unsetenv("DM_TOUCH_TEST_DROP");
|
||||
uint64_t b = 0; int32_t lx = 0, ly = 0, rx = 0, ry = 0;
|
||||
test_tick = 100;
|
||||
dm_touch_host_step(0, &b, &lx, &ly, &rx, &ry);
|
||||
ui_cb("FrontEndNavigation", "ToGame", "");
|
||||
ui_cb("PanelManager", "UnloadPanel", "LoadScreenPanel"); test_loadscreen_down = 1;
|
||||
dm_touch_host_step(0, &b, &lx, &ly, &rx, &ry);
|
||||
CHECK(lx == 0 && ly == 0, "down 只建立摇杆原点");
|
||||
for (test_tick = 101; test_tick <= 162; test_tick++) {
|
||||
b = 0; lx = ly = rx = ry = 0;
|
||||
dm_touch_host_step(0, &b, &lx, &ly, &rx, &ry);
|
||||
}
|
||||
CHECK(lx > 0 && ly == 0, "move 写入宿主左摇杆");
|
||||
test_tick = 162;
|
||||
b = 0; lx = ly = rx = ry = 0; dm_touch_host_step(0, &b, &lx, &ly, &rx, &ry);
|
||||
CHECK(lx > 0 && ly == 0, "同一拍重复采样不推进脚本时间");
|
||||
test_tick = 212;
|
||||
b = 0; lx = ly = rx = ry = 0; dm_touch_host_step(0, &b, &lx, &ly, &rx, &ry);
|
||||
CHECK(lx == 0 && ly == 0, "up 清空宿主左摇杆");
|
||||
// 模式切换事务的清理(dm_mode_items.h 登记的「出」):触摸排下的替按键在切换时作废;进局替按一次「显示物品」那种宿主自己发的不在此列
|
||||
// Cleanup of the mode switch transaction (the "leave" registered in dm_mode_items.h): key presses on the player's behalf queued by touch are voided on a switch; ones the host sends by itself, such as the single 「显示物品」(Show Items) press on entering a run, are not among them
|
||||
{ uint64_t dm_ui_auto_buttons(void); void dm_ui_key_pulse(uint64_t, int), dm_ui_auto_mode_leave(void), dm_ui_cache_mode_leave(void);
|
||||
dm_ui_key_pulse(0x40, 1000); CHECK(dm_ui_auto_buttons() == 0x40, "触摸按钮的键脉冲在途:替按键里有这颗键");
|
||||
dm_ui_auto_mode_leave(); CHECK(dm_ui_auto_buttons() == 0, "切换清理后在途的键脉冲作废");
|
||||
dm_ui_cache_mode_leave(); CHECK(1, "界面缓存清理在没有界面根时不崩"); }
|
||||
printf("== touch host %d 项,失败 %d ==\n", checks, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
void dm_shop_get(dm_shop_info *out) { memset(out, 0, sizeof *out); } // 商人读数(dm_actions.c):全 0 | vendor readout (dm_actions.c): all 0
|
||||
void dm_item_use(unsigned id) { (void)id; }
|
||||
int dm_ui_hover_now(int x, int y) { (void)x; (void)y; return 0; }
|
||||
void dm_item_equip(unsigned id) { (void)id; }
|
||||
void dm_item_unequip(unsigned id) { (void)id; }
|
||||
int dm_held_size(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
int dm_item_targeting(void) { return 0; }
|
||||
int dm_vendor_repair_mode(void) { return 0; }
|
||||
void dm_item_repair(uint32_t id) { (void)id; }
|
||||
void dm_belt_fill(uint64_t w) { (void)w; }
|
||||
void dm_item_identify(unsigned id) { (void)id; }
|
||||
void dm_item_target_cancel(void) {}
|
||||
void dm_item_compare(int on) { (void)on; }
|
||||
void dm_held_stow(void) {}
|
||||
int dm_held_stow_result(void) { return -1; }
|
||||
int dm_held_pending(void) { return 0; }
|
||||
void uimsg_emit(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; }
|
||||
void dm_item_identify_free(unsigned id) { (void)id; } // 免费鉴定(dm_actions.c)的桩 | stub for free identify (dm_actions.c)
|
||||
int dm_runeword_long_press(const void *ci) { (void)ci; return 0; } // 符文之语助手(dm_runeword.c)的桩 | stub for the runeword helper (dm_runeword.c)
|
||||
int dm_runeword_list_open(void) { return 0; }
|
||||
void dm_runeword_button(const char *name) { (void)name; }
|
||||
void dm_runeword_list_close(void) {}
|
||||
@@ -0,0 +1,92 @@
|
||||
#include <stdint.h>
|
||||
|
||||
uint32_t dm_cur_tick(void) { return 0; }
|
||||
int dm_loadscreen_down(void) { return 1; } // 读取画面判定在 diag.c;触点单测当作已撤 | the loading screen check is in diag.c; the touch point unit test treats it as already down
|
||||
// 点世界(dm_world.c):这些单测不带游戏映像,给空桩
|
||||
// World tapping (dm_world.c): these unit tests carry no game image, so empty stubs are given
|
||||
void dm_world_pump(void) {}
|
||||
int dm_world_has_target(void) { return 1; }
|
||||
unsigned dm_world_tap(float nx, float ny) { (void)nx; (void)ny; return 0; }
|
||||
void dm_textinput_pump(void) {} // 文本框接法(dm_textinput.c):同上,给空桩 | text box hookup (dm_textinput.c): same as above, an empty stub
|
||||
void dm_update_pump(void) {} // 选角页构建号与新版本提示(dm_update.c):同上,给空桩 | build number and new-version notice on the character select page (dm_update.c): same as above, an empty stub
|
||||
void dm_num_set(int n) { (void)n; }
|
||||
void dm_actions_pump(void) {}
|
||||
uint64_t dm_swapskill_filter(uint64_t b) { return b; } // 副手组技能(dm_actions.c):不压键 | swap-set skill (dm_actions.c): does not suppress keys
|
||||
uint64_t dm_runeword_pad_filter(uint64_t b) { return b; } // 手柄模式符文之语清单(dm_runeword.c):不吃键 | Runeword list in controller mode (dm_runeword.c): swallow no buttons
|
||||
uint64_t dm_padmode_page_filter(uint64_t b) { return b; } // 手柄模式我们自己的页(dm_padmode.c):不吃键 | Our own pages in controller mode (dm_padmode.c): swallow no buttons
|
||||
int dm_padmode_input_gate(uint64_t *b) { (void)b; return 0; } // 手柄 / 触屏切换事务的输入闸(dm_padmode.c):没在切 | Input gate of the controller / touch switch transaction (dm_padmode.c): not switching
|
||||
int dm_padmode_current(void) { return 0; } // 手柄 / 触屏模式(dm_padmode.c):触屏 | Controller / touch mode (dm_padmode.c): touch
|
||||
uint64_t dm_padmode_page_keys(uint64_t m) { (void)m; return 0; } void dm_padmode_legend_hide(const char *l, int a) { (void)l; (void)a; } int dm_padmode_busy(void) { return 0; } uint64_t dm_padmode_page_held(void) { return 0; } void dm_padmode_page_pulse(uint64_t m) { (void)m; } void dm_padmode_ident_hint(int on) { (void)on; } void dm_padmode_legend(int a, const char *t) { (void)a; (void)t; } const char *dm_str(uint8_t *b, const char *k) { (void)b; return k; } // 手柄页键 / 提示条 / 取串的桩(个人仓库手柄翻页用,触屏下不走) | Stubs for controller page keys / button legend / string fetch (used by controller paging of the personal stash, not reached under touch)
|
||||
int dm_swapskill_wset(void) { return -1; }
|
||||
int dm_pages_cur(void) { return 0; } int dm_pages_count(void) { return 5; } void dm_pages_request_flip(int d) { (void)d; } // 个人仓库多页(dm_pages.c)桩 | stubs for the multi-page personal stash (dm_pages.c)
|
||||
void dm_vault_ui_flip(int dir) { (void)dir; }
|
||||
int dm_vault_ui_pager_hit(int x, int y) { (void)x; (void)y; return 0; }
|
||||
void dm_vault_request_deposit(uint32_t id) { (void)id; }
|
||||
uint32_t dm_vault_ui_held(void) { return 0; }
|
||||
int dm_vault_ui_over(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_tip_gate(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_pouch_tip_gate(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_blocks(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_tap(int x, int y) { (void)x; (void)y; return 0; }
|
||||
int dm_vault_ui_drag(int phase, int x, int y) { (void)phase; (void)x; (void)y; return 0; }
|
||||
uint32_t dm_swapskill_itemsig(void) { return 0; } // 同上:读不到当前武器组 | same as above: the current weapon set cannot be read
|
||||
void dm_shop_buy(void) {}
|
||||
void dm_shop_sell_cursor(void) {}
|
||||
void dm_stat_add(int s, int n) { (void)s; (void)n; }
|
||||
void dm_skill_add_selected(void) {}
|
||||
void dm_test_hold_first_sellable(void) {}
|
||||
void dm_belt_put(unsigned id) { (void)id; }
|
||||
void dm_test_sell_first(void) {}
|
||||
int dm_shop_open(void) { return 0; }
|
||||
_Atomic int g_dm_frz_want, g_dm_frozen; void dm_freeze_frame(int want) { (void)want; } // 面板冻结(diag.c)的桩 | stub for the panel freeze (diag.c)
|
||||
int dm_cursor_item(void *out) { (void)out; return 0; } // 光标下的物品(dm_cursor_item.c):没有 | item under the cursor (dm_cursor_item.c): none
|
||||
void dm_test_belt_first_potion(void) {}
|
||||
void dm_shop_get(void *out) { __builtin_memset(out, 0, 320); } // 商人读数(dm_actions.c):全 0(dm_shop_info 不到 320 字节) | vendor readout (dm_actions.c): all 0 (dm_shop_info is under 320 bytes)
|
||||
void dm_test_use_first(int kind) { (void)kind; }
|
||||
void dm_test_hover_at(float nx, float ny) { (void)nx; (void)ny; }
|
||||
int dm_ui_hover_now(int x, int y) { (void)x; (void)y; return 0; }
|
||||
void dm_item_compare(int on) { (void)on; }
|
||||
void dm_belt_expand(int on) { (void)on; }
|
||||
void dm_inv_sort(int page) { (void)page; }
|
||||
int dm_diag_difficulty(void) { return -1; }
|
||||
uint64_t dm_fs_commit_count(void) { return 0; }
|
||||
void dm_held_equip(int bodyloc) { (void)bodyloc; }
|
||||
int dm_rift_merc_unlocked(void) { return 1; }
|
||||
int dm_rift_merc_slot_empty(int loc) { (void)loc; return 0; }
|
||||
void dm_rift_merc_locked_hint(void) {}
|
||||
void dm_name_random(void) {}
|
||||
void dm_item_use(unsigned id) { (void)id; }
|
||||
void dm_test_equip(int what) { (void)what; }
|
||||
void dm_item_equip(unsigned id) { (void)id; }
|
||||
void dm_item_unequip(unsigned id) { (void)id; }
|
||||
int dm_held_size(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
int dm_item_targeting(void) { return 0; }
|
||||
int dm_vendor_repair_mode(void) { return 0; }
|
||||
void dm_item_repair(uint32_t id) { (void)id; }
|
||||
void dm_belt_fill(uint64_t w) { (void)w; }
|
||||
void dm_test_identify(int what) { (void)what; }
|
||||
uint64_t dm_diag_srv_item(uint32_t id) { (void)id; return 0; }
|
||||
void dm_belt_use(int col, int row) { (void)col; (void)row; }
|
||||
void dm_aim_cone_pump(void) {}
|
||||
void dm_item_identify(unsigned id) { (void)id; }
|
||||
void dm_item_target_cancel(void) {}
|
||||
void dm_elysium_arm(int on) { (void)on; } // 极乐世界勾选(dm_elysium.c):单测里空桩 | Elysium checkbox (dm_elysium.c): empty stub in the unit test
|
||||
void dm_custom_on_uimsg(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; } // 「自定义」设置(dm_custom.c)的桩 | stub for the "Custom" settings (dm_custom.c)
|
||||
void dm_test_stash_take(int n) { (void)n; }
|
||||
void dm_stash_take(int n) { (void)n; }
|
||||
float dm_ui_ny(float ny) { return ny; }
|
||||
int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; }
|
||||
void dm_uiscreen_enable(int m) { (void)m; }
|
||||
void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; }
|
||||
int dm_uiscreen_ingame(void) { return 0; }
|
||||
void dm_uiscreen_set_ingame(int on) { (void)on; }
|
||||
void dm_held_stow(void) {}
|
||||
int dm_held_stow_result(void) { return -1; }
|
||||
void dm_test_swap_held(void) {}
|
||||
int dm_held_pending(void) { return 0; }
|
||||
void uimsg_emit(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; }
|
||||
void dm_item_identify_free(unsigned id) { (void)id; } // 免费鉴定(dm_actions.c)的桩 | stub for free identify (dm_actions.c)
|
||||
int dm_runeword_long_press(const void *ci) { (void)ci; return 0; } // 符文之语助手(dm_runeword.c)的桩 | stub for the runeword helper (dm_runeword.c)
|
||||
int dm_runeword_list_open(void) { return 0; }
|
||||
void dm_runeword_button(const char *name) { (void)name; }
|
||||
void dm_runeword_list_close(void) {}
|
||||
@@ -0,0 +1,64 @@
|
||||
// 「单位 → 所在关卡」读法的单测(dm_unit.h,秒级)。
|
||||
// 现场:换幕的读取画面期间客户端玩家「有路径、没有房间」。原先的写法一口气连读四层,房间为空就去读地址 0x18 → sig=11 addr=0x18。
|
||||
// 红 → 绿:同一组输入,旧写法(old_level,照抄修前那一行)在子进程里跑,必须死于 SIGSEGV;新写法返回 0(未知关卡)。
|
||||
// Unit test for reading "unit -> the level it is in" (dm_unit.h, takes seconds).
|
||||
// Situation: during the loading screen of an act change the client player "has a path but no room". The old code read four levels in one go, and with a null room went on to read address 0x18 -> sig=11 addr=0x18.
|
||||
// Fail -> pass: with the same set of inputs, the old code (old_level, copied verbatim from the pre-fix line) runs in a child process and must die of SIGSEGV; the new code returns 0 (unknown level).
|
||||
#include "dm_unit.h"
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
static uint64_t rd(uint64_t a) { return a ? *(volatile uint64_t *)(uintptr_t)a : 0; }
|
||||
static int old_level(uint64_t u) { uint64_t r = rd(rd(rd(rd(u + 0x38) + 0x20) + 0x18) + 0x90); return r ? *(int32_t *)(uintptr_t)(r + 0x1f8) : 0; } // 修前的原样 | exactly as it was before the fix
|
||||
// 在子进程里跑旧写法:返回它死于哪个信号(0 = 正常返回)
|
||||
// Run the old code in a child process: returns which signal it died of (0 = returned normally)
|
||||
static int old_dies(uint64_t u) {
|
||||
fflush(stdout); pid_t p = fork(); if (p == 0) { signal(SIGSEGV, SIG_DFL); signal(SIGBUS, SIG_DFL); volatile int v = old_level(u); (void)v; _exit(0); }
|
||||
int st = 0; waitpid(p, &st, 0); return WIFSIGNALED(st) ? WTERMSIG(st) : 0;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
static uint8_t unit[0x200], path[0x100], room[0x100], ex[0x100], level[0x300];
|
||||
// 完整的一条链:关卡号 59
|
||||
// A complete chain: level id 59
|
||||
*(uint64_t *)(unit + 0x38) = (uint64_t)(uintptr_t)path; *(uint64_t *)(path + 0x20) = (uint64_t)(uintptr_t)room;
|
||||
*(uint64_t *)(room + 0x18) = (uint64_t)(uintptr_t)ex; *(uint64_t *)(ex + 0x90) = (uint64_t)(uintptr_t)level; *(int32_t *)(level + 0x1f8) = 59;
|
||||
uint64_t u = (uint64_t)(uintptr_t)unit;
|
||||
CHECK(dm_unit_level(u) == 59, "完整链应读到 59,读到 %d", dm_unit_level(u));
|
||||
CHECK(dm_unit_level_ptr(u) == (uint64_t)(uintptr_t)level, "完整链应返回关卡结构指针");
|
||||
CHECK(old_level(u) == 59, "旧写法在完整链上也应读到 59(对照)");
|
||||
|
||||
// ① 有路径、房间为空(换幕读取期间的客户端玩家)
|
||||
// (1) Has a path, room is null (the client player during an act-change loading)
|
||||
*(uint64_t *)(path + 0x20) = 0;
|
||||
int sg = old_dies(u); CHECK(sg == SIGSEGV || sg == SIGBUS, "旧写法在「有路径、房间为空」上应崩(红),实际信号 %d", sg);
|
||||
CHECK(dm_unit_level(u) == 0 && dm_unit_level_ptr(u) == 0, "新写法在「有路径、房间为空」上应返回 0");
|
||||
// ② 路径为空
|
||||
// (2) Path is null
|
||||
*(uint64_t *)(path + 0x20) = (uint64_t)(uintptr_t)room; *(uint64_t *)(unit + 0x38) = 0;
|
||||
sg = old_dies(u); CHECK(sg == SIGSEGV || sg == SIGBUS, "旧写法在「路径为空」上应崩(红),实际信号 %d", sg);
|
||||
CHECK(dm_unit_level(u) == 0 && dm_unit_level_ptr(u) == 0, "新写法在「路径为空」上应返回 0");
|
||||
// ③ 单位为空
|
||||
// (3) Unit is null
|
||||
sg = old_dies(0); CHECK(sg == SIGSEGV || sg == SIGBUS, "旧写法在「单位为空」上应崩(红),实际信号 %d", sg);
|
||||
CHECK(dm_unit_level(0) == 0 && dm_unit_level_ptr(0) == 0, "新写法在「单位为空」上应返回 0");
|
||||
// ④ 房间在、房间 +0x18 为空;⑤ +0x90 为空(链的后两步)
|
||||
// (4) Room present, room +0x18 null; (5) +0x90 null (the last two steps of the chain)
|
||||
*(uint64_t *)(unit + 0x38) = (uint64_t)(uintptr_t)path; *(uint64_t *)(room + 0x18) = 0;
|
||||
CHECK(dm_unit_level(u) == 0, "房间 +0x18 为空应返回 0");
|
||||
*(uint64_t *)(room + 0x18) = (uint64_t)(uintptr_t)ex; *(uint64_t *)(ex + 0x90) = 0;
|
||||
CHECK(dm_unit_level(u) == 0, "关卡指针为空应返回 0");
|
||||
*(uint64_t *)(ex + 0x90) = (uint64_t)(uintptr_t)level;
|
||||
CHECK(dm_unit_level(u) == 59, "链接回去后应再读到 59");
|
||||
// 关卡指针为空时取房间链头:返回 0(原先各处直接 rd(lv + 0x10) 去读地址 0x10)
|
||||
// Taking the room chain head when the level pointer is null: returns 0 (previously each place did rd(lv + 0x10) directly and read address 0x10)
|
||||
CHECK(dm_level_rooms(0) == 0, "关卡指针为空时房间链头应为 0");
|
||||
*(uint64_t *)(level + 0x10) = (uint64_t)(uintptr_t)room; CHECK(dm_level_rooms((uint64_t)(uintptr_t)level) == (uint64_t)(uintptr_t)room, "关卡非空时应读到 +0x10 的房间");
|
||||
printf("t_unit_level: %d 项,%d 失败\n", checks, fails); return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// 控件类型核对(dm_widget.h)的单测,秒级。假「主模块」是一块内存,控件第一个字 = 基址 + 虚表偏移。
|
||||
// Unit test for the widget type check (dm_widget.h), runs in seconds. The fake "main module" is a block of memory; a widget's first word = base + vtable offset.
|
||||
#include "dm_widget.h"
|
||||
#include <stdio.h>
|
||||
|
||||
static int fails, checks;
|
||||
#define CHECK(c, ...) do { checks++; if (!(c)) { fails++; printf(" ✗ "); printf(__VA_ARGS__); printf("\n"); } } while (0)
|
||||
|
||||
int main(void) {
|
||||
static uint8_t base[16]; static uint64_t w_toggle[4], w_text[4], w_slot[4], w_slotb[4], w_slotc[4], w_other[4];
|
||||
w_toggle[0] = (uint64_t)(uintptr_t)base + DM_VT_TOGGLE; w_text[0] = (uint64_t)(uintptr_t)base + DM_VT_TEXT; w_other[0] = (uint64_t)(uintptr_t)base + 0x1234;
|
||||
w_slot[0] = (uint64_t)(uintptr_t)base + DM_VT_SLOT; w_slotb[0] = (uint64_t)(uintptr_t)base + DM_VT_SLOT_B; w_slotc[0] = (uint64_t)(uintptr_t)base + DM_VT_SLOT_C;
|
||||
uint64_t tg = (uint64_t)(uintptr_t)w_toggle, tx = (uint64_t)(uintptr_t)w_text, ot = (uint64_t)(uintptr_t)w_other;
|
||||
|
||||
CHECK(dm_widget_vt(base, tg) == DM_VT_TOGGLE, "勾选框的虚表偏移应读到 %#x,读到 %#llx", DM_VT_TOGGLE, (unsigned long long)dm_widget_vt(base, tg));
|
||||
CHECK(dm_widget_is(base, tg, DM_VT_TOGGLE), "勾选框应认作勾选框");
|
||||
CHECK(!dm_widget_is(base, tx, DM_VT_TOGGLE), "文字框不该认作勾选框(同名控件换了类时就是这种情况)");
|
||||
CHECK(dm_widget_is(base, tx, DM_VT_TEXT), "文字框应认作文字框");
|
||||
CHECK(!dm_widget_is(base, ot, DM_VT_TOGGLE) && !dm_widget_is(base, ot, DM_VT_TEXT), "不认识的类一律不认");
|
||||
CHECK(!dm_widget_is(base, 0, DM_VT_TOGGLE) && dm_widget_vt(base, 0) == 0, "空控件:不认、虚表读 0");
|
||||
CHECK(!dm_widget_is(NULL, tg, DM_VT_TOGGLE) && dm_widget_vt(NULL, tg) == 0, "没有基址:不认、虚表读 0");
|
||||
CHECK(dm_widget_is_slot(base, (uint64_t)(uintptr_t)w_slot) && dm_widget_is_slot(base, (uint64_t)(uintptr_t)w_slotb) && dm_widget_is_slot(base, (uint64_t)(uintptr_t)w_slotc), "三种物品格都认作物品格");
|
||||
CHECK(!dm_widget_is_slot(base, tg) && !dm_widget_is_slot(base, 0), "勾选框 / 空控件不是物品格");
|
||||
// 各类的虚表值两两不同(抄错一个数会让两类互认)
|
||||
// Vtable values of the classes are pairwise distinct (one mistyped number would make two classes match each other)
|
||||
{ const uint64_t v[] = { DM_VT_TEXT, DM_VT_INPUT, DM_VT_NUMINPUT, DM_VT_TOGGLE, DM_VT_TABBAR, DM_VT_SLOT, DM_VT_SLOT_B, DM_VT_SLOT_C, DM_VT_IMAGE, DM_VT_BUTTON }; int dup = 0;
|
||||
for (unsigned i = 0; i < sizeof v / sizeof *v; i++) for (unsigned j = i + 1; j < sizeof v / sizeof *v; j++) dup += v[i] == v[j];
|
||||
CHECK(dup == 0, "虚表常量有 %d 对重复", dup); }
|
||||
|
||||
printf("t_widget:%d 项,%d 项不通\n", checks, fails); return fails != 0;
|
||||
}
|
||||
Reference in New Issue
Block a user