Check that win64/aces.exe, wto_ws.dll, and wto_ws.cfg exist and are readable immediately before spawning the game, surfacing a dedicated error when security software removes them. On unexpected non-zero exits, log a compact read-only snapshot of hook file presence, wto_ws.log tail lines, and newly created .game_logs entries. Checked: root typecheck, launcher typecheck, and zh-CN/en locale key parity.
173 lines
6.8 KiB
TypeScript
173 lines
6.8 KiB
TypeScript
import { execFile, spawn } from 'node:child_process';
|
|
import { constants } from 'node:fs';
|
|
import { access, lstat, open, readdir } from 'node:fs/promises';
|
|
import { dirname, join } from 'node:path';
|
|
import { promisify } from 'node:util';
|
|
import { GAME_FILES } from '@wto/patcher';
|
|
import { AppError } from '@shared/errors.ts';
|
|
import offlineGameArguments from '@shared/offline-game-arguments.json';
|
|
import { formatExitCode, type GameExit } from '@shared/schemas/launch.ts';
|
|
|
|
const execute = promisify(execFile);
|
|
const HOOK_DLL_FILENAME = 'wto_ws.dll';
|
|
const HOOK_CFG_FILENAME = 'wto_ws.cfg';
|
|
const HOOK_LOG_FILENAME = 'wto_ws.log';
|
|
const HOOK_LOG_TAIL_BYTES = 8 * 1024;
|
|
const HOOK_LOG_TAIL_LINES = 8;
|
|
const HOOK_LOG_LINE_LIMIT = 200;
|
|
/** Allow small filesystem timestamp skew when matching newly created .game_logs entries. */
|
|
const MTIME_SKEW_MS = 2000;
|
|
|
|
export async function gameProcessRunning(signal: AbortSignal): Promise<boolean> {
|
|
if (process.platform !== 'win32') return false;
|
|
const games = await execute('tasklist.exe', ['/FI', 'IMAGENAME eq aces.exe', '/FO', 'CSV', '/NH'], { windowsHide: true, signal });
|
|
return /^"aces\.exe",/im.test(games.stdout);
|
|
}
|
|
|
|
export async function runGameProcess(
|
|
copyPath: string, additionalArguments: readonly string[], signal: AbortSignal, onStart: () => void,
|
|
): Promise<GameExit> {
|
|
if (await gameProcessRunning(signal)) throw new AppError('launch_game_running');
|
|
await verifyLaunchFiles(copyPath);
|
|
signal.throwIfAborted();
|
|
const executable = join(copyPath, GAME_FILES.executable);
|
|
const args = [...offlineGameArguments, ...additionalArguments];
|
|
const startedAt = Date.now();
|
|
console.info('[game] starting:', executable, args);
|
|
const child = spawn(executable, args, {
|
|
cwd: copyPath, shell: false, stdio: 'ignore',
|
|
});
|
|
const stop = (): void => { child.kill(); };
|
|
|
|
try {
|
|
return await new Promise<GameExit>((resolve, reject) => {
|
|
child.once('spawn', () => {
|
|
console.info('[game] process started, pid:', child.pid ?? 'unknown');
|
|
if (signal.aborted) stop();
|
|
else onStart();
|
|
});
|
|
child.once('error', (error) => {
|
|
console.error('[game] process error:', error);
|
|
reject(new AppError('launch_game_failed'));
|
|
});
|
|
child.once('close', (code, reason) => {
|
|
const logFolder = join(copyPath, '.game_logs');
|
|
const elapsedMs = Date.now() - startedAt;
|
|
const summary = code !== null ? formatExitCode(code) : (reason ?? 'unknown');
|
|
if (code !== 0 && !signal.aborted) {
|
|
console.warn('[game] process exited:', summary, `after ${elapsedMs} ms`, logFolder);
|
|
void logAbnormalExitContext(copyPath, startedAt)
|
|
.catch((error: unknown) => console.warn('[game] inspecting post-exit files failed:', error))
|
|
.finally(() => resolve({ code, signal: reason, logFolder }));
|
|
return;
|
|
}
|
|
console.info('[game] process exited:', summary, `after ${elapsedMs} ms`);
|
|
resolve({ code, signal: reason, logFolder });
|
|
});
|
|
signal.addEventListener('abort', stop, { once: true });
|
|
});
|
|
} finally {
|
|
signal.removeEventListener('abort', stop);
|
|
}
|
|
}
|
|
|
|
/** Verify the patched executable and hook files are still present and readable right before spawn. */
|
|
async function verifyLaunchFiles(copyPath: string): Promise<void> {
|
|
const exeFolder = dirname(GAME_FILES.executable);
|
|
const required = [
|
|
GAME_FILES.executable,
|
|
join(exeFolder, HOOK_DLL_FILENAME),
|
|
join(exeFolder, HOOK_CFG_FILENAME),
|
|
];
|
|
const missing: string[] = [];
|
|
for (const relativePath of required) {
|
|
const fullPath = join(copyPath, relativePath);
|
|
try {
|
|
const stats = await lstat(fullPath);
|
|
if (!stats.isFile() || stats.size === 0) {
|
|
missing.push(`${relativePath} (not a non-empty file)`);
|
|
continue;
|
|
}
|
|
await access(fullPath, constants.R_OK);
|
|
} catch (error) {
|
|
const code = (error as NodeJS.ErrnoException).code ?? 'error';
|
|
missing.push(`${relativePath} (${code})`);
|
|
}
|
|
}
|
|
if (missing.length > 0) {
|
|
console.error('[game] required launch files unavailable before start:', missing.join(', '));
|
|
throw new AppError('launch_game_files_missing');
|
|
}
|
|
}
|
|
|
|
/** Record a compact read-only snapshot of hook and game log files after an unexpected non-zero exit. */
|
|
async function logAbnormalExitContext(copyPath: string, startedAt: number): Promise<void> {
|
|
const exeFolder = join(copyPath, dirname(GAME_FILES.executable));
|
|
const [dllState, cfgState, hookLogStat, newGameLogs] = await Promise.all([
|
|
describeFile(join(exeFolder, HOOK_DLL_FILENAME)),
|
|
describeFile(join(exeFolder, HOOK_CFG_FILENAME)),
|
|
safeRegularStat(join(exeFolder, HOOK_LOG_FILENAME)),
|
|
listNewGameLogs(join(copyPath, '.game_logs'), startedAt),
|
|
]);
|
|
const hookLogDesc = hookLogStat
|
|
? `${hookLogStat.size} bytes (${hookLogStat.mtimeMs >= startedAt - MTIME_SKEW_MS ? 'updated' : 'stale'})`
|
|
: 'missing';
|
|
console.warn(
|
|
`[game] post-exit check: ${HOOK_DLL_FILENAME}=${dllState}, ${HOOK_CFG_FILENAME}=${cfgState}, ` +
|
|
`${HOOK_LOG_FILENAME}=${hookLogDesc}, newGameLogs=${newGameLogs}`,
|
|
);
|
|
if (hookLogStat && hookLogStat.size > 0) {
|
|
const tail = await readTailLines(join(exeFolder, HOOK_LOG_FILENAME), hookLogStat.size);
|
|
if (tail.length > 0) {
|
|
console.warn(`[game] ${HOOK_LOG_FILENAME} tail:\n ${tail.join('\n ')}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function describeFile(path: string): Promise<string> {
|
|
const stats = await safeRegularStat(path);
|
|
return stats ? `${stats.size} bytes` : 'missing';
|
|
}
|
|
|
|
async function safeRegularStat(path: string) {
|
|
try {
|
|
const stats = await lstat(path);
|
|
return stats.isFile() ? stats : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function listNewGameLogs(folder: string, startedAt: number): Promise<string> {
|
|
try {
|
|
const entries = await readdir(folder, { withFileTypes: true });
|
|
const recent: string[] = [];
|
|
for (const entry of entries) {
|
|
if (!entry.isFile()) continue;
|
|
const stats = await safeRegularStat(join(folder, entry.name));
|
|
if (!stats || stats.mtimeMs < startedAt - MTIME_SKEW_MS) continue;
|
|
recent.push(`${entry.name} (${stats.size} bytes)`);
|
|
}
|
|
return recent.length > 0 ? recent.slice(0, 6).join(', ') : 'none';
|
|
} catch {
|
|
return 'unavailable';
|
|
}
|
|
}
|
|
|
|
async function readTailLines(path: string, fileSize: number): Promise<string[]> {
|
|
const length = Math.min(fileSize, HOOK_LOG_TAIL_BYTES);
|
|
const start = fileSize - length;
|
|
const handle = await open(path, 'r');
|
|
try {
|
|
const buffer = Buffer.alloc(length);
|
|
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
|
const text = buffer.subarray(0, bytesRead).toString('utf8');
|
|
const lines = text.split(/\r?\n/).filter((line) => line.length > 0);
|
|
return lines.slice(-HOOK_LOG_TAIL_LINES).map((line) => (
|
|
line.length > HOOK_LOG_LINE_LIMIT ? `${line.slice(0, HOOK_LOG_LINE_LIMIT)}…` : line
|
|
));
|
|
} finally {
|
|
await handle.close();
|
|
}
|
|
}
|