diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..9dab7c20 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,26 @@ +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); case \"$CMD\" in *grep*|*rg\\ *|*ripgrep*|*find\\ *|*fd\\ *|*ack\\ *|*ag\\ *) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run `graphify query \\\"\\\"` before grepping raw files. Only grep after graphify has oriented you, or to modify/debug specific lines.\"}}' || true ;; esac", + "powershell": "$inp = [Console]::In.ReadToEnd(); try { $t = ($inp | ConvertFrom-Json).tool_input; $c = if ($t.command) { $t.command } else { '' }; $kw = @('grep','rg ','ripgrep','find ','fd ','ack ','ag '); if (($kw | Where-Object { $c -like \"*$_*\" }) -and (Test-Path 'graphify-out/graph.json')) { Write-Output ('{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify query before grepping raw files. Only grep after graphify has oriented you, or to modify/debug specific lines.\"}}') } } catch {}; exit 0" + } + ] + }, + { + "matcher": "Read|Glob", + "hooks": [ + { + "type": "command", + "command": "HIT=$(python3 -c \"import json,sys;d=json.load(sys.stdin);t=d.get('tool_input',d);exts=('.py','.js','.ts','.tsx','.jsx','.astro','.vue','.svelte','.go','.rs','.java','.rb','.c','.h','.cpp','.hpp','.cc','.cs','.kt','.swift','.php','.scala','.lua','.sh','.md','.rst','.txt','.mdx');vals=[str(t.get('file_path') or ''),str(t.get('pattern') or ''),str(t.get('path') or '')];j=' '.join(vals).lower().replace(chr(92),'/');tails=[('.'+x.rsplit('.',1)[-1]) for v in vals if v for x in [v.lower().replace(chr(92),'/').rsplit('/',1)[-1]] if '.' in x];sys.stdout.write('1' if 'graphify-out/' not in j and any(tl in exts for tl in tails) else '')\" 2>/dev/null || true); if [ \"$HIT\" = 1 ] && [ -f graphify-out/graph.json ]; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify before reading source files. Use: `graphify query \\\"\\\"` (scoped subgraph), `graphify explain \\\"\\\"`, or `graphify path \\\"\\\" \\\"\\\"`. Only read raw files after graphify has oriented you, or to modify/debug specific lines. This rule applies to subagents too — include it in every subagent prompt involving code exploration.\"}}'; fi || true", + "powershell": "$inp = [Console]::In.ReadToEnd(); try { $t = ($inp | ConvertFrom-Json).tool_input; $fp = if ($t.file_path) { $t.file_path } elseif ($t.pattern) { $t.pattern } elseif ($t.path) { $t.path } else { '' }; $exts = @('.py','.js','.ts','.tsx','.jsx','.astro','.vue','.svelte','.go','.rs','.java','.rb','.c','.h','.cpp','.hpp','.cc','.cs','.kt','.swift','.php','.scala','.lua','.sh','.md','.rst','.txt','.mdx'); $ext = [System.IO.Path]::GetExtension($fp).ToLower(); if ($ext -and ($exts -contains $ext) -and ($fp -notlike 'graphify-out/*') -and (Test-Path 'graphify-out/graph.json')) { Write-Output ('{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"MANDATORY: graphify-out/graph.json exists. You MUST run graphify before reading source files. Use: graphify query (scoped subgraph), graphify explain, or graphify path. Only read raw files after graphify has oriented you, or to modify/debug specific lines. This rule applies to subagents too - include it in every subagent prompt involving code exploration.\"}}') } } catch {}; exit 0" + } + ] + } + ] + } +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 83a14afd..6b259bd3 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ objdir .vs/* .vscode/* +graphify-out/* diff --git a/.graphifyignore b/.graphifyignore new file mode 100644 index 00000000..395dd1d9 --- /dev/null +++ b/.graphifyignore @@ -0,0 +1,43 @@ +# Binaries +*.dll +*.dylib +*.exe +*.so + +# Files generated by Visual Studio +*.aps +*.ipch +*.ncb +*.opensdf +*.sdf +*.suo +*.user + +# Build directories +CrazyDebug*/ +Debug*/ +Release*/ +LIB-Release/ +LIB-Debug/ + +# Files generated by Mac OS X Finder +.DS_Store + +# Files generated by Windows Explorer +[Dd]esktop.ini +[Tt]humbs.db + +# AMBuild build directories +obj-*/ +*~ +*.rej +*.orig +*.smx +*.swp +*.gdb_history +objdir +# Not standardized, but common name for build directories +/build*/ + +.vs/* +.vscode/* diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..136ad479 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,29 @@ +# Repository Guidelines + +## Project Structure & Module Organization + +SourceMod is a C++17 Metamod:Source plugin with a SourcePawn scripting layer. The runtime path is `loader/` (Metamod entry point) to the per-SDK `core/` to engine-independent `core/logic/`; interfaces between the latter two live in `bridge/include/`. Bundled C++ extensions are in `extensions/`, while bundled SourcePawn plugins and public `.inc` APIs are in `plugins/` and `plugins/include/`. Keep game offsets and signatures in `gamedata/`, defaults in `configs/`, and phrase files in `translations/`. `sourcepawn/`, `public/amtl`, `public/safetyhook`, and `hl2sdk-manifests/` are submodules: do not make local product changes there. + +## Build, Test, and Development Commands + +Fetch dependencies from a sibling checkout using `tools/checkout-deps.ps1` (Windows) or `tools/checkout-deps.sh`; these scripts expect this repository to be named `sourcemod`. + +```text +mkdir build; cd build +python ../configure.py --enable-optimize --sdks=present --targets=x86,x86_64 +ambuild +``` + +This produces the distributable tree in `build/package/`. Rebuild an existing output directory with `ambuild build-win` (or the relevant build directory). Use `--enable-debug`, `--no-mysql`, or `--scripting-only` when appropriate. Verify translation-only changes with `python tools/language_check/sanity_check.py`. + +## Coding Style & Naming Conventions + +Follow the surrounding file exactly. C++ uses four-space indentation, brace-on-next-line function definitions, and established `CamelCase` types/functions with `m_` member prefixes. SourcePawn uses four spaces, `#pragma semicolon 1`, `#pragma newdecls required`, and `PascalCase` callback/function names; name test plugins `test_.sp`. Do not add a formatter configuration or reformat unrelated code. Public API changes in `plugins/include/` require especially careful compatibility review. + +## Testing Guidelines + +There is no standalone unit-test command. Add functional SourcePawn coverage under `plugins/testsuite/`; CI mock tests belong in `plugins/testsuite/mock/`. The mock workflow builds with `--sdks=mock --targets=x86_64`, compiles each test with `spcomp64`, and fails on `FAIL` output. Run a targeted built plugin against a suitable Source server or mirror `.github/workflows/mocktest.yml` for full mock coverage. + +## Commits & Pull Requests + +Use short imperative subjects, optionally scoped, such as `gamedata: update PVKII offsets` or `Fix build`; include an issue reference when relevant. Keep commits focused. Discuss nontrivial changes before opening a PRβ€”new configuration options are rarely accepted. Target `master` or the active `X.Y-dev` branch, describe behavior and testing, link the issue, and include a minimal reproduction for bug fixes. Report security issues privately to `security@alliedmods.net`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..2a066c42 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,66 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Overview + +SourceMod is a Metamod:Source plugin for Source engine game servers, providing server administration and a scripting environment (SourcePawn). C++17, built with AMBuild 2.2+. Targets Windows and Linux, x86 and x86_64, against multiple HL2SDK engine branches simultaneously. + +## Build + +Dependencies (HL2SDKs, Metamod:Source, MySQL, AMBuild) are fetched by `tools/checkout-deps.ps1` / `tools/checkout-deps.sh`, run from a sibling directory of the repo checkout (it expects a `sourcemod` folder next to it). Example: `tools/checkout-deps.sh -s tf2,css` to limit SDKs. + +Configure and build (out-of-source): + +``` +mkdir build && cd build +python ../configure.py --enable-optimize --sdks=present --targets=x86,x86_64 +ambuild +``` + +- To rebuild after edits, just run `ambuild` from (or pointed at) the existing build dir β€” e.g. `ambuild build-win`. This repo already has configured output dirs: `build-win`, `build-win32`, `build-lin`. +- Key configure flags: `--sdks=` (comma list, `present`, or `all`), `--targets=x86,x86_64`, `--no-mysql`, `--enable-debug`, `--hl2sdk-root=`, `--mms-path=`, `--scripting-only` (build only spcomp + scripting package). +- The packaged layout lands in `/package` (an `addons/sourcemod` tree). +- GCC builds use `-Wall -Werror`; MSVC 2017 15.7+ / GCC 9+ / Clang 5+ required. + +## Tests + +There is no unit test runner in this repo; functional tests are SourcePawn plugins in `plugins/testsuite/`, with the CI-run subset in `plugins/testsuite/mock/` (see `.github/workflows/mocktest.yml`). They run against [hl2sdk-mock](https://github.com/alliedmodders/hl2sdk-mock), a fake Source engine: + +1. Build metamod-source and SourceMod with `--sdks=mock --targets=x86_64`, build hl2sdk-mock, then assemble a gamedir with hl2sdk-mock's `build_gamedir.sh` from both package dirs. +2. Compile a test: `spcomp64 -i /addons/sourcemod/scripting/include -o test.smx -E plugins/testsuite/mock/.sp` +3. Run one test: `./srcds -game_dir +map de_thunder -command "sm plugins load optional/" -run -run-ticks 20` β€” output containing `FAIL` means failure. + +## Architecture + +Runtime loading chain: **loader β†’ core (per-engine) β†’ logic (engine-agnostic)**. + +- `loader/` β€” builds `sourcemod_mm`, the Metamod:Source plugin stub. At runtime it detects the engine branch and loads the matching core binary (`sourcemod.2.`, e.g. `sourcemod.2.tf2`). +- `core/` β€” engine-dependent core, compiled **once per SDK** (each `sourcemod.2.` binary): console command/convar hooks, events, menus, players, timers. `core/logic_bridge.cpp` implements `CoreProvider`. +- `core/logic/` β€” `sourcemod.logic`, compiled once, engine-agnostic: plugin system, handles, natives, admin cache, extensions manager, database support, translator. +- `bridge/` β€” the interface boundary between core and logic (`CoreProvider`/`LogicProvider` structs in `bridge/include/`). Anything logic needs from the engine goes through here. +- `sourcepawn/` β€” **git submodule**: the SourcePawn VM/JIT and compiler (`spcomp`). Don't edit here for SourceMod changes; it's updated by bumping the submodule. +- `public/amtl`, `public/safetyhook`, `hl2sdk-manifests/` β€” other submodules (AlliedModders template library, detour library, SDK build manifests consumed by `AMBuildScript`). +- `extensions/` β€” bundled C++ extensions, each with its own `AMBuilder` (registered in the root `AMBuildScript`). Engine-dependent ones (sdktools, sdkhooks, cstrike, tf2, dhooks) build per-SDK; others (mysql, regex, geoip, clientprefs…) build once. +- `plugins/` β€” bundled SourcePawn plugins. `plugins/include/` is the **public scripting API** (`.inc` files) β€” changes here change the API surface for every plugin author and are documented at sm.alliedmods.net/new-api. +- `gamedata/` β€” per-game offsets/signatures/patch info (KeyValues text files), often updated for game patches without code changes. +- `configs/`, `translations/` β€” shipped default configs and localization phrase files. Translations have their own sanity-check CI workflows. +- `versionlib/` + `product.version` β€” auto-versioning; generated headers end up in `/includes` (disable with `--disable-auto-versioning`). + +Extensions interface with core via the public SDK headers in `public/` (e.g. `IExtensionSys.h`, `IPluginSys.h`), the same headers third-party extension authors use (`public/sample_ext` is the template). + +## Contributing notes + +- Nontrivial changes are expected to be discussed in an issue or with the dev team before a PR (see `.github/CONTRIBUTING.md`); new configuration options are very rarely accepted. +- Security issues go to security@alliedmods.net, not the public tracker. +- PR branches target `master` or the active `X.Y-dev` branch. + +## graphify + +This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships. + +Rules: +- For codebase questions, first run `graphify query ""` when graphify-out/graph.json exists. Use `graphify path "" ""` for relationships and `graphify explain ""` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. +- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing. +- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context. +- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost). diff --git a/core/logic/sprintf.cpp b/core/logic/sprintf.cpp index 8f1c24de..77a44ea7 100644 --- a/core/logic/sprintf.cpp +++ b/core/logic/sprintf.cpp @@ -337,7 +337,7 @@ void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec, in val = (int)(fval / tmp); *buf++ = '0' + val; fval -= val * tmp; - tmp *= 0.1; + tmp /= 10.0; } maxlen--; } @@ -360,7 +360,7 @@ void AddFloat(char **buf_p, size_t &maxlen, double fval, int width, int prec, in } else { - tmp *= 0.1; + tmp /= 10.0; val = (int)(fval / tmp); *buf++ = '0' + val; fval -= val * tmp; @@ -1401,4 +1401,3 @@ done: *param = arg; return (maxlen - llen - 1); } - diff --git a/plugins/testsuite/async_file_test.sp b/plugins/testsuite/async_file_test.sp new file mode 100644 index 00000000..6a3cee4c --- /dev/null +++ b/plugins/testsuite/async_file_test.sp @@ -0,0 +1,319 @@ +#pragma semicolon 1 +#pragma newdecls required + +#include + +public Plugin myinfo = +{ + name = "Async File API Test", + author = "AlliedModders", + description = "Manual functional test for the asynchronous file API", + version = "1.0", + url = "https://www.sourcemod.net/" +}; + +enum TestStep +{ + TestStep_CreateDirectory, + TestStep_DirExists, + TestStep_Write, + TestStep_FileExists, + TestStep_FileSize, + TestStep_Read, + TestStep_Copy, + TestStep_Rename, + TestStep_OpenDirectory, + TestStep_DeleteRenamed, + TestStep_DeleteSource, + TestStep_RemoveDirectory, + TestStep_Done, +}; + +static const char g_Directory[] = "addons/sourcemod/data/async_file_api_test"; +static const char g_Source[] = "addons/sourcemod/data/async_file_api_test/source.bin"; +static const char g_Copy[] = "addons/sourcemod/data/async_file_api_test/copy.bin"; +static const char g_Renamed[] = "addons/sourcemod/data/async_file_api_test/renamed.bin"; +static const char g_PathID[] = "DEFAULT_WRITE_PATH"; +static int g_Bytes[] = {0x00, 0x01, 0x41, 0x00, 0xff, 0x7f}; +static const int g_ByteCount = 6; + +static bool g_Running; +static bool g_ValveFS; +static int g_Failures; +static TestStep g_Step; + +public void OnPluginStart() +{ + RegAdminCmd("sm_async_file_test", Command_RunOS, ADMFLAG_ROOT, + "Run the asynchronous file API test against the OS filesystem"); + RegAdminCmd("sm_async_file_test_valve", Command_RunValve, ADMFLAG_ROOT, + "Run the asynchronous file API test against the Valve filesystem"); +} + +public Action Command_RunOS(int client, int args) +{ + StartTest(false); + return Plugin_Handled; +} + +public Action Command_RunValve(int client, int args) +{ + StartTest(true); + return Plugin_Handled; +} + +static void StartTest(bool valveFS) +{ + if (g_Running) + { + PrintToServer("[async-file-test] A test is already running."); + return; + } + + g_Running = true; + g_ValveFS = valveFS; + g_Failures = 0; + g_Step = TestStep_CreateDirectory; + + // Cleanup is deliberately synchronous: it only removes this test's stale + // artifacts before the async test begins. + DeleteFile(g_Source, valveFS, g_PathID); + DeleteFile(g_Copy, valveFS, g_PathID); + DeleteFile(g_Renamed, valveFS, g_PathID); + RemoveDir(g_Directory); + + PrintToServer("[async-file-test] Starting %s filesystem test.", + valveFS ? "Valve" : "OS"); + RunNextStep(); +} + +static void RunNextStep() +{ + switch (g_Step) + { + case TestStep_CreateDirectory: + { + CreateDirectoryAsync(g_Directory, + FPERM_U_READ | FPERM_U_WRITE | FPERM_U_EXEC | + FPERM_G_READ | FPERM_G_EXEC | FPERM_O_READ | FPERM_O_EXEC, + OnResult, g_Step, g_ValveFS, g_PathID); + } + case TestStep_DirExists: + { + DirExistsAsync(g_Directory, OnExists, g_Step, g_ValveFS, g_PathID); + } + case TestStep_Write: + { + char bytes[6]; + for (int i = 0; i < g_ByteCount; i++) + { + bytes[i] = g_Bytes[i]; + } + WriteFileAsync(g_Source, bytes, g_ByteCount, OnResult, g_Step, + false, g_ValveFS, g_PathID); + } + case TestStep_FileExists: + { + FileExistsAsync(g_Source, OnExists, g_Step, g_ValveFS, g_PathID); + } + case TestStep_FileSize: + { + FileSizeAsync(g_Source, OnFileSize, g_Step, g_ValveFS, g_PathID); + } + case TestStep_Read: + { + ReadFileAsync(g_Source, OnRead, g_Step, g_ValveFS, g_PathID); + } + case TestStep_Copy: + { + CopyFileAsync(g_Copy, g_Source, OnResult, g_Step, g_ValveFS, + g_PathID, g_PathID); + } + case TestStep_Rename: + { + RenameFileAsync(g_Renamed, g_Copy, OnResult, g_Step, g_ValveFS, g_PathID); + } + case TestStep_OpenDirectory: + { + if (g_ValveFS) + { + PrintToServer("[async-file-test] Skipping Valve directory enumeration (not supported asynchronously)."); + Advance(); + return; + } + + OpenDirectoryAsync(g_Directory, OnDirectory, g_Step); + } + case TestStep_DeleteRenamed: + { + DeleteFileAsync(g_Renamed, OnResult, g_Step, g_ValveFS, g_PathID); + } + case TestStep_DeleteSource: + { + DeleteFileAsync(g_Source, OnResult, g_Step, g_ValveFS, g_PathID); + } + case TestStep_RemoveDirectory: + { + // RemoveDirAsync currently operates on the OS filesystem only. + RemoveDirAsync(g_Directory, OnResult, g_Step); + } + case TestStep_Done: + { + FinishTest(); + } + } +} + +void OnResult(FileOpResult result, const char[] path, any data) +{ + CheckCallbackData(data); + Check(result == FileOp_Success, "operation result"); + CheckExpectedPath(path); + Advance(); +} + +void OnExists(bool exists, const char[] path, any data) +{ + CheckCallbackData(data); + Check(exists, "entry exists"); + CheckExpectedPath(path); + Advance(); +} + +void OnFileSize(FileOpResult result, const char[] path, int size, any data) +{ + CheckCallbackData(data); + Check(result == FileOp_Success, "file-size result"); + Check(size == g_ByteCount, "file size"); + CheckExpectedPath(path); + Advance(); +} + +void OnRead(FileOpResult result, const char[] path, const char[] contents, int size, any data) +{ + CheckCallbackData(data); + Check(result == FileOp_Success, "read result"); + Check(size == g_ByteCount, "read size"); + CheckExpectedPath(path); + bool mismatch = false; + for (int i = 0; i < size && i < g_ByteCount; i++) + { + if ((contents[i] & 0xff) != (g_Bytes[i] & 0xff)) + { + PrintToServer("[async-file-test] Read mismatch at byte %d: expected 0x%02X, async 0x%02X.", + i, g_Bytes[i] & 0xff, contents[i] & 0xff); + Check(false, "read byte"); + mismatch = true; + } + } + if (mismatch && g_ValveFS) + DiagnoseValveRead(); + Advance(); +} + +void DiagnoseValveRead() +{ + File file = OpenFile(g_Source, "rb", true, g_PathID); + if (file == null) + { + PrintToServer("[async-file-test] DIAG: synchronous Valve read could not open '%s'.", g_Source); + return; + } + + int bytes[6]; + int count = file.Read(bytes, sizeof(bytes), 1); + delete file; + + PrintToServer("[async-file-test] DIAG: synchronous Valve read returned %d bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X.", + count, bytes[0] & 0xff, bytes[1] & 0xff, bytes[2] & 0xff, + bytes[3] & 0xff, bytes[4] & 0xff, bytes[5] & 0xff); +} + +void OnDirectory(FileOpResult result, const char[] path, DirectoryListing listing, any data) +{ + char name[PLATFORM_MAX_PATH]; + FileType type; + bool foundSource; + bool foundRenamed; + + CheckCallbackData(data); + Check(result == FileOp_Success, "directory result"); + CheckExpectedPath(path); + Check(listing != null, "directory listing"); + if (listing != null) + { + while (listing.GetNext(name, sizeof(name), type)) + { + if (StrEqual(name, "source.bin")) + { + Check(type == FileType_File, "source entry type"); + foundSource = true; + } + else if (StrEqual(name, "renamed.bin")) + { + Check(type == FileType_File, "renamed entry type"); + foundRenamed = true; + } + } + delete listing; + } + Check(foundSource, "source directory entry"); + Check(foundRenamed, "renamed directory entry"); + Advance(); +} + +static void CheckCallbackData(any data) +{ + Check(data == g_Step, "callback data"); +} + +static void CheckExpectedPath(const char[] path) +{ + char expected[PLATFORM_MAX_PATH]; + switch (g_Step) + { + case TestStep_CreateDirectory, TestStep_DirExists, TestStep_OpenDirectory, + TestStep_RemoveDirectory: + { + strcopy(expected, sizeof(expected), g_Directory); + } + case TestStep_Write, TestStep_FileExists, TestStep_FileSize, TestStep_Read, + TestStep_DeleteSource: + { + strcopy(expected, sizeof(expected), g_Source); + } + case TestStep_Copy: + { + strcopy(expected, sizeof(expected), g_Copy); + } + case TestStep_Rename, TestStep_DeleteRenamed: + { + strcopy(expected, sizeof(expected), g_Renamed); + } + } + Check(StrEqual(path, expected), "callback path"); +} + +static void Check(bool condition, const char[] name) +{ + if (condition) + return; + + g_Failures++; + PrintToServer("[async-file-test] FAIL: %s (step %d, %s filesystem)", name, + g_Step, g_ValveFS ? "Valve" : "OS"); +} + +static void Advance() +{ + g_Step++; + RunNextStep(); +} + +static void FinishTest() +{ + PrintToServer("[async-file-test] %s filesystem test %s (%d failure%s).", + g_ValveFS ? "Valve" : "OS", g_Failures ? "FAILED" : "PASSED", g_Failures, + g_Failures == 1 ? "" : "s"); + g_Running = false; +} diff --git a/plugins/testsuite/mock/test_forward_free_during_call.sp b/plugins/testsuite/mock/test_forward_free_during_call.sp new file mode 100644 index 00000000..0e6bb935 --- /dev/null +++ b/plugins/testsuite/mock/test_forward_free_during_call.sp @@ -0,0 +1,36 @@ +#pragma semicolon 1 +#include + +#pragma newdecls required + +public Plugin myinfo = +{ + name = "Forward Free During Call Test", + author = "AlliedModders LLC", + description = "Tests that freeing a private forward from within one of its own callbacks does not crash", + version = "1.0.0.0", + url = "https://www.sourcemod.net/" +}; + +public void OnPluginStart() { + SetTestContext("Forward Free During Call Test"); + Test_FreeForwardDuringOwnCall(); + PrintToServer("PASS"); +} + +void Test_FreeForwardDuringOwnCall() { + Handle fwd = CreateForward(ET_Ignore, Param_Cell); + AddToForward(fwd, INVALID_HANDLE, ForwardCall); + + Call_StartForward(fwd); + Call_PushCell(fwd); + Call_Finish(); + + // If we got here without crashing, the forward was safely destroyed. +} + +public void ForwardCall(Handle fwd) { + // Mirrors the NativeVotes pattern that triggered issue #1041: freeing the + // forward's own handle from within one of its own callbacks. + delete fwd; +} diff --git a/plugins/testsuite/test_mysql_connection_stress.sp b/plugins/testsuite/test_mysql_connection_stress.sp new file mode 100644 index 00000000..1df6f1e7 --- /dev/null +++ b/plugins/testsuite/test_mysql_connection_stress.sp @@ -0,0 +1,266 @@ +#pragma semicolon 1 +#pragma newdecls required + +#include + +public Plugin myinfo = +{ + name = "MySQL Connection Stress Test", + author = "AlliedModders", + description = "Exercises one MySQL connection from synchronous and threaded queries", + version = "1.0", + url = "https://www.sourcemod.net/" +}; + +static const char g_ConfigName[] = "mysql-stress"; +static const int g_DefaultRounds = 5000; +static const int g_AsyncQueriesPerRound = 4; + +static Database g_Database; +static DBStatement g_Statement; +static bool g_Running; +static int g_TargetRounds; +static int g_RoundsRun; +static int g_QueriesSubmitted; +static int g_QueriesCompleted; +static int g_ExpectedValue; +static int g_Failures; + +public void OnPluginStart() +{ + RegServerCmd("sm_mysql_stress", Command_Run, + "Stress a shared MySQL connection. Usage: sm_mysql_stress [rounds]"); +} + +public Action Command_Run(int args) +{ + if (g_Running) + { + PrintToServer("[mysql-stress] A test is already running."); + return Plugin_Handled; + } + + int rounds = g_DefaultRounds; + if (args >= 1) + { + char argument[16]; + GetCmdArg(1, argument, sizeof(argument)); + rounds = StringToInt(argument); + } + + if (rounds < 1 || rounds > 100000) + { + PrintToServer("[mysql-stress] Rounds must be between 1 and 100000."); + return Plugin_Handled; + } + + StartTest(rounds); + return Plugin_Handled; +} + +static void StartTest(int rounds) +{ + char error[256]; + g_Database = SQL_Connect(g_ConfigName, false, error, sizeof(error)); + if (g_Database == null) + { + PrintToServer("[mysql-stress] Connection to '%s' failed: %s", g_ConfigName, error); + return; + } + + if (!PrepareDatabase()) + { + CloseTestHandles(); + return; + } + + g_Statement = SQL_PrepareQuery(g_Database, + "UPDATE sm_mysql_connection_stress SET value = value + 1 WHERE id = ?", + error, sizeof(error)); + if (g_Statement == null) + { + PrintToServer("[mysql-stress] Failed to prepare statement: %s", error); + CloseTestHandles(); + return; + } + + g_Running = true; + g_TargetRounds = rounds; + g_RoundsRun = 0; + g_QueriesSubmitted = 0; + g_QueriesCompleted = 0; + g_ExpectedValue = 0; + g_Failures = 0; + + PrintToServer("[mysql-stress] Starting %d rounds (%d threaded queries per round).", + g_TargetRounds, g_AsyncQueriesPerRound); + CreateTimer(0.01, Timer_RunRound, _, TIMER_REPEAT); +} + +static bool PrepareDatabase() +{ + return FastQuery("CREATE TABLE IF NOT EXISTS sm_mysql_connection_stress (id INT PRIMARY KEY, value INT NOT NULL)", "create table") + && FastQuery("INSERT INTO sm_mysql_connection_stress (id, value) VALUES (1, 0) ON DUPLICATE KEY UPDATE value = 0", "reset table"); +} + +public Action Timer_RunRound(Handle timer) +{ + if (g_RoundsRun == g_TargetRounds) + { + FinishIfComplete(); + return Plugin_Stop; + } + + for (int i = 0; i < g_AsyncQueriesPerRound; i++) + { + g_Database.Query(OnThreadedQuery, + "SELECT SLEEP(0.002) AS delay, value FROM sm_mysql_connection_stress WHERE id = 1"); + g_QueriesSubmitted++; + } + + RunSynchronousRound(); + g_RoundsRun++; + return Plugin_Continue; +} + +static void RunSynchronousRound() +{ + char escaped[128]; + int written; + if (!SQL_EscapeString(g_Database, "quote ' test", escaped, sizeof(escaped), written) + || written == 0) + { + ReportDatabaseFailure("escape string", g_Database); + } + + if (FastQuery("UPDATE sm_mysql_connection_stress SET value = value + 1 WHERE id = 1", "fast query")) + { + g_ExpectedValue++; + } + + DBResultSet result = SQL_Query(g_Database, + "SELECT value FROM sm_mysql_connection_stress WHERE id = 1"); + if (result == null || !result.FetchRow()) + { + ReportDatabaseFailure("synchronous query", g_Database); + } + delete result; + + SQL_BindParamInt(g_Statement, 0, 1); + if (!SQL_Execute(g_Statement)) + { + ReportDatabaseFailure("prepared statement", g_Statement); + } + else + { + g_ExpectedValue++; + } + + if (g_RoundsRun % 64 == 0) + { + if (!SQL_SetCharset(g_Database, "utf8")) + { + ReportDatabaseFailure("set charset", g_Database); + } + + // This verifies that the public recursive lock still works when the + // driver also acquires it internally. + SQL_LockDatabase(g_Database); + bool succeeded = FastQuery( + "UPDATE sm_mysql_connection_stress SET value = value + 1 WHERE id = 1", + "explicit lock query"); + SQL_UnlockDatabase(g_Database); + + if (succeeded) + { + g_ExpectedValue++; + } + } +} + +public void OnThreadedQuery(Database db, DBResultSet results, const char[] error, any data) +{ + g_QueriesCompleted++; + + if (results == null) + { + ReportFailure("threaded query failed: %s", error); + } + else if (!results.FetchRow()) + { + ReportFailure("threaded query returned no row"); + } + else + { + results.FetchInt(1); + } + + FinishIfComplete(); +} + +static bool FastQuery(const char[] query, const char[] operation) +{ + if (SQL_FastQuery(g_Database, query)) + { + return true; + } + + ReportDatabaseFailure(operation, g_Database); + return false; +} + +static void FinishIfComplete() +{ + if (!g_Running || g_RoundsRun != g_TargetRounds || g_QueriesCompleted != g_QueriesSubmitted) + { + return; + } + + DBResultSet result = SQL_Query(g_Database, + "SELECT value FROM sm_mysql_connection_stress WHERE id = 1"); + if (result == null || !result.FetchRow()) + { + ReportDatabaseFailure("final value query", g_Database); + } + else + { + int actual = result.FetchInt(0); + if (actual != g_ExpectedValue) + { + ReportFailure("final value mismatch: expected %d, received %d", g_ExpectedValue, actual); + } + } + delete result; + + PrintToServer("[mysql-stress] %s: %d rounds, %d threaded queries, %d failure%s.", + g_Failures == 0 ? "PASS" : "FAIL", g_RoundsRun, g_QueriesCompleted, g_Failures, + g_Failures == 1 ? "" : "s"); + + g_Running = false; + CloseTestHandles(); +} + +static void ReportDatabaseFailure(const char[] operation, Handle handle) +{ + char error[256]; + SQL_GetError(handle, error, sizeof(error)); + ReportFailure("%s failed: %s", operation, error); +} + +static void ReportFailure(const char[] format, any ...) +{ + g_Failures++; + + if (g_Failures <= 10) + { + char message[256]; + VFormat(message, sizeof(message), format, 2); + PrintToServer("[mysql-stress] FAIL: %s", message); + } +} + +static void CloseTestHandles() +{ + delete g_Statement; + delete g_Database; +} diff --git a/plugins/testsuite/test_mysql_unload_stress.sp b/plugins/testsuite/test_mysql_unload_stress.sp new file mode 100644 index 00000000..0bd80026 --- /dev/null +++ b/plugins/testsuite/test_mysql_unload_stress.sp @@ -0,0 +1,86 @@ +#pragma semicolon 1 +#pragma newdecls required + +#include + +public Plugin myinfo = +{ + name = "MySQL unload stress test", + author = "AlliedModders", + description = "Verifies that threaded-query unload behavior is safe", + version = "1.0", + url = "https://www.sourcemod.net/" +}; + +#define DATABASE_CONFIG "mysql-stress" +#define RELOAD_COMMAND "sm plugins reload test_mysql_unload_stress" + +ConVar g_TestState; +ConVar g_TestCallback; +ConVar g_TestStartedAt; + +public void OnPluginStart() +{ + g_TestState = CreateConVar("sm_mysql_unload_stress_state", "0", "Internal state for the MySQL unload stress test."); + g_TestCallback = CreateConVar("sm_mysql_unload_stress_callback", "0", "Internal callback marker for the MySQL unload stress test."); + g_TestStartedAt = CreateConVar("sm_mysql_unload_stress_started_at", "0", "Internal start timestamp for the MySQL unload stress test."); + + RegConsoleCmd("sm_mysql_unload_stress", Command_StartStress, "Run the MySQL threaded-query unload stress test."); + + if (g_TestState.IntValue == 1) + { + float elapsed = GetEngineTime() - g_TestStartedAt.FloatValue; + if (g_TestCallback.IntValue == 0 && elapsed < 2.0) + { + PrintToServer("[mysql-unload-stress] PASS: discard reloaded promptly and did not run the old callback."); + } + else if (g_TestCallback.IntValue == 1 && elapsed >= 4.0) + { + PrintToServer("[mysql-unload-stress] PASS: wait preserved the historical callback-before-unload behavior."); + } + else + { + LogError("[mysql-unload-stress] FAIL: unexpected unload behavior (callback %d, elapsed %.2f seconds).", g_TestCallback.IntValue, elapsed); + } + g_TestState.IntValue = 0; + } +} + +public Action Command_StartStress(int client, int args) +{ + if (g_TestState.IntValue != 0) + { + ReplyToCommand(client, "[mysql-unload-stress] A test is already in progress."); + return Plugin_Handled; + } + + char error[256]; + Database db = SQL_Connect(DATABASE_CONFIG, false, error, sizeof(error)); + if (db == null) + { + ReplyToCommand(client, "[mysql-unload-stress] Could not connect: %s", error); + return Plugin_Handled; + } + + g_TestState.IntValue = 1; + g_TestCallback.IntValue = 0; + g_TestStartedAt.FloatValue = GetEngineTime(); + SQL_TQuery(db, OnSlowQueryComplete, "SELECT SLEEP(5)"); + delete db; + + CreateTimer(0.25, Timer_ReloadPlugin); + ReplyToCommand(client, "[mysql-unload-stress] Started a five-second query; reloading this plugin shortly."); + return Plugin_Handled; +} + +public Action Timer_ReloadPlugin(Handle timer) +{ + ServerCommand(RELOAD_COMMAND); + return Plugin_Stop; +} + +public void OnSlowQueryComplete(Database db, DBResultSet results, const char[] error, any data) +{ + g_TestCallback.IntValue = 1; + PrintToServer("[mysql-unload-stress] The old query callback completed before unload."); +} \ No newline at end of file diff --git a/plugins/testsuite/test_usermsg_stack_alignment.sp b/plugins/testsuite/test_usermsg_stack_alignment.sp new file mode 100644 index 00000000..18020781 --- /dev/null +++ b/plugins/testsuite/test_usermsg_stack_alignment.sp @@ -0,0 +1,64 @@ +#pragma semicolon 1 +#pragma newdecls required + +#include + +bool g_SeenMessages[255]; +int g_HookedMessages; +int g_InterceptedMessages; + +public Plugin myinfo = +{ + name = "User Message Stack Alignment Test", + author = "AlliedModders LLC", + description = "Exercises pre user-message interception callbacks", + version = "1.0.0.0", + url = "https://www.sourcemod.net/" +}; + +public void OnPluginStart() +{ + if (GetEngineVersion() != Engine_CSS) + { + SetFailState("This test is intended for Counter-Strike: Source."); + return; + } + + for (int id = 0; id < sizeof(g_SeenMessages); id++) + { + UserMsg message = view_as(id); + char name[64]; + if (!GetUserMessageName(message, name, sizeof(name))) + continue; + + HookUserMessage(message, OnUserMessage, true); + g_HookedMessages++; + } + + RegServerCmd("sm_test_usermsg_stack_alignment_status", Command_Status); + LogMessage("Hooked %d user messages for pre-interception.", g_HookedMessages); +} + +public Action Command_Status(int args) +{ + LogMessage("Intercepted %d user messages.", g_InterceptedMessages); + return Plugin_Handled; +} + +public Action OnUserMessage(UserMsg message, BfRead buffer, const int[] players, + int playersNum, bool reliable, bool init) +{ + int id = view_as(message); + g_InterceptedMessages++; + + // Log each message type once so normal game traffic does not flood the log. + if (!g_SeenMessages[id]) + { + char name[64]; + GetUserMessageName(message, name, sizeof(name)); + LogMessage("Intercepted %s (%d) for the first time.", name, id); + g_SeenMessages[id] = true; + } + + return Plugin_Continue; +} diff --git a/pr-2547-followup.patch b/pr-2547-followup.patch new file mode 100644 index 00000000..42b8cf07 --- /dev/null +++ b/pr-2547-followup.patch @@ -0,0 +1,63 @@ +diff --git a/extensions/bintools/x64_macros.h b/extensions/bintools/x64_macros.h +--- a/extensions/bintools/x64_macros.h ++++ b/extensions/bintools/x64_macros.h +@@ -187,9 +187,9 @@ + +-inline void X64_Mov_RmRSP_Disp32_Reg(JitWriter *jit, jit_uint8_t src, jit_int8_t disp) ++inline void X64_Mov_RmRSP_Disp32_Reg(JitWriter *jit, jit_uint8_t src, jit_int32_t disp) + { + jit->write_ubyte(x64_rex(true, src, 0, kREG_RSP)); + jit->write_ubyte(IA32_MOV_RM_REG); + jit->write_ubyte(ia32_modrm(MOD_DISP32, src & 7, kREG_RSP)); + jit->write_ubyte(ia32_sib(NOSCALE, kREG_NOIDX, kREG_RSP)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -336,7 +336,7 @@ + jit->write_ubyte(0x0F); + jit->write_ubyte(0x29); + jit->write_ubyte(ia32_modrm(MOD_DISP32, src & 7, dest & 7)); + if ((dest & 7) == kREG_RSP) + jit->write_ubyte(ia32_sib(NOSCALE, kREG_NOIDX, dest & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -348,7 +348,7 @@ + jit->write_ubyte(0x0F); + jit->write_ubyte(0x11); + jit->write_ubyte(ia32_modrm(MOD_DISP32, src & 7, dest & 7)); + if ((dest & 7) == kREG_RSP) + jit->write_ubyte(ia32_sib(NOSCALE, kREG_NOIDX, dest & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -418,5 +418,5 @@ + jit->write_ubyte(0x0F); + jit->write_ubyte(0x28); + jit->write_ubyte(ia32_modrm(MOD_DISP32, dest & 7, src & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -428,5 +428,5 @@ + jit->write_ubyte(0x0F); + jit->write_ubyte(0x10); + jit->write_ubyte(ia32_modrm(MOD_DISP32, dest & 7, src & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -480,6 +480,6 @@ + jit->write_ubyte(0x66); + jit->write_ubyte(0x0F); + jit->write_ubyte(0x28); + jit->write_ubyte(ia32_modrm(MOD_DISP32, dest & 7, src & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } +@@ -491,6 +491,6 @@ + jit->write_ubyte(0x66); + jit->write_ubyte(0x0F); + jit->write_ubyte(0x10); + jit->write_ubyte(ia32_modrm(MOD_DISP32, dest & 7, src & 7)); +- jit->write_byte(disp); ++ jit->write_int32(disp); + } diff --git a/scratch_issue1685_plan.md b/scratch_issue1685_plan.md new file mode 100644 index 00000000..6ab5197a --- /dev/null +++ b/scratch_issue1685_plan.md @@ -0,0 +1,125 @@ +# Fix Plan: Dangling `IGameEvent` pointer when a plugin blocks an event + +**Issue:** [alliedmodders/sourcemod#1685](https://github.com/alliedmodders/sourcemod/issues/1685) +**Area:** `core/EventManager.cpp`, `core/EventManager.h` (per-SDK core) + +## Root cause (confirmed) + +`EventManager::OnFireEvent` (`core/EventManager.cpp:436-440`) frees the event +**inside the pre-hook** and then returns `MRES_SUPERCEDE`: + +```cpp +if (res >= Pl_Handled) +{ + gameevents->FreeEvent(pEvent); + RETURN_META_VALUE(MRES_SUPERCEDE, false); +} +``` + +`MRES_SUPERCEDE` only suppresses the engine's original `FireEvent` β€” it does **not** +stop lower-priority hooks in the same SourceHook chain. Those hooks (other +extensions / Metamod plugins) then run with a freed `pEvent` β†’ dangling pointer / crash. + +The reporter's suggested fix ("just remove the `FreeEvent()` calls") is wrong: in the +superseded path the engine never runs, so nothing else frees the event. Removing the +calls leaks one `IGameEvent` every time a plugin blocks an event. + +## Key facts that make the real fix safe + +- **SourceHook always runs the post-hook even after a supersede.** Proof from the + existing code: the pre-hook pushes to `m_EventStack` unconditionally (`:407`/`:444`) + and the post-hook pops unconditionally (`:513`). If post-hooks were skipped on + supersede, the stack would desync on every blocked event and SM would have been + crashing for years. It doesn't β€” so the post-hook is a reliable place to defer work. +- **The post-hook never touches the real `pEvent`.** In `OnFireEvent_Post`, the + non-copy path pushes `BAD_HANDLE` (`:484`) and the copy path uses the *duplicated* + event from `m_EventCopies` (`:478`), not `pEvent`. So `pEvent` is free to be freed there. +- **Freeing in the post-hook matches engine timing.** Normally the engine's `FireEvent` + frees the event between the pre and post phases, so post-hooks already can't rely on + `pEvent`. Deferring the free to SM's post-hook reproduces that contract instead of + violating it β€” no regression. +- The handle freed at `:428` does **not** free `pEvent` (the stack-local `EventInfo` + has `pOwner == NULL`, so `OnHandleDestroy` is a no-op for it). The explicit + `FreeEvent` at `:438` is the only thing releasing the event, so moving that single + call is the entire behavioral change. + +## Changes + +### 1. `core/EventManager.h` + +Add a parallel stack to carry the deferred free across the preβ†’post transition, +pushed/popped in lockstep with `m_EventStack`: + +```cpp +CStack m_EventDeferredFree; // pEvent to free in post-hook, or NULL +``` + +A pointer stack (rather than a bool stack) means the post-hook frees the exact +pointer captured at supersede time β€” robust against nested/reentrant `FireEvent` +calls, which the stack design already anticipates. + +### 2. `core/EventManager.cpp` β€” `OnFireEvent` (pre-hook) + +Push to `m_EventDeferredFree` in lockstep with `m_EventStack` in **both** branches +(hooked and unhooked) so the two stacks stay balanced: + +- unhooked branch (`:444`): push `NULL`. +- hooked branch: push `NULL` by default. + +Replace the blocked path (`:436-440`): + +```cpp +if (res >= Pl_Handled) +{ + // Defer free to the post-hook so lower-priority hooks in the + // chain still see a valid event (issue #1685). + m_EventDeferredFree.top() = pEvent; // overwrite the NULL pushed above + RETURN_META_VALUE(MRES_SUPERCEDE, false); +} +``` + +(Exact mechanism β€” top-overwrite vs. deferring the push β€” finalized during +implementation; intent is one push per fire, balanced with `m_EventStack`.) + +### 3. `core/EventManager.cpp` β€” `OnFireEvent_Post` + +After the existing post-forward work, alongside the `m_EventStack.pop()` (`:513`), +pop the parallel stack and free if set: + +```cpp +IGameEvent *pDeferred = m_EventDeferredFree.front(); +m_EventDeferredFree.pop(); +if (pDeferred) + gameevents->FreeEvent(pDeferred); +``` + +Guard stack balance for the early `!pEvent` returns: the post-hook `!pEvent` return +(`:462`) and the pre-hook `!pEvent` return (`:394`) both return **before** any push, +so neither must pop. Verify both paths stay symmetric β€” this is the one bit of +bookkeeping to get exactly right. + +## Test + +Add a mock-testsuite plugin under `plugins/testsuite/mock/` (register in +`.github/workflows/mocktest.yml`): hook a common event in `EventHookMode_Pre`, return +`Plugin_Handled`, and confirm no crash / correct suppression. + +To actually exercise the dangling-pointer path we need a *second* consumer of +`IGameEventManager2::FireEvent` at lower priority; since that's hard to stage from +pure SourcePawn, document the manual repro (two extensions, one blocking) in the PR +and rely on the mock test for the no-regression guarantee. + +## Build & verify + +- Rebuild core against mock: `--sdks=mock --targets=x86_64`, assemble gamedir, run the + new test via `srcds ... -run` and confirm no `FAIL`. +- This is per-SDK core code (not logic), so it compiles once per SDK, but the change is + engine-agnostic; a mock build is sufficient to validate. + +## Scope / risk notes + +- Contained to `EventManager.{h,cpp}`; no API/`.inc` surface change, no gamedata. +- The bug is niche (needs a second lower-priority `FireEvent` hooker), which is why + it's sat open since 2022 β€” worth calling out in the PR so reviewers understand the trigger. +- Per `CLAUDE.md`, nontrivial changes should be discussed with the dev team first β€” this + is PR-with-issue-reference material, not a drive-by. diff --git a/sourcepawn b/sourcepawn index 861f7293..6797adb4 160000 --- a/sourcepawn +++ b/sourcepawn @@ -1 +1 @@ -Subproject commit 861f72931ad0d2a9b722d2e9143e703e6ff53953 +Subproject commit 6797adb45c7335485eb529b8255a7215f1011f84