From bc9d488c4228a32aedb7ec69f2d8d336e3da4859 Mon Sep 17 00:00:00 2001 From: esrrhs Date: Tue, 1 Dec 2026 21:14:08 +0800 Subject: [PATCH] Add multi-state sessions, CPU v2 profiles, and regression tests Align vLua with recent pLua tooling and session APIs: write CPU v2 .pro metadata, add tools/vlua -proto export with Go tests, and replace the removed google-perftools apt package in CI. Give each lua_State its own profiler session with status/close/config and a configurable SIGPROF interval, keep hookso lrealstart/lrealstop, and return clear errors when the target C function cannot be found. Register attribution ranking, API, hot-reload stress, converter, and two-state unit tests in ctest. Document Lua 5.3.x-only support. --- .github/workflows/ccpp.yml | 11 +- .gitignore | 1 + README.md | 329 +++++++----- README_CN.md | 59 +- src/vlua.cpp | 957 ++++++++++++++++++++++++--------- test/CMakeLists.txt | 66 ++- test/bench_vlua.lua | 3 + test/test_api.lua | 75 +++ test/test_funcname.lua | 69 ++- test/test_getstr.lua | 84 ++- test/test_hotreload.lua | 5 +- test/test_hotreload_stress.lua | 7 +- test/test_vlua.lua | 119 +++- test/unit_test.cpp | 158 ++++++ tools/show.sh | 17 +- tools/vlua.go | 215 +++++++- tools/vlua_test.go | 292 ++++++++++ 17 files changed, 1964 insertions(+), 503 deletions(-) create mode 100644 test/test_api.lua create mode 100644 test/unit_test.cpp create mode 100644 tools/vlua_test.go diff --git a/.github/workflows/ccpp.yml b/.github/workflows/ccpp.yml index b60ef22..d38f4da 100644 --- a/.github/workflows/ccpp.yml +++ b/.github/workflows/ccpp.yml @@ -19,7 +19,11 @@ jobs: - name: Install Dependencies run: | sudo apt-get update - sudo apt-get install -y build-essential cmake golang-go graphviz google-perftools + # google-perftools binary package was removed on Ubuntu 26.04+; + # use the Go pprof binary for call-graph --dot in show.sh. + sudo apt-get install -y build-essential cmake golang-go graphviz + go install github.com/google/pprof@latest + echo "$(go env GOPATH)/bin" >> "$GITHUB_PATH" - name: Configure CMake run: | @@ -33,6 +37,11 @@ jobs: run: | ctest --test-dir build --output-on-failure + - name: Run Converter Tests + run: | + go test + working-directory: tools + - name: Run Example & Test Visualization Tools run: | cd test diff --git a/.gitignore b/.gitignore index 8aa2d14..1535290 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,7 @@ src/lzio.h *.prof *.dot *.fl +*.pb.gz *.svg test/*.png !test/getstr.png diff --git a/README.md b/README.md index 0350335..2b0ef94 100644 --- a/README.md +++ b/README.md @@ -1,149 +1,180 @@ -# vLua - -[English](README.md) | [中文说明](README_CN.md) - -[](https://github.com/esrrhs/vLua) -[](https://github.com/esrrhs/vLua) -[](https://github.com/esrrhs/vLua/actions) - -Attribute Lua VM C-function CPU time back to Lua source lines. - -## Overview - -`perf` can show that `luaH_getshortstr` costs 13% CPU, but not **which Lua lines** contribute that 13%. **vLua** samples only while a chosen Lua VM C function is on CPU, then attributes those samples to Lua source locations with full call stacks. - -## Features - -- **Precise**: SIGPROF sampling + PC-range filter — capture Lua stacks only when the target C function is executing -- **Lightweight**: ~0.03% overhead at 100Hz — safe to leave on in production -- **Safe**: signal-handler parses stacks in place; ring buffer stores value types only; SIGSEGV trampoline covers hot-reload races -- **Compatible**: writes [pLua](https://github.com/esrrhs/pLua)-format `.pro` files for pprof / [FlameGraph](https://github.com/brendangregg/FlameGraph) -- **Flexible**: target C function name is a parameter — profile any Lua VM internal - -## Build - -vLua vendors **Lua 5.3.6** headers (private VM structs). CMake extracts `dep/lua-5.3.6.tar.gz` automatically. - -```shell -./build.sh -# or: -cmake -B build -DCMAKE_BUILD_TYPE=Release -cmake --build build -``` - -Outputs: - -- `bin/libvlua.so` — sampler shared library -- `bin/vlua` — profile converter (if Go is available) -- `build/lua/lua53` — matching Lua 5.3.6 interpreter for tests - -## Test - -```shell -ctest --test-dir build --output-on-failure -``` - -Or run a script directly with the vendored interpreter: - -```shell -cd test -../build/lua/lua53 test_getstr.lua -``` - -## Usage - -### Embed in Lua - -```lua -local v = require "libvlua" - --- Arg 1: Lua VM C function to sample --- Arg 2: output .pro file (pLua-compatible) -v.start("luaH_getshortstr", "call.pro") - -do_some_thing() - --- Stop sampling; returns a text hotspot summary -local text = v.stop() -print(text) -``` - -### Inject with [hookso](https://github.com/esrrhs/hookso) - -```shell -# a) Get lua_State* (e.g. first arg of lua_settop in xxx.so) -./hookso arg $PID xxx.so lua_settop 1 -# => 123456 - -# b) Load libvlua.so -./hookso dlopen $PID ./libvlua.so - -# c) Start: lrealstart(L, "luaH_getshortstr", "./call.pro") -./hookso call $PID libvlua.so lrealstart i=123456 s="luaH_getshortstr" s="./call.pro" - -# d) Stop: lrealstop(L) -./hookso call $PID libvlua.so lrealstop i=123456 -``` - -## Visualization & Tools - -The `tools/` directory converts `.pro` profile data into FlameGraph SVGs and call graph images. - -### Prerequisites (Optional) - -- **FlameGraph**: `show.sh` fetches `flamegraph.pl` from GitHub if not found locally or in `PATH`. On CentOS/RHEL you may need `yum install perl-open`. -- **Graphviz** (call graph PNG): `sudo apt install graphviz` / `sudo yum install graphviz` -- **pprof** (call graph DOT/PNG): `sudo apt install google-perftools` / `sudo yum install gperftools` - -### Generate Visualizations - -```shell -cd tools -./show.sh ../test -``` - -This generates: - -- `.fl`: Folded stack traces -- `.svg`: Interactive SVG flame graph -- `.prof`: Symbolized pprof profile -- `.dot`: Graphviz call graph -- `.png`: Rendered PNG call graph (if graphviz and pprof are installed) - -`show.sh` looks for `bin/vlua` (built by CMake) or builds `tools/vlua` via Go on demand. - -## Example - -Simulated table get-by-string hotspots (nested `player.role.battle.stat.kill` chains), sampling `luaH_getshortstr`: - -#### Call graph - -![image](test/getstr.png) - -#### Text summary from `v.stop()` - -``` -Top hotspots (source:line -> count, pct of analysable) - count pct location - 152 31.67% @test_getstr.lua:24 -- calc_damage: player.role.battle.weapon.damage = ... - 131 27.29% @test_getstr.lua:36 -- update_kill: player.role.battle.stat.kill = ... - 63 13.12% @test_getstr.lua:49 -- update_pos: player.role.pos.y = ... - 57 11.88% @test_getstr.lua:48 -- update_pos: player.role.pos.x = ... - ... -``` - -## Notes - -- Do **not** strip the host binary — static symbols like `luaH_getshortstr` live in `.symtab` - Verify: `nm | grep luaH_getshortstr` -- Safe during hot-reload (value-type samples + pointer checks + SIGSEGV trampoline) -- Currently assumes a single Lua VM (`g_L`); multi-`lua_State` needs extension -- Headers / test interpreter are Lua **5.3.6**; host process must use a matching 5.3.x VM layout - -## Related - -[lua-family-bucket](https://github.com/esrrhs/lua-family-bucket) · [pLua](https://github.com/esrrhs/pLua) · [hookso](https://github.com/esrrhs/hookso) - -## License - -MIT +# vLua + +[English](README.md) | [中文说明](README_CN.md) + +[](https://github.com/esrrhs/vLua) +[](https://github.com/esrrhs/vLua) +[](https://github.com/esrrhs/vLua/actions) + +Attribute Lua VM C-function CPU time back to Lua source lines. + +## Overview + +`perf` can show that `luaH_getshortstr` costs 13% CPU, but not **which Lua lines** contribute that 13%. **vLua** samples only while a chosen Lua VM C function is on CPU, then attributes those samples to Lua source locations with full call stacks. + +## Features + +- **Precise**: SIGPROF sampling + PC-range filter — capture Lua stacks only when the target C function is executing +- **Lightweight**: ~0.03% overhead at 100Hz — safe to leave on in production +- **Safe**: signal-handler parses stacks in place; ring buffer stores value types only; SIGSEGV trampoline covers hot-reload races +- **Compatible**: writes [pLua](https://github.com/esrrhs/pLua)-format `.pro` files (CPU v2 metadata) for pprof / [FlameGraph](https://github.com/brendangregg/FlameGraph) +- **Flexible**: target C function name is a parameter — profile any Lua VM internal +- **Multi-state**: each `lua_State` has its own profiler session; stopping one does not stop others + +## Platform and Lua version + +- **Lua 5.3.x only.** Headers and the test interpreter are vendored **Lua 5.3.6** private VM structs (`lobject.h` / `lstate.h`). The host process must use a matching 5.3.x layout. **Lua 5.4 is out of scope** and is rejected at `start()`. +- **Linux is the supported platform** (SIGPROF / `ITIMER_PROF` + ELF symbol lookup). CI runs on `ubuntu-latest`. Other Unix systems are untested. There is no Windows port. + +## Build + +CMake extracts `dep/lua-5.3.6.tar.gz` automatically. + +```shell +./build.sh +# or: +cmake -B build -DCMAKE_BUILD_TYPE=Release +cmake --build build +``` + +Outputs: + +- `bin/libvlua.so` — sampler shared library +- `bin/vlua` — profile converter (if Go is available) +- `build/lua/lua53` — matching Lua 5.3.6 interpreter for tests + +## Test + +```shell +ctest --test-dir build --output-on-failure +# converter tests (also part of ctest when Go is available): +cd tools && go test +``` + +Registered tests include attribution ranking (`test_getstr`, `test_vlua`), function-name recovery (`test_funcname`), session APIs and errors (`test_api`), two-`lua_State` independence (`unit_test`), and hot-reload safety (including a stress run). A crash in the stress test is a failure. + +`test/bench_vlua.lua` is an optional local overhead experiment and is **not** in CI (the numbers are statistical, not a pass/fail gate): + +```shell +cd test +../build/lua/lua53 bench_vlua.lua +``` + +## Usage + +### Embed in Lua + +```lua +local v = require "libvlua" + +-- Arg 1: Lua VM C function to sample +-- Arg 2: output .pro file (pLua-compatible, CPU v2) +-- Arg 3 (optional): sample interval in milliseconds (default 10) +v.start("luaH_getshortstr", "call.pro") +-- or: v.start("luaH_getshortstr", "call.pro", 5) + +do_some_thing() + +-- Stop sampling; returns a text hotspot summary +local text, err = v.stop() +print(text) + +-- Session helpers (per lua_State) +local st = v.status() -- running, target, output, interval_ms, samples, ticks, hits, backend, config +v.set_config({ cpu_interval_ms = 5 }) -- default for later start() calls +local cfg = v.get_config() +v.close() -- stop if needed and drop the session +``` + +`start()` returns `0` on success, or `nil, error` on failure (target C function not found, stripped symbols, Lua version / VM layout mismatch, already running, conflicting SIGPROF interval, and similar). `stop()` returns the text report, or `nil, error`. + +Each `lua_State` has its own session. You can profile two VMs at once; they must use the same sample interval because `ITIMER_PROF` is process-wide. Sessions are **not OS-thread safe**: call the APIs and run the VM on the same thread (same limitation as pLua). The SIGPROF handler never calls Lua APIs, allocates, or takes locks. + +The default interval is 10 ms (100 Hz), overridable with `v.start(..., interval_ms)`, `v.set_config`, or the `VLUA_CPU_INTERVAL_MS` environment variable. + +### Inject with [hookso](https://github.com/esrrhs/hookso) + +`lrealstart` / `lrealstop` signatures are unchanged: + +```shell +# a) Get lua_State* (e.g. first arg of lua_settop in xxx.so) +./hookso arg $PID xxx.so lua_settop 1 +# => 123456 + +# b) Load libvlua.so +./hookso dlopen $PID ./libvlua.so + +# c) Start: lrealstart(L, "luaH_getshortstr", "./call.pro") +./hookso call $PID libvlua.so lrealstart i=123456 s="luaH_getshortstr" s="./call.pro" + +# d) Stop: lrealstop(L) +./hookso call $PID libvlua.so lrealstop i=123456 +``` + +## Visualization & Tools + +The `tools/` directory converts `.pro` profile data into FlameGraph SVGs, call graphs, and modern pprof proto files. + +### Prerequisites (Optional) + +- **FlameGraph**: `show.sh` fetches `flamegraph.pl` from GitHub if not found locally or in `PATH`. On CentOS/RHEL you may need `yum install perl-open`. +- **Graphviz** (call graph PNG): `sudo apt install graphviz` / `sudo yum install graphviz` +- **pprof** (call graph DOT/PNG): `go install github.com/google/pprof@latest` (the `google-perftools` apt package was removed on newer Ubuntu) + +### Generate Visualizations + +```shell +cd tools +./show.sh ../test + +# or invoke the converter directly: +../bin/vlua -i ../test/getstr.pro -proto getstr.pb.gz -pprof getstr.prof -flame getstr.fl +go tool pprof -top getstr.pb.gz +``` + +This generates: + +- `.fl`: Folded stack traces +- `.svg`: Interactive SVG flame graph +- `.prof`: Legacy symbolized pprof profile +- `.pb.gz`: gzip `profile.proto` for modern `go tool pprof` +- `.dot` / `.png`: Graphviz call graph (if pprof and graphviz are installed) + +`show.sh` looks for `bin/vlua` (built by CMake) or builds `tools/vlua` via Go on demand. The converter has no third-party Go dependencies. Legacy (pre-v2) `.pro` files still parse; `-pprof` and `-flame` work on them. `-proto` requires a v2 CPU profile (vLua writes these by default). + +## Example + +Simulated table get-by-string hotspots (nested `player.role.battle.stat.kill` chains), sampling `luaH_getshortstr`: + +#### Call graph + +![image](test/getstr.png) + +#### Text summary from `v.stop()` + +``` +Top hotspots (source:line -> count, pct of analysable) + count pct location + 152 31.67% @test_getstr.lua:24 -- calc_damage: player.role.battle.weapon.damage = ... + 131 27.29% @test_getstr.lua:36 -- update_kill: player.role.battle.stat.kill = ... + 63 13.12% @test_getstr.lua:49 -- update_pos: player.role.pos.y = ... + 57 11.88% @test_getstr.lua:48 -- update_pos: player.role.pos.x = ... + ... +``` + +## Notes + +- On optimized Lua builds, tiny helpers such as `luaH_getshortstr` are often **inlined** into `luaH_get` / `luaH_getstr`. If `start()` succeeds but the report has 0 hits, sample the caller that still has a symbol (`nm | grep luaH_get`). CI attribution tests use `luaH_get` for that reason. +- Do **not** strip the host binary — static symbols like `luaH_getshortstr` live in `.symtab` + Verify: `nm | grep luaH_getshortstr` +- Safe during hot-reload (value-type samples + pointer checks + SIGSEGV trampoline) +- A session is bound to the `lua_State*` passed to `start()` (coroutine threads are separate states) +- Headers / test interpreter are Lua **5.3.6**; Lua 5.4 is not supported + +## Related + +[lua-family-bucket](https://github.com/esrrhs/lua-family-bucket) · [pLua](https://github.com/esrrhs/pLua) · [hookso](https://github.com/esrrhs/hookso) + +## License + +MIT diff --git a/README_CN.md b/README_CN.md index e28aa25..7f00096 100644 --- a/README_CN.md +++ b/README_CN.md @@ -17,12 +17,18 @@ perf 能看到 `luaH_getshortstr` 占 13% CPU,但看不到是哪些 Lua 代码 - **精准**:SIGPROF 定时采样 + PC 范围判断,只在目标 C 函数执行时捕获 Lua 调用栈 - **轻量**:100Hz 采样下 overhead ≈ 0.03%,可长期常开 - **安全**:signal handler 内就地解析,ring buffer 只存值类型;SIGSEGV trampoline 兜底,热更期间不会崩 -- **兼容**:输出 [pLua](https://github.com/esrrhs/pLua) 格式的 `.pro` 文件,可直接用 pprof、[火焰图](https://github.com/brendangregg/FlameGraph) 工具链分析 +- **兼容**:输出 [pLua](https://github.com/esrrhs/pLua) 格式的 `.pro` 文件(含 CPU v2 元数据),可直接用 pprof、[火焰图](https://github.com/brendangregg/FlameGraph) 工具链分析 - **灵活**:目标函数名作为参数传入,可以分析任意 Lua VM 内部 C 函数 +- **多 VM**:每个 `lua_State` 有独立的 profiler session,停其中一个不会影响其他 + +## 平台与 Lua 版本 + +- **仅支持 Lua 5.3.x。** 头文件与测试解释器为内置的 **Lua 5.3.6** 私有 VM 结构体(`lobject.h` / `lstate.h`)。宿主进程必须使用匹配的 5.3.x 布局。**Lua 5.4 不在本次支持范围**,`start()` 会直接拒绝。 +- **官方支持平台为 Linux**(SIGPROF / `ITIMER_PROF` + ELF 符号查找)。CI 跑在 `ubuntu-latest`。其他 Unix 未测试,没有 Windows 移植。 ## 编译 -vLua 内置 **Lua 5.3.6** 头文件(需要私有 VM 结构体)。CMake 会自动解压 `dep/lua-5.3.6.tar.gz`。 +CMake 会自动解压 `dep/lua-5.3.6.tar.gz`。 ```shell ./build.sh @@ -41,13 +47,17 @@ cmake --build build ```shell ctest --test-dir build --output-on-failure +# 转换工具测试(有 Go 时也会编进 ctest): +cd tools && go test ``` -或直接用内置解释器跑脚本: +已注册的测试包括热点排序断言(`test_getstr`、`test_vlua`)、函数名恢复(`test_funcname`)、会话 API 与错误路径(`test_api`)、两个 `lua_State` 互不影响(`unit_test`),以及热更安全(含压力测试)。压力测试里崩溃即失败。 + +`test/bench_vlua.lua` 是可选的本地开销实验,**不进入 CI**(统计结果不适合做通过/失败门槛): ```shell cd test -../build/lua/lua53 test_getstr.lua +../build/lua/lua53 bench_vlua.lua ``` ## 使用 @@ -58,18 +68,34 @@ cd test local v = require "libvlua" -- 参数1:要采样的 C 函数名 --- 参数2:采样结果文件(pLua 兼容的二进制格式) +-- 参数2:采样结果文件(pLua 兼容的 CPU v2 .pro) +-- 参数3(可选):采样间隔,毫秒(默认 10) v.start("luaH_getshortstr", "call.pro") +-- 或:v.start("luaH_getshortstr", "call.pro", 5) do_some_thing() -- 结束采样,返回文本摘要报告 -local text = v.stop() +local text, err = v.stop() print(text) + +-- 每个 lua_State 一套会话 API +local st = v.status() -- running, target, output, interval_ms, samples, ticks, hits, backend, config +v.set_config({ cpu_interval_ms = 5 }) -- 影响之后的 start() +local cfg = v.get_config() +v.close() -- 如有必要先 stop,再释放 session ``` +`start()` 成功返回 `0`,失败返回 `nil, error`(目标 C 函数找不到、符号被 strip、Lua 版本或 VM 布局不匹配、重复 start、SIGPROF 间隔冲突等)。`stop()` 成功返回文本报告,失败返回 `nil, error`。 + +每个 `lua_State` 有独立 session,可以同时给两个 VM 采样;因为 `ITIMER_PROF` 是进程级的,它们必须使用相同的采样间隔。会话**不是 OS 线程安全的**:API 调用和 VM 执行需要在同一线程(与 pLua 相同)。SIGPROF handler 中不会调用 Lua API、不会分配内存、也不会加锁。 + +默认间隔 10ms(100Hz),也可通过 `v.start(..., interval_ms)`、`v.set_config` 或环境变量 `VLUA_CPU_INTERVAL_MS` 修改。 + ### 用 [hookso](https://github.com/esrrhs/hookso) 注入 +`lrealstart` / `lrealstop` 的签名保持兼容: + ```shell # a) 获取进程中的 lua_State 指针,比如进程的 xxx.so 调用了 lua_settop(L),取第一个参数 ./hookso arg $PID xxx.so lua_settop 1 @@ -87,30 +113,34 @@ print(text) ## 可视化与工具 -`tools/` 目录用于把 `.pro` 采样数据转换成火焰图 SVG 和调用图。 +`tools/` 目录用于把 `.pro` 采样数据转换成火焰图 SVG、调用图和现代 pprof proto。 ### 可选依赖 - **FlameGraph**:本地或 `PATH` 中没有时,`show.sh` 会从 GitHub 自动下载 `flamegraph.pl`。CentOS/RHEL 可能需要 `yum install perl-open`。 - **Graphviz**(调用图 PNG):`sudo apt install graphviz` / `sudo yum install graphviz` -- **pprof**(调用图 DOT/PNG):`sudo apt install google-perftools` / `sudo yum install gperftools` +- **pprof**(调用图 DOT/PNG):`go install github.com/google/pprof@latest`(较新的 Ubuntu 已移除 `google-perftools` apt 包) ### 生成可视化 ```shell cd tools ./show.sh ../test + +# 或直接调用转换工具: +../bin/vlua -i ../test/getstr.pro -proto getstr.pb.gz -pprof getstr.prof -flame getstr.fl +go tool pprof -top getstr.pb.gz ``` 会生成: - `.fl`:折叠调用栈 - `.svg`:可交互火焰图 -- `.prof`:符号化 pprof profile -- `.dot`:Graphviz 调用图 -- `.png`:调用图 PNG(需 graphviz + pprof) +- `.prof`:旧版符号化 pprof profile +- `.pb.gz`:gzip `profile.proto`,可供现代 `go tool pprof` 直接读取 +- `.dot` / `.png`:调用图(需 pprof + graphviz) -`show.sh` 会优先使用 CMake 产出的 `bin/vlua`,否则在有 Go 时现场编译 `tools/vlua`。 +`show.sh` 会优先使用 CMake 产出的 `bin/vlua`,否则在有 Go 时现场编译 `tools/vlua`。转换工具没有第三方 Go 依赖。旧版(无 v2 头)`.pro` 仍可解析,`-pprof` / `-flame` 可用;`-proto` 需要 v2 CPU profile(vLua 默认就写这个格式)。 ## 示例 @@ -134,11 +164,12 @@ Top hotspots (source:line -> count, pct of analysable) ## 注意事项 +- 在优化编译的 Lua 里,`luaH_getshortstr` 这类小函数常被**内联**进 `luaH_get` / `luaH_getstr`。如果 `start()` 成功但报告命中为 0,请改采仍然保留独立符号的调用者(`nm | grep luaH_get`)。CI 里的归因测试因此使用 `luaH_get`。 - 二进制不要 `strip`,`luaH_getshortstr` 等 static 符号只在 `.symtab` 中 验证:`nm | grep luaH_getshortstr` - 热更期间可以常开,不会崩(三层防护:值类型 Sample + 指针校验 + SIGSEGV trampoline) -- 当前假设单 Lua VM(`g_L`),多 lua_State 场景需要扩展 -- 头文件与测试解释器为 Lua **5.3.6**,宿主进程需使用匹配的 5.3.x VM 布局 +- session 绑定到 `start()` 时传入的 `lua_State*`(coroutine 是另一个 state) +- 头文件与测试解释器为 Lua **5.3.6**,不支持 Lua 5.4 ## 其他 diff --git a/src/vlua.cpp b/src/vlua.cpp index 0c3fbff..de8ab23 100644 --- a/src/vlua.cpp +++ b/src/vlua.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -90,10 +91,6 @@ static void vlog(const char *header, const char *file, const char *func, int pos // 采样配置 // ---------------------------------------------------------------------------- -// 采样间隔(微秒)。10000us = 10ms = 100Hz,对齐 pLua 的 CPU_SAMPLE_ITER。 -// 100Hz 下 signal 投递本身的开销约 0.03%,可以长时间常开。 -static const int SAMPLE_INTERVAL_US = 10 * 1000; - // Ring buffer 容量(条数)。100Hz 下可连续采样约 2.7 分钟不回绕。 // 单条 Sample 约 16 KB(depth + 64 frames × 260 字节),1<<14 ≈ 256 MB // 虚拟内存预留;命中率较低时可采更长时间,回绕后老样本被覆盖、报告会 @@ -107,7 +104,7 @@ static const size_t SAMPLE_SRC_MAX = 127; static const int MAX_STACK_DEPTH = 64; // ---------------------------------------------------------------------------- -// 全局状态 +// 采样数据结构 // ---------------------------------------------------------------------------- // 一帧栈信息(自包含,不持有 Lua 堆指针) @@ -126,34 +123,6 @@ struct Sample { StackFrame frames[MAX_STACK_DEPTH]; // frames[0] = 栈底,frames[depth-1] = 栈顶 }; -// 目标 C 函数的 PC 范围 -static uintptr_t g_target_addr = 0; -static uintptr_t g_target_end = 0; -static std::string g_target_name; - -// 当前 profile 的 lua_State -// 注意:signal handler 通过此全局访问,用 volatile 保证可见性 -static lua_State *volatile g_L = NULL; - -// 是否正在运行。signal handler 里用 volatile 读,start/stop 里在单线程 -// 主流程里写;SIGPROF 只打断当前线程,不存在跨线程写竞争。 -static volatile sig_atomic_t g_running = 0; - -// Ring buffer:单线程 Lua VM 假设下,signal handler 和主线程不会并发 -// 访问这些计数器: -// - SIGPROF handler 执行期间,同线程不会再收到第二个 SIGPROF -// (kernel 保证 handler 执行期间该信号被 masked) -// - stop() 在主线程走到 resolve_and_report 前已经关定时器 + pthread_sigmask -// 栅栏,此时不会再有 handler 在跑 -// 因此用普通 volatile 计数器即可,避免原子操作开销。 -static Sample *g_samples = NULL; -static volatile uint64_t g_sample_write_idx = 0; // 写入位置 -static volatile uint64_t g_sample_hit_count = 0; // 命中目标函数次数 -static volatile uint64_t g_sample_total_tick = 0; // 总 SIGPROF 次数 - -// 输出文件 -static std::string g_filename; - // ---------------------------------------------------------------------------- // 工具:从 ELF 拿到符号地址和大小 // ---------------------------------------------------------------------------- @@ -373,28 +342,6 @@ static inline uintptr_t get_pc_from_ucontext(const ucontext_t *uc) { #endif } -// 检查地址是否在目标 C 函数范围内 -static inline int pc_in_target(uintptr_t addr) { - return addr >= g_target_addr && addr < g_target_end; -} - -// 通过 backtrace() 获取被中断时的 C 调用栈,检查目标函数是否在调用链上。 -// backtrace() 使用 .eh_frame DWARF unwind info 回溯,不依赖 frame pointer, -// 在 signal handler 中可以穿过 signal trampoline 拿到被中断代码的完整帧链。 -// 最大回溯 16 层,对 luaV_execute → 子函数的场景绰绰有余。 -static const int BACKTRACE_MAX_DEPTH = 64; - -static inline int check_target_in_backtrace(void) { - void *frames[BACKTRACE_MAX_DEPTH]; - int n = backtrace(frames, BACKTRACE_MAX_DEPTH); - for (int i = 0; i < n; i++) { - if (pc_in_target((uintptr_t) frames[i])) { - return 1; - } - } - return 0; -} - // 判断 ci 是否是一个 Lua 函数帧(复制自 lstate.h 的 isLua 宏) static inline int ci_is_lua(const CallInfo *ci) { return ci->callstatus & CIST_LUA; @@ -614,35 +561,277 @@ static inline int extract_frame(const CallInfo *ci, const lua_State *L, return 1; } -static void signal_handler(int sig, siginfo_t *si, void *ucontext) { - (void) sig; (void) si; +// ---------------------------------------------------------------------------- +// Per-lua_State sessions + process-wide SIGPROF +// +// The SIGPROF handler is process-wide (ITIMER_PROF) and must stay async-signal +// safe: no Lua APIs, no allocation, no locks, no std:: containers. Sessions are +// published to a fixed slot table while SIGPROF is blocked. Stopping one +// session must not stop others. +// +// Sessions are not safe to start/stop or sample from multiple OS threads at +// once; all API calls and VM execution for a profiled state must stay on the +// same thread (same limitation as pLua). +// ---------------------------------------------------------------------------- - g_sample_total_tick++; +static const uint32_t PLUA_PRO_MAGIC = 0x41554C50; // 'PLUA' LE +static const uint32_t PLUA_PRO_VERSION_V2 = 2; +static const uint32_t PLUA_PRO_KIND_CPU = 1; +static const uint32_t PLUA_PRO_BACKEND_SIGPROF = 1; +// vLua does not use a VM instruction hook for sampling; the v2 header still +// requires a non-zero hook-step field for pLua-compatible tools. +static const uint32_t PLUA_PRO_HOOK_STEP = 1; + +static const int DEFAULT_CPU_INTERVAL_MS = 10; +static const int MAX_SESSIONS = 64; + +static const int BACKTRACE_MAX_DEPTH = 64; + +struct ProfilerSession { + // Signal-handler fields (plain C types only). + lua_State *volatile L; + volatile sig_atomic_t running; + uintptr_t target_addr; + uintptr_t target_end; + Sample *samples; + volatile uint64_t write_idx; + volatile uint64_t hit_count; + volatile uint64_t total_tick; + + // Main-thread only. The handler never touches these. + int interval_ms; + std::string target_name; + std::string filename; + std::string text_report; + std::string last_error; + std::string pending_func; + std::string pending_file; +}; + +static std::map g_sessions; +static ProfilerSession *volatile g_active[MAX_SESSIONS]; + +static int g_timer_users = 0; +static int g_timer_interval_ms = 0; +static int g_handlers_installed = 0; + +static int g_default_interval_ms = DEFAULT_CPU_INTERVAL_MS; +static int g_defaults_loaded = 0; + +static std::string g_last_error; + +static const char *kSessionAnchorKey = "vlua.session_anchor"; + +struct SessionAnchor { + lua_State *owner; +}; + +static void destroy_session(ProfilerSession *s); +static void ensure_session_anchor(lua_State *L); +static int start_impl(lua_State *L, const char *func_name, const char *file, int interval_ms); +static int stop_impl(lua_State *L); + +static void set_error(ProfilerSession *s, const char *fmt, ...) { + char buf[1024]; + va_list ap; + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + va_end(ap); + g_last_error = buf; + if (s) { + s->last_error = buf; + } + VERR("%s", buf); +} - if (!g_running) { +static void load_env_defaults() { + if (g_defaults_loaded) { return; } + g_defaults_loaded = 1; + const char *v = getenv("VLUA_CPU_INTERVAL_MS"); + if (v && *v) { + char *end = NULL; + long n = strtol(v, &end, 10); + if (end != v && n > 0 && n < 1000000) { + g_default_interval_ms = (int) n; + } + } +} - ucontext_t *uc = (ucontext_t *) ucontext; - uintptr_t pc = get_pc_from_ucontext(uc); +static ProfilerSession *get_session(lua_State *L, int create) { + auto it = g_sessions.find(L); + if (it != g_sessions.end()) { + return it->second; + } + if (!create) { + return NULL; + } + load_env_defaults(); + ProfilerSession *s = new ProfilerSession(); + s->L = L; + s->running = 0; + s->target_addr = 0; + s->target_end = 0; + s->samples = NULL; + s->write_idx = 0; + s->hit_count = 0; + s->total_tick = 0; + s->interval_ms = g_default_interval_ms; + g_sessions[L] = s; + ensure_session_anchor(L); + return s; +} + +static int session_anchor_gc(lua_State *L) { + SessionAnchor *a = (SessionAnchor *) lua_touserdata(L, 1); + if (!a || !a->owner) { + return 0; + } + lua_State *owner = a->owner; + a->owner = NULL; + auto it = g_sessions.find(owner); + if (it == g_sessions.end()) { + return 0; + } + destroy_session(it->second); + return 0; +} + +static void ensure_session_anchor(lua_State *L) { + lua_getfield(L, LUA_REGISTRYINDEX, kSessionAnchorKey); + if (lua_isnil(L, -1)) { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setfield(L, LUA_REGISTRYINDEX, kSessionAnchorKey); + } + lua_pushlightuserdata(L, L); + lua_newtable(L); + SessionAnchor *a = (SessionAnchor *) lua_newuserdata(L, sizeof(SessionAnchor)); + a->owner = L; + if (luaL_newmetatable(L, "vlua.session_anchor_mt")) { + lua_pushcfunction(L, session_anchor_gc); + lua_setfield(L, -2, "__gc"); + } + lua_setmetatable(L, -2); + lua_setfield(L, -2, "anchor"); + lua_pushthread(L); + lua_setfield(L, -2, "thread"); + lua_rawset(L, -3); + lua_pop(L, 1); +} + +static void detach_session_anchor(lua_State *L) { + lua_getfield(L, LUA_REGISTRYINDEX, kSessionAnchorKey); + if (lua_istable(L, -1)) { + lua_pushlightuserdata(L, L); + lua_rawget(L, -2); + if (lua_istable(L, -1)) { + lua_getfield(L, -1, "anchor"); + SessionAnchor *a = (SessionAnchor *) lua_touserdata(L, -1); + if (a) { + a->owner = NULL; + } + lua_pop(L, 1); + } + lua_pop(L, 1); + lua_pushlightuserdata(L, L); + lua_pushnil(L); + lua_rawset(L, -3); + } + lua_pop(L, 1); +} + +static void block_sigprof(sigset_t *old) { + sigset_t block; + sigemptyset(&block); + sigaddset(&block, SIGPROF); + pthread_sigmask(SIG_BLOCK, &block, old); +} + +static void restore_sigmask(const sigset_t *old) { + pthread_sigmask(SIG_SETMASK, old, NULL); +} + +static int publish_session(ProfilerSession *s) { + sigset_t old; + block_sigprof(&old); + int slot = -1; + for (int i = 0; i < MAX_SESSIONS; i++) { + if (g_active[i] == s) { + slot = i; + break; + } + if (slot < 0 && g_active[i] == NULL) { + slot = i; + } + } + int ok = 0; + if (slot >= 0) { + g_active[slot] = s; + ok = 1; + } + restore_sigmask(&old); + return ok; +} - // 快速路径:PC 直接在目标函数内,直接命中。 - // 绝大多数不相关的 SIGPROF 在这里就 return 了。 - int hit = pc_in_target(pc); - if (!hit) { - // PC 不在目标函数内,可能在目标函数调用的子函数里。 - // 通过 backtrace() 回溯 C 调用栈,检查目标函数是否在调用链上。 - if (!check_target_in_backtrace()) { - return; +static void unpublish_session(ProfilerSession *s) { + sigset_t old; + block_sigprof(&old); + s->running = 0; + for (int i = 0; i < MAX_SESSIONS; i++) { + if (g_active[i] == s) { + g_active[i] = NULL; } } + restore_sigmask(&old); +} + +static int check_lua_version(lua_State *L, ProfilerSession *s) { + const lua_Number *ver = lua_version(L); + if (!ver) { + set_error(s, "vLua could not read lua_version(); expected Lua 5.3.x " + "(vendored 5.3.6 private VM layout). Lua 5.4 is not supported."); + return -1; + } + int v = (int) *ver; + if (v != 503) { + set_error(s, "vLua requires Lua 5.3.x (vendored 5.3.6 private VM layout); " + "this lua_State reports version %d. Lua 5.4 is not supported.", v); + return -1; + } + if (!ptr_aligned(L, 8) || !L->l_G || !ptr_aligned(L->l_G, 8)) { + set_error(s, "lua_State VM layout does not match Lua 5.3.6 private structs " + "(l_G missing or unaligned). The host process must use a matching 5.3.x VM."); + return -1; + } + return 0; +} - lua_State *L = g_L; +static inline int session_pc_hit(const ProfilerSession *s, uintptr_t pc, + int have_bt, void **bt, int nbt) { + if (pc >= s->target_addr && pc < s->target_end) { + return 1; + } + if (!have_bt) { + return 0; + } + for (int i = 0; i < nbt; i++) { + uintptr_t addr = (uintptr_t) bt[i]; + if (addr >= s->target_addr && addr < s->target_end) { + return 1; + } + } + return 0; +} + +static void sample_session(ProfilerSession *s) { + lua_State *L = s->L; if (!L) { return; } - // ---- 架起 SEGV 安全网 ---- if (sigsetjmp(tl_segv_jmp, 1) != 0) { tl_segv_armed = 0; return; @@ -654,7 +843,6 @@ static void signal_handler(int sig, siginfo_t *si, void *ucontext) { return; } - // ---- 遍历 ci 链,先收集所有 Lua 帧的 ci 指针 ---- const CallInfo *lua_cis[MAX_STACK_DEPTH]; int num_lua_cis = 0; @@ -668,10 +856,7 @@ static void signal_handler(int sig, siginfo_t *si, void *ucontext) { } ci = ci->previous; } - // lua_cis[0] = 栈顶,lua_cis[num-1] = 栈底 - // ---- 提取每帧信息,传递 caller 的 Proto+pc 用于推导函数名 ---- - // 对于 lua_cis[i],它的 caller 是 lua_cis[i+1](更深一层) StackFrame tmp_frames[MAX_STACK_DEPTH]; int tmp_depth = 0; @@ -679,7 +864,6 @@ static void signal_handler(int sig, siginfo_t *si, void *ucontext) { const Proto *caller_p = NULL; int caller_pc = -1; - // 找 caller 帧(更深一层的 Lua 帧) if (i + 1 < num_lua_cis) { const CallInfo *caller_ci = lua_cis[i + 1]; StkId caller_func = caller_ci->func; @@ -712,126 +896,186 @@ static void signal_handler(int sig, siginfo_t *si, void *ucontext) { tl_segv_armed = 0; - if (tmp_depth == 0) { + if (tmp_depth == 0 || !s->samples) { return; } - // ---- 写入 ring buffer:翻转为栈底在前(和 pLua 一致)---- - uint64_t idx = g_sample_write_idx++; - Sample *slot = &g_samples[idx & (RING_BUFFER_SIZE - 1)]; + uint64_t idx = s->write_idx++; + Sample *slot = &s->samples[idx & (RING_BUFFER_SIZE - 1)]; slot->depth = tmp_depth; for (int i = 0; i < tmp_depth; i++) { slot->frames[i] = tmp_frames[tmp_depth - 1 - i]; } + s->hit_count++; +} - g_sample_hit_count++; +static unsigned peek_nccalls(ProfilerSession *s) { + lua_State *L = s->L; + if (!L) { + return 0; + } + if (sigsetjmp(tl_segv_jmp, 1) != 0) { + tl_segv_armed = 0; + return 0; + } + tl_segv_armed = 1; + unsigned n = 0; + if (ptr_aligned(L, 8)) { + n = (unsigned) L->nCcalls; + } + tl_segv_armed = 0; + return n; } -// ---------------------------------------------------------------------------- -// start / stop -// ---------------------------------------------------------------------------- +static void signal_handler(int sig, siginfo_t *si, void *ucontext) { + (void) sig; + (void) si; -static int start_impl(lua_State *L, const char *func_name, const char *file) { - if (g_running) { - VERR("vlua already running"); - return -1; - } + ucontext_t *uc = (ucontext_t *) ucontext; + uintptr_t pc = get_pc_from_ucontext(uc); - // 预热 backtrace():glibc 的 backtrace() 首次调用可能 dlopen - // libgcc_s.so 加载 unwind 支持,dlopen 不是 async-signal-safe, - // 如果第一次调用发生在 SIGPROF handler 里、且被打断的代码刚好 - // 持有 dynamic loader 锁,会死锁。这里在主线程提前触发一次, - // 保证后续 signal handler 里 backtrace() 不会再走 dlopen 路径。 - { - void *warmup_frames[1]; - (void) backtrace(warmup_frames, 1); + ProfilerSession *hits[MAX_SESSIONS]; + unsigned ncc[MAX_SESSIONS]; + int nhit = 0; + int need_bt = 0; + + for (int i = 0; i < MAX_SESSIONS; i++) { + ProfilerSession *s = g_active[i]; + if (!s || !s->running) { + continue; + } + s->total_tick++; + if (pc < s->target_addr || pc >= s->target_end) { + need_bt = 1; + } } - uintptr_t addr = 0; - size_t size = 0; - if (resolve_symbol(func_name, &addr, &size) != 0) { - VERR("resolve_symbol(%s) failed", func_name); - return -1; + void *frames[BACKTRACE_MAX_DEPTH]; + int nframes = 0; + if (need_bt) { + nframes = backtrace(frames, BACKTRACE_MAX_DEPTH); } - g_target_name = func_name; - g_target_addr = addr; - g_target_end = addr + size; - g_filename = file; - g_L = L; + unsigned max_ncc = 0; + int any_hit = 0; + for (int i = 0; i < MAX_SESSIONS; i++) { + ProfilerSession *s = g_active[i]; + if (!s || !s->running) { + continue; + } + if (!session_pc_hit(s, pc, need_bt, frames, nframes)) { + continue; + } + unsigned n = peek_nccalls(s); + hits[nhit] = s; + ncc[nhit] = n; + nhit++; + any_hit = 1; + if (n > max_ncc) { + max_ncc = n; + } + } + if (!any_hit) { + return; + } - // 分配 ring buffer - if (!g_samples) { - g_samples = (Sample *) calloc(RING_BUFFER_SIZE, sizeof(Sample)); - if (!g_samples) { - VERR("alloc ring buffer failed"); - return -1; + // One running session: sample it (backward compatible, including C-API + // calls where nCcalls may be 0). Several sessions: prefer the lua_State + // that is actually inside the VM (highest nCcalls). + for (int i = 0; i < nhit; i++) { + if (nhit > 1 && ncc[i] < max_ncc) { + continue; } - } else { - memset(g_samples, 0, sizeof(Sample) * RING_BUFFER_SIZE); + sample_session(hits[i]); + } +} + +static int install_handlers() { + if (g_handlers_installed) { + return 0; } - g_sample_write_idx = 0; - g_sample_hit_count = 0; - g_sample_total_tick = 0; - // 安装 SIGPROF handler,保存原 handler 用于 stop 时恢复 struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = signal_handler; sa.sa_flags = SA_RESTART | SA_SIGINFO; sigemptyset(&sa.sa_mask); if (sigaction(SIGPROF, &sa, &g_prev_sigprof) != 0) { - VERR("sigaction(SIGPROF) failed: %s", strerror(errno)); + set_error(NULL, "sigaction(SIGPROF) failed: %s", strerror(errno)); return -1; } - // 安装 SIGSEGV/SIGBUS 兜底 handler(只在 vlua 采样区间接管) struct sigaction sa_segv; memset(&sa_segv, 0, sizeof(sa_segv)); sa_segv.sa_sigaction = segv_handler; - // SA_NODEFER 允许 handler 内再次触发同信号(siglongjmp 后不阻塞) sa_segv.sa_flags = SA_SIGINFO | SA_NODEFER; sigemptyset(&sa_segv.sa_mask); if (sigaction(SIGSEGV, &sa_segv, &g_prev_sigsegv) != 0) { - VERR("sigaction(SIGSEGV) failed: %s", strerror(errno)); + set_error(NULL, "sigaction(SIGSEGV) failed: %s", strerror(errno)); sigaction(SIGPROF, &g_prev_sigprof, NULL); return -1; } if (sigaction(SIGBUS, &sa_segv, &g_prev_sigbus) != 0) { - VERR("sigaction(SIGBUS) failed: %s", strerror(errno)); + set_error(NULL, "sigaction(SIGBUS) failed: %s", strerror(errno)); sigaction(SIGSEGV, &g_prev_sigsegv, NULL); sigaction(SIGPROF, &g_prev_sigprof, NULL); return -1; } + g_handlers_installed = 1; + return 0; +} - g_running = 1; +static void uninstall_handlers() { + if (!g_handlers_installed) { + return; + } + sigaction(SIGSEGV, &g_prev_sigsegv, NULL); + sigaction(SIGBUS, &g_prev_sigbus, NULL); + sigaction(SIGPROF, &g_prev_sigprof, NULL); + g_handlers_installed = 0; +} - // 启动定时器 +static int start_timer(int interval_ms) { + if (g_timer_users > 0) { + if (g_timer_interval_ms != interval_ms) { + return -1; + } + g_timer_users++; + return 0; + } struct itimerval timer; - timer.it_interval.tv_sec = 0; - timer.it_interval.tv_usec = SAMPLE_INTERVAL_US; + timer.it_interval.tv_sec = interval_ms / 1000; + timer.it_interval.tv_usec = (interval_ms % 1000) * 1000; timer.it_value = timer.it_interval; if (setitimer(ITIMER_PROF, &timer, NULL) != 0) { - VERR("setitimer failed: %s", strerror(errno)); - g_running = 0; - return -1; + set_error(NULL, "setitimer failed: %s", strerror(errno)); + return -2; } - - printf("vlua started: target=%s addr=%p size=%zu file=%s\n", - func_name, (void*)addr, size, file); + g_timer_interval_ms = interval_ms; + g_timer_users = 1; return 0; } +static void stop_timer() { + if (g_timer_users <= 0) { + return; + } + g_timer_users--; + if (g_timer_users == 0) { + struct itimerval timer; + memset(&timer, 0, sizeof(timer)); + setitimer(ITIMER_PROF, &timer, NULL); + g_timer_interval_ms = 0; + uninstall_handlers(); + } +} + // ---------------------------------------------------------------------------- -// 报告聚合与输出 +// Report aggregation and .pro output (CPU v2 header + legacy body) // ---------------------------------------------------------------------------- -// pLua 兼容常量(与 plua.cpp / plua.go 一致) static const int PLUA_MAX_FUNC_NAME_SIZE = 127; static const int PLUA_MAX_STACK_SIZE = 64; - -// pLua 的 IGNORE_NAME 起始 ID 数量,vlua 不需要忽略名字,但 ID 从 -// VALID_MIN_ID 开始分配,保持和 pLua 工具链兼容。 static const int VALID_MIN_ID = 9; struct CallStack { @@ -860,18 +1104,18 @@ struct CallStackEqual { } }; -static void flush_file(int fd, const char *buf, size_t len) { +static int flush_file(int fd, const char *buf, size_t len) { while (len > 0) { ssize_t r = write(fd, buf, len); if (r <= 0) { - break; + return 0; } buf += r; len -= r; } + return 1; } -// 把 source 字符串单行化(load(str) 产生的 chunk source 含多行源码) static std::string sanitize_source(const std::string &in) { std::string s = in; for (char &c : s) { @@ -885,12 +1129,10 @@ static std::string sanitize_source(const std::string &in) { return s; } -// 为 StackFrame 生成 .pro 文件里的帧标识名:直接用预生成的 name 字段 static std::string frame_name(const StackFrame &f) { return sanitize_source(f.name); } -// 为 StackFrame 生成精确行号标识(用于文本报告 top hotspots) static std::string frame_line_name(const StackFrame &f) { char buf[256]; std::string src = sanitize_source(f.source); @@ -902,38 +1144,48 @@ static std::string frame_line_name(const StackFrame &f) { return buf; } -// 写 pLua 兼容的 .pro 二进制文件。 -// 格式与 plua.cpp flush() 完全一致: -// [N 个 CallStack 条目]: count(int32) + CallStack{depth(int32) + stack[64](int32×64)} -// [M 个字符串条目]: name(变长bytes) + name_len(int32) + id(int32) -// [尾部 4 字节]: M(int32) = 字符串条目总数 -// -// 每帧对应一个 string ID("@file.lua:27"),完整栈直接映射为 CallStack。 -static void flush_pro_file(uint64_t to_scan) { - int fd = open(g_filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666); +// Write a pLua-compatible .pro file with CPU v2 metadata: +// header 24 bytes: magic, version=2, kind=CPU, backend=SIGPROF, +// interval_ms, hook_step +// then the legacy body (call stacks + string table + count). +// Legacy (no-magic) readers that walk from the tail still work. +static int flush_pro_file(ProfilerSession *s, uint64_t to_scan) { + int fd = open(s->filename.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666); if (fd < 0) { - VERR("open %s failed", g_filename.c_str()); - return; + set_error(s, "open %s failed: %s", s->filename.c_str(), strerror(errno)); + return -1; + } + + uint32_t header[] = { + PLUA_PRO_MAGIC, + PLUA_PRO_VERSION_V2, + PLUA_PRO_KIND_CPU, + PLUA_PRO_BACKEND_SIGPROF, + (uint32_t) s->interval_ms, + PLUA_PRO_HOOK_STEP, + }; + if (!flush_file(fd, (const char *) header, sizeof(header))) { + set_error(s, "write header to %s failed", s->filename.c_str()); + close(fd); + return -1; } std::unordered_map str2id; int next_id = VALID_MIN_ID; - - // 为每个 Sample 构造 CallStack(用 string ID),聚合相同 CallStack 的计数 std::unordered_map cs_agg; for (uint64_t i = 0; i < to_scan; i++) { - const Sample &s = g_samples[i]; - if (s.depth <= 0) { + const Sample &samp = s->samples[i]; + if (samp.depth <= 0) { continue; } CallStack cs; memset(&cs, 0, sizeof(cs)); - cs.depth = s.depth; + cs.depth = samp.depth; - for (int j = 0; j < s.depth; j++) { - std::string name = frame_name(s.frames[j]); + for (int j = 0; j < samp.depth; j++) { + std::string name = frame_name(samp.frames[j]); auto it = str2id.find(name); if (it == str2id.end()) { str2id[name] = next_id; @@ -943,11 +1195,9 @@ static void flush_pro_file(uint64_t to_scan) { cs.stack[j] = it->second; } } - cs_agg[cs]++; } - // 写 CallStack 条目 for (auto &kv : cs_agg) { const CallStack &cs = kv.first; int count = kv.second; @@ -955,12 +1205,10 @@ static void flush_pro_file(uint64_t to_scan) { flush_file(fd, (const char *) &cs, sizeof(cs)); } - // 写字符串表 int total_len = 0; for (auto &kv : str2id) { const std::string &str = kv.first; int id = kv.second; - int len = (int) str.length(); if (len > PLUA_MAX_FUNC_NAME_SIZE) { len = PLUA_MAX_FUNC_NAME_SIZE; @@ -970,28 +1218,23 @@ static void flush_pro_file(uint64_t to_scan) { flush_file(fd, (const char *) &id, sizeof(id)); total_len++; } - - // 写尾部:字符串条目总数 flush_file(fd, (const char *) &total_len, sizeof(total_len)); close(fd); + return 0; } -// 生成文本报告(返回 string,不写文件) -// 统计维度:栈顶帧的 source:line(即直接触发目标 C 函数的 Lua 行) -static std::string build_text_report( +static std::string build_text_report(ProfilerSession *s, uint64_t total_hit, uint64_t total_tick, uint64_t written, uint64_t to_scan) { - // 按栈顶帧聚合 struct LineCount { std::string name; uint64_t count; }; std::unordered_map top_agg; for (uint64_t i = 0; i < to_scan; i++) { - const Sample &s = g_samples[i]; - if (s.depth <= 0) { + const Sample &samp = s->samples[i]; + if (samp.depth <= 0) { continue; } - // 栈顶 = frames[depth-1],文本报告用精确行号 - std::string name = frame_line_name(s.frames[s.depth - 1]); + std::string name = frame_line_name(samp.frames[samp.depth - 1]); top_agg[name]++; } @@ -1012,15 +1255,15 @@ static std::string build_text_report( std::string report; report += "==================== vLua sampling report ====================\n"; - snprintf(buf, sizeof(buf), "target function : %s\n", g_target_name.c_str()); + snprintf(buf, sizeof(buf), "target function : %s\n", s->target_name.c_str()); report += buf; snprintf(buf, sizeof(buf), "target addr range : [%p, %p) size=%zu\n", - (void*) g_target_addr, (void*) g_target_end, - (size_t)(g_target_end - g_target_addr)); + (void *) s->target_addr, (void *) s->target_end, + (size_t) (s->target_end - s->target_addr)); report += buf; - snprintf(buf, sizeof(buf), "output file : %s\n", g_filename.c_str()); + snprintf(buf, sizeof(buf), "output file : %s\n", s->filename.c_str()); report += buf; - snprintf(buf, sizeof(buf), "sample interval : %d us\n", SAMPLE_INTERVAL_US); + snprintf(buf, sizeof(buf), "sample interval : %d ms\n", s->interval_ms); report += buf; snprintf(buf, sizeof(buf), "ring buffer size : %zu\n", (size_t) RING_BUFFER_SIZE); report += buf; @@ -1057,149 +1300,339 @@ static std::string build_text_report( } report += "\n"; report += "================================================================\n"; - report += "(use plua.go + pprof on the .pro file for full callstack / flamegraph)\n"; + report += "(use tools/vlua -proto / -pprof / -flame on the .pro file for full callstacks)\n"; return report; } -// stop 返回的文本报告 -static std::string g_text_report; +static int start_impl(lua_State *L, const char *func_name, const char *file, int interval_ms) { + load_env_defaults(); + ProfilerSession *s = get_session(L, 1); -static int stop_impl(lua_State *L) { - (void) L; - if (!g_running) { - VERR("vlua not running"); + if (check_lua_version(L, s) != 0) { + return -1; + } + if (s->running) { + set_error(s, "vlua is already running on this lua_State; call stop() first"); + return -1; + } + if (!func_name || !*func_name) { + set_error(s, "missing target C function name"); + return -1; + } + if (!file || !*file) { + set_error(s, "missing output .pro path"); return -1; } - // 先置 running 为 0,正在执行的 handler 走完当前这次后下次进来直接 return - g_running = 0; + int interval = interval_ms > 0 ? interval_ms : g_default_interval_ms; + if (interval <= 0) { + interval = DEFAULT_CPU_INTERVAL_MS; + } + if (g_timer_users > 0 && g_timer_interval_ms != interval) { + set_error(s, "SIGPROF interval is already %d ms (set by another lua_State); " + "requested %d ms. Stop other sessions or use the same interval.", + g_timer_interval_ms, interval); + return -1; + } - // 关闭定时器:此后不会再有新的 SIGPROF 产生 - struct itimerval timer; - memset(&timer, 0, sizeof(timer)); - setitimer(ITIMER_PROF, &timer, NULL); - - // 关键同步:确保当前线程没有在执行 handler。 - // 方法:短暂阻塞 SIGPROF,再解除。阻塞/解除系统调用会确保内核 - // 将任何 pending SIGPROF 要么投递要么丢弃,而已在执行的 handler - // 会在此系统调用返回前完成(同线程不能并发执行 signal handler)。 - sigset_t block, old; - sigemptyset(&block); - sigaddset(&block, SIGPROF); - pthread_sigmask(SIG_BLOCK, &block, &old); - pthread_sigmask(SIG_SETMASK, &old, NULL); + { + void *warmup_frames[1]; + (void) backtrace(warmup_frames, 1); + } - // 此时可以安全读 ring buffer - uint64_t total_hit = g_sample_hit_count; - uint64_t total_tick = g_sample_total_tick; - uint64_t written = g_sample_write_idx; - uint64_t to_scan = written < RING_BUFFER_SIZE ? written : RING_BUFFER_SIZE; + uintptr_t addr = 0; + size_t size = 0; + if (resolve_symbol(func_name, &addr, &size) != 0) { + set_error(s, "target C function '%s' not found (not in .dynsym or .symtab). " + "The host binary may be stripped; verify with: nm | grep %s", + func_name, func_name); + return -1; + } - // 写 pLua 兼容的二进制 .pro 文件(完整栈) - flush_pro_file(to_scan); + if (!s->samples) { + s->samples = (Sample *) calloc(RING_BUFFER_SIZE, sizeof(Sample)); + if (!s->samples) { + set_error(s, "alloc ring buffer failed"); + return -1; + } + } else { + memset(s->samples, 0, sizeof(Sample) * RING_BUFFER_SIZE); + } + s->write_idx = 0; + s->hit_count = 0; + s->total_tick = 0; + s->target_name = func_name; + s->target_addr = addr; + s->target_end = addr + size; + s->filename = file; + s->interval_ms = interval; + s->text_report.clear(); + + if (install_handlers() != 0) { + if (g_last_error.size()) { + s->last_error = g_last_error; + } + return -1; + } - // 生成文本报告(栈顶帧聚合) - g_text_report = build_text_report(total_hit, total_tick, written, to_scan); + int timer_rc = start_timer(interval); + if (timer_rc != 0) { + if (timer_rc == -1) { + set_error(s, "SIGPROF interval is already %d ms (set by another lua_State); " + "requested %d ms. Stop other sessions or use the same interval.", + g_timer_interval_ms, interval); + } else if (s->last_error.empty() && !g_last_error.empty()) { + s->last_error = g_last_error; + } + if (g_timer_users == 0) { + uninstall_handlers(); + } + return -1; + } + + s->running = 1; + if (!publish_session(s)) { + s->running = 0; + stop_timer(); + set_error(s, "too many concurrent vLua sessions (max %d)", MAX_SESSIONS); + return -1; + } + + printf("vlua started: target=%s addr=%p size=%zu file=%s interval=%dms\n", + func_name, (void *) addr, size, file, interval); + return 0; +} + +static int stop_impl(lua_State *L) { + ProfilerSession *s = get_session(L, 0); + if (!s || !s->running) { + set_error(s, "vlua is not running on this lua_State"); + return -1; + } + + // Drop this session first so other sessions keep receiving SIGPROF. + unpublish_session(s); + stop_timer(); + + uint64_t total_hit = s->hit_count; + uint64_t total_tick = s->total_tick; + uint64_t written = s->write_idx; + uint64_t to_scan = written < RING_BUFFER_SIZE ? written : RING_BUFFER_SIZE; + + int wr = flush_pro_file(s, to_scan); + s->text_report = build_text_report(s, total_hit, total_tick, written, to_scan); printf("vlua stopped: %llu ticks, %llu hits (%.2f%%), report -> %s\n", (unsigned long long) total_tick, (unsigned long long) total_hit, total_tick > 0 ? 100.0 * total_hit / total_tick : 0.0, - g_filename.c_str()); + s->filename.c_str()); - // 恢复原 SIGSEGV/SIGBUS/SIGPROF handler - sigaction(SIGSEGV, &g_prev_sigsegv, NULL); - sigaction(SIGBUS, &g_prev_sigbus, NULL); - sigaction(SIGPROF, &g_prev_sigprof, NULL); - - // 清理 - g_L = NULL; - g_sample_write_idx = 0; - g_sample_hit_count = 0; - g_sample_total_tick = 0; + if (wr != 0) { + return -1; + } return 0; } +static void destroy_session(ProfilerSession *s) { + if (!s) { + return; + } + lua_State *L = (lua_State *) s->L; + if (s->running) { + unpublish_session(s); + stop_timer(); + } else { + unpublish_session(s); + } + if (s->samples) { + free(s->samples); + s->samples = NULL; + } + if (L) { + auto it = g_sessions.find(L); + if (it != g_sessions.end() && it->second == s) { + g_sessions.erase(it); + } + detach_session_anchor(L); + } + delete s; +} + // ---------------------------------------------------------------------------- -// Lua binding + hookso 注入接口 +// Lua binding + hookso injection entry points // ---------------------------------------------------------------------------- -// hookso 注入时的参数暂存 -static std::string g_pending_func_name; -static std::string g_pending_filename; - -// lua_sethook 回调:在 Lua VM 安全上下文中执行真正的 start static void StartHandlerHook(lua_State *L, lua_Debug *par) { (void) par; - start_impl(L, g_pending_func_name.c_str(), g_pending_filename.c_str()); - lua_sethook(L, 0, 0, 0); + lua_sethook(L, NULL, 0, 0); + ProfilerSession *s = get_session(L, 0); + const char *func = (s && !s->pending_func.empty()) ? s->pending_func.c_str() : ""; + const char *file = (s && !s->pending_file.empty()) ? s->pending_file.c_str() : ""; + start_impl(L, func, file, 0); } -// lua_sethook 回调:在 Lua VM 安全上下文中执行真正的 stop static void StopHandlerHook(lua_State *L, lua_Debug *par) { (void) par; + lua_sethook(L, NULL, 0, 0); stop_impl(L); - lua_sethook(L, 0, 0, 0); } -// hookso 注入入口:开始采样 -// hookso 可能在任意时刻注入调用此函数,不能直接操作 Lua 栈, -// 因此只保存参数并通过 lua_sethook 延迟到 Lua VM 安全上下文执行。 -// 用法:hookso call $PID libvlua.so lrealstart i=$L s="luaH_getshortstr" s="./call.pro" +// hookso injection: lrealstart(L, "luaH_getshortstr", "./call.pro") +// Defers start_impl into a Lua VM-safe hook. Signature is unchanged. extern "C" int lrealstart(lua_State *L, const char *func_name, const char *file) { - if (g_running) { - VERR("start again, failed"); + ProfilerSession *s = get_session(L, 1); + if (s->running) { + set_error(s, "vlua is already running on this lua_State; call stop() first"); return -1; } - - g_L = L; - g_pending_func_name = func_name; - g_pending_filename = file; - - lua_sethook(g_L, StartHandlerHook, LUA_MASKCOUNT, 1); - + s->pending_func = func_name ? func_name : ""; + s->pending_file = file ? file : ""; + lua_sethook(L, StartHandlerHook, LUA_MASKCOUNT, 1); VLOG("lrealstart %s %s", func_name, file); return 0; } -// hookso 注入入口:停止采样 -// 通过 lua_sethook 延迟到 Lua VM 安全上下文执行 stop_impl。 -// 注意:不能在这里设 g_running = 0,否则 stop_impl 会因为 g_running==0 而提前返回, -// 导致 .pro 文件不会被写入。g_running 的置零由 stop_impl 内部处理。 -// 用法:hookso call $PID libvlua.so lrealstop i=$L +// hookso injection: lrealstop(L) +// Defers stop_impl into a Lua VM-safe hook. Do not clear running here. extern "C" int lrealstop(lua_State *L) { lua_sethook(L, StopHandlerHook, LUA_MASKCOUNT, 1); VLOG("lrealstop"); return 0; } -// vlua.start(func_name, output_file) +// vlua.start(func_name, output_file [, interval_ms]) -> 0 | nil, err static int l_start(lua_State *L) { const char *func_name = luaL_checkstring(L, 1); const char *file = luaL_checkstring(L, 2); - int ret = start_impl(L, func_name, file); - lua_pushinteger(L, ret); - return 1; + int interval = 0; + if (lua_gettop(L) >= 3 && !lua_isnil(L, 3)) { + interval = (int) luaL_checkinteger(L, 3); + if (interval <= 0) { + lua_pushnil(L); + lua_pushstring(L, "interval_ms must be a positive integer"); + return 2; + } + } + int ret = start_impl(L, func_name, file, interval); + if (ret == 0) { + lua_pushinteger(L, 0); + return 1; + } + lua_pushnil(L); + lua_pushstring(L, g_last_error.empty() ? "vlua start failed" : g_last_error.c_str()); + return 2; } -// vlua.stop() -> string|nil -// 成功时返回文本报告,失败返回 nil +// vlua.stop() -> report | nil, err static int l_stop(lua_State *L) { int ret = stop_impl(L); - if (ret == 0) { - lua_pushstring(L, g_text_report.c_str()); + ProfilerSession *s = get_session(L, 0); + if (ret == 0 && s) { + lua_pushstring(L, s->text_report.c_str()); + return 1; + } + lua_pushnil(L); + lua_pushstring(L, g_last_error.empty() ? "vlua is not running on this lua_State" + : g_last_error.c_str()); + return 2; +} + +static int l_status(lua_State *L) { + ProfilerSession *s = get_session(L, 0); + lua_newtable(L); + + lua_pushboolean(L, s && s->running); + lua_setfield(L, -2, "running"); + + if (s && !s->target_name.empty()) { + lua_pushstring(L, s->target_name.c_str()); } else { lua_pushnil(L); } + lua_setfield(L, -2, "target"); + + if (s && !s->filename.empty()) { + lua_pushstring(L, s->filename.c_str()); + } else { + lua_pushnil(L); + } + lua_setfield(L, -2, "output"); + + lua_pushinteger(L, s ? s->interval_ms : g_default_interval_ms); + lua_setfield(L, -2, "interval_ms"); + + lua_pushinteger(L, s ? (lua_Integer) s->write_idx : 0); + lua_setfield(L, -2, "samples"); + + lua_pushinteger(L, s ? (lua_Integer) s->total_tick : 0); + lua_setfield(L, -2, "ticks"); + + lua_pushinteger(L, s ? (lua_Integer) s->hit_count : 0); + lua_setfield(L, -2, "hits"); + + lua_pushstring(L, "sigprof"); + lua_setfield(L, -2, "backend"); + + lua_newtable(L); + load_env_defaults(); + lua_pushinteger(L, g_default_interval_ms); + lua_setfield(L, -2, "cpu_interval_ms"); + lua_setfield(L, -2, "config"); + return 1; +} + +static int l_close(lua_State *L) { + ProfilerSession *s = get_session(L, 0); + if (!s) { + lua_pushinteger(L, 0); + return 1; + } + if (s->running) { + stop_impl(L); + s = get_session(L, 0); + } + if (s) { + destroy_session(s); + } + lua_pushinteger(L, 0); + return 1; +} + +static int l_set_config(lua_State *L) { + load_env_defaults(); + if (lua_istable(L, 1)) { + lua_getfield(L, 1, "cpu_interval_ms"); + if (lua_isnumber(L, -1)) { + int v = (int) lua_tointeger(L, -1); + if (v > 0) { + g_default_interval_ms = v; + } + } + lua_pop(L, 1); + } + lua_pushinteger(L, 0); + return 1; +} + +static int l_get_config(lua_State *L) { + load_env_defaults(); + lua_newtable(L); + lua_pushinteger(L, g_default_interval_ms); + lua_setfield(L, -2, "cpu_interval_ms"); return 1; } extern "C" int luaopen_libvlua(lua_State *L) { luaL_checkversion(L); luaL_Reg l[] = { - {"start", l_start}, - {"stop", l_stop}, + {"start", l_start}, + {"stop", l_stop}, + {"status", l_status}, + {"close", l_close}, + {"set_config", l_set_config}, + {"get_config", l_get_config}, {NULL, NULL}, }; luaL_newlib(L, l); diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 511814c..b64c1f6 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -1,27 +1,57 @@ -# Smoke tests use the vendored Lua 5.3.6 interpreter so VM internals match +# Tests use the vendored Lua 5.3.6 interpreter so VM internals match # the headers used to compile libvlua.so. set(VLUA_TEST_ENV "LUA_CPATH=${CMAKE_SOURCE_DIR}/bin/?.so\;${CMAKE_SOURCE_DIR}/bin/lib?.so" + "VLUA_TOOL=${CMAKE_SOURCE_DIR}/bin/vlua" ) -add_test( - NAME test_getstr - COMMAND $ ${CMAKE_CURRENT_SOURCE_DIR}/test_getstr.lua - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} -) -set_tests_properties(test_getstr PROPERTIES ENVIRONMENT "${VLUA_TEST_ENV}") +function(vlua_lua_test name script) + add_test( + NAME ${name} + COMMAND $ ${CMAKE_CURRENT_SOURCE_DIR}/${script} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + ) + set_tests_properties(${name} PROPERTIES ENVIRONMENT "${VLUA_TEST_ENV}") +endfunction() -add_test( - NAME test_funcname - COMMAND $ ${CMAKE_CURRENT_SOURCE_DIR}/test_funcname.lua - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} -) -set_tests_properties(test_funcname PROPERTIES ENVIRONMENT "${VLUA_TEST_ENV}") +vlua_lua_test(test_getstr test_getstr.lua) +vlua_lua_test(test_funcname test_funcname.lua) +vlua_lua_test(test_hotreload test_hotreload.lua) +vlua_lua_test(test_vlua test_vlua.lua) +vlua_lua_test(test_api test_api.lua) +vlua_lua_test(test_hotreload_stress test_hotreload_stress.lua) + +# Stress is crash-or-pass and can run longer than the smoke tests. +set_tests_properties(test_hotreload_stress PROPERTIES TIMEOUT 180) +set_tests_properties(test_getstr PROPERTIES TIMEOUT 120) +set_tests_properties(test_vlua PROPERTIES TIMEOUT 120) +set_tests_properties(test_funcname PROPERTIES TIMEOUT 120) +set_tests_properties(test_hotreload PROPERTIES TIMEOUT 120) -add_test( - NAME test_hotreload - COMMAND $ ${CMAKE_CURRENT_SOURCE_DIR}/test_hotreload.lua - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} +# Two lua_State sessions + error paths (cannot be expressed in one interpreter). +add_executable(unit_test unit_test.cpp) +target_include_directories(unit_test PRIVATE ${LUA_INCLUDE_DIR}) +target_link_libraries(unit_test PRIVATE vlua lua_vendor) +set_target_properties(unit_test PROPERTIES + RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/test + ENABLE_EXPORTS ON + BUILD_RPATH "${CMAKE_SOURCE_DIR}/bin" ) -set_tests_properties(test_hotreload PROPERTIES ENVIRONMENT "${VLUA_TEST_ENV}") +add_test(NAME unit_test COMMAND $ + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) +set_tests_properties(unit_test PROPERTIES + ENVIRONMENT "LD_LIBRARY_PATH=${CMAKE_SOURCE_DIR}/bin" + TIMEOUT 60 +) + +# Converter tests (legacy + v2 metadata, proto export). Optional bench is +# documented in the README and is not run here: overhead is statistical. +if(GO_EXECUTABLE) + add_test( + NAME test_converter + COMMAND ${GO_EXECUTABLE} test + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/tools + ) + set_tests_properties(test_converter PROPERTIES TIMEOUT 60) +endif() diff --git a/test/bench_vlua.lua b/test/bench_vlua.lua index 7cf98f1..20b9cfc 100644 --- a/test/bench_vlua.lua +++ b/test/bench_vlua.lua @@ -1,4 +1,7 @@ -- bench_vlua.lua - 测量 vlua 开启 vs 关闭的 workload 耗时 +-- Optional local experiment only. Not registered in ctest/CI: +-- overhead is statistical and would be flaky as a pass/fail gate. +-- Run: ../build/lua/lua53 bench_vlua.lua package.cpath = "../bin/?.so;" .. package.cpath local v = require "libvlua" diff --git a/test/test_api.lua b/test/test_api.lua new file mode 100644 index 0000000..88f263d --- /dev/null +++ b/test/test_api.lua @@ -0,0 +1,75 @@ +-- test_api.lua +-- status / close / set_config / interval / clear errors. Single lua_State. +package.cpath = "../bin/?.so;" .. package.cpath +local v = require "libvlua" + +local function assert_true(cond, msg) + if not cond then + error(msg or "assertion failed", 2) + end +end + +-- Function not found must be a clear error, not a silent no-op. +local ok, err = v.start("this_function_does_not_exist_xyz", "missing.pro") +assert_true(ok == nil, "start(unknown) should return nil, err (got " .. tostring(ok) .. ")") +assert_true(type(err) == "string" and err:find("not found", 1, true), + "start(unknown) error should mention 'not found': " .. tostring(err)) +print("function-not-found error OK: " .. err) + +local st = v.status() +assert_true(type(st) == "table") +assert_true(st.running == false) +assert_true(type(st.interval_ms) == "number") +assert_true(type(st.config) == "table") +assert_true(type(st.config.cpu_interval_ms) == "number") + +local cfg = v.get_config() +assert_true(type(cfg.cpu_interval_ms) == "number" and cfg.cpu_interval_ms > 0) + +v.set_config({ cpu_interval_ms = 7 }) +cfg = v.get_config() +assert_true(cfg.cpu_interval_ms == 7, "set_config did not stick, got " .. tostring(cfg.cpu_interval_ms)) + +ok, err = v.start("luaV_execute", "api_interval.pro") +assert_true(ok == 0, "start after set_config failed: " .. tostring(err)) +st = v.status() +assert_true(st.running == true) +assert_true(st.target == "luaV_execute") +assert_true(st.output == "api_interval.pro") +assert_true(st.interval_ms == 7, "session interval should be 7, got " .. tostring(st.interval_ms)) +assert_true(st.backend == "sigprof") + +local acc = 0 +for i = 1, 200000 do acc = acc + i end + +-- Already running on this state must fail clearly; other work stays running. +local ok2, err2 = v.start("luaV_execute", "api_again.pro") +assert_true(ok2 == nil, "second start should fail") +assert_true(type(err2) == "string" and err2:find("already running", 1, true), + "already-running error unclear: " .. tostring(err2)) +assert_true(v.status().running == true, "failed start must not stop the session") + +local text, stop_err = v.stop() +assert_true(type(text) == "string", "stop failed: " .. tostring(stop_err)) +st = v.status() +assert_true(st.running == false) +assert_true(st.output == "api_interval.pro") + +-- Explicit interval argument overrides the default. +ok, err = v.start("luaV_execute", "api_arg.pro", 3) +assert_true(ok == 0, "start with interval arg failed: " .. tostring(err)) +assert_true(v.status().interval_ms == 3) +for i = 1, 100000 do acc = acc + i end +text, stop_err = v.stop() +assert_true(type(text) == "string", "stop(arg) failed: " .. tostring(stop_err)) + +-- stop when idle is a clear error +local idle, idle_err = v.stop() +assert_true(idle == nil, "idle stop should return nil, err") +assert_true(type(idle_err) == "string" and idle_err:find("not running", 1, true), + "idle stop error unclear: " .. tostring(idle_err)) + +assert_true(v.close() == 0) +st = v.status() +assert_true(st.running == false) +print("status/close/interval API OK") diff --git a/test/test_funcname.lua b/test/test_funcname.lua index a8c7dec..640df1d 100644 --- a/test/test_funcname.lua +++ b/test/test_funcname.lua @@ -1,5 +1,6 @@ -- test_funcname.lua --- 验证 try_get_funcname_from_caller 的所有 case +-- 验证 try_get_funcname_from_caller 的所有 case。 +-- 不依赖宿主 luac 或本地 ./pprof;用 tools/vlua -flame 检查帧名。 package.cpath = "../bin/?.so;" .. package.cpath local v = require "libvlua" @@ -79,15 +80,65 @@ local function run_all() end end --- 验证字节码 -print("=== bytecode of run_all ===") -os.execute("luac -l -l test_funcname.lua 2>&1 | grep -A1 'CALL' | head -40") - -print("\n=== sampling ===") -v.start("luaV_execute", "funcname.pro") +print("=== sampling ===") +local ok, err = v.start("luaV_execute", "funcname.pro", 1) +if ok ~= 0 then + error("v.start failed: " .. tostring(err)) +end run_all() -local text = v.stop() +local text, stop_err = v.stop() +if not text then + error("v.stop failed: " .. tostring(stop_err)) +end print(text) +local hits = tonumber(text:match("hits in target function%s*:%s*(%d+)")) +if not hits or hits < 1 then + error("funcname workload produced no luaV_execute hits") +end + +local function find_tool() + local candidates = { + os.getenv("VLUA_TOOL"), + "../bin/vlua", + "../tools/vlua", + } + for _, p in ipairs(candidates) do + if p and p ~= "" then + local f = io.open(p, "r") + if f then + f:close() + return p + end + end + end + return nil +end + +local tool = find_tool() +if not tool then + error("vlua converter not found (build tools/vlua); cannot validate function names") +end + +local fl = "funcname.fl" +local cmd = string.format("%s -i funcname.pro -flame %s", tool, fl) +local rc = os.execute(cmd) +if rc ~= 0 and rc ~= true then + error("vlua -flame failed: " .. cmd) +end +local f = io.open(fl, "r") +if not f then + error("failed to read " .. fl) +end +local collapsed = f:read("*a") +f:close() print("=== collapsed ===") -os.execute("cd ../tools && ./vlua -i ../test/funcname.pro -pprof /tmp/funcname.prof 2>&1 && ./pprof --collapsed /tmp/funcname.prof 2>/dev/null") +print(collapsed) + +local expected = { "'global_func'", "'table_func'", "'method_func'", "'upval_func'", "'local_func'" } +for _, name in ipairs(expected) do + if not collapsed:find(name, 1, true) then + error("missing function name in collapsed stacks: " .. name) + end +end +print("function names OK") diff --git a/test/test_getstr.lua b/test/test_getstr.lua index f262f49..6d56aca 100644 --- a/test/test_getstr.lua +++ b/test/test_getstr.lua @@ -1,5 +1,8 @@ -- test_getstr.lua --- 模拟实际业务的多层调用,各分支调用量不同 +-- 模拟实际业务的多层调用,各分支调用量不同。 +-- CI 断言:calc_damage / update_kill 必须排在更冷路径前面。 +-- 目标函数用 luaH_get:在 -O2/-O3 下 luaH_getshortstr 会被内联进 luaH_get, +-- 独立符号几乎采不到样本。 package.cpath = "../bin/?.so;" .. package.cpath local v = require "libvlua" @@ -87,7 +90,82 @@ local function main() end end -v.start("luaH_getshortstr", "getstr.pro") +-- 1ms interval: denser samples so ranking assertions stay stable in CI. +local ok, err = v.start("luaH_get", "getstr.pro", 1) +if ok ~= 0 then + error("v.start failed: " .. tostring(err)) +end main() -local text = v.stop() +local text, stop_err = v.stop() +if not text then + error("v.stop failed: " .. tostring(stop_err)) +end print(text) + +local function hotspot_ranks(report) + local ranks = {} + local n = 0 + for loc in report:gmatch("%d+%.%d+%%%s+(%S+)") do + n = n + 1 + if not ranks[loc] then + ranks[loc] = n + end + end + return ranks, n +end + +local ranks, n = hotspot_ranks(text) +if n == 0 then + error("no analysable hotspots in report") +end + +local function source_line(snippet) + local src = arg[0] + local i = 0 + for line in io.lines(src) do + i = i + 1 + if line:find(snippet, 1, true) then + return i + end + end + error("snippet not found in " .. tostring(src) .. ": " .. snippet) +end + +local function find_rank(lineno) + local suffix = "test_getstr.lua:" .. tostring(lineno) + for loc, rank in pairs(ranks) do + if loc:find(suffix, 1, true) then + return rank, loc + end + end + return nil, suffix +end + +local r_damage, loc_damage = find_rank(source_line("weapon.damage = player.role.battle.weapon.damage")) +local r_kill, loc_kill = find_rank(source_line("stat.kill = player.role.battle.stat.kill")) +local r_death = find_rank(source_line("stat.death = player.role.battle.stat.death")) +local r_bag = find_rank(source_line("player.role.bag.capacity")) + +if not r_damage then + error("calc_damage hotspot not found in report") +end +if not r_kill then + error("update_kill hotspot not found in report") +end +print(string.format("ranks: %s=%d %s=%d death=%s bag=%s", + loc_damage, r_damage, loc_kill, r_kill, + tostring(r_death), tostring(r_bag))) + +if r_death and r_damage >= r_death then + error("calc_damage should rank ahead of colder update_death") +end +if r_death and r_kill >= r_death then + error("update_kill should rank ahead of colder update_death") +end +if r_bag and r_damage >= r_bag then + error("calc_damage should rank ahead of colder check_bag") +end +if r_bag and r_kill >= r_bag then + error("update_kill should rank ahead of colder check_bag") +end +print("attribution ranking OK") diff --git a/test/test_hotreload.lua b/test/test_hotreload.lua index bb8c871..6eeb505 100644 --- a/test/test_hotreload.lua +++ b/test/test_hotreload.lua @@ -21,7 +21,7 @@ local function make_func(tag) end print("start sampling luaH_newkey during simulated hot-reload...") -v.start("luaH_newkey", "hotreload.pro") +assert(v.start("luaH_newkey", "hotreload.pro") == 0, "start failed") -- 模拟 20000 次热更循环,保证采样能打到 luaH_newkey for round = 1, 20000 do @@ -33,6 +33,7 @@ for round = 1, 20000 do end end -v.stop() +local text, err = v.stop() +assert(text, "stop failed: " .. tostring(err)) print("done. no crash -> hot-reload safety OK") print("see hotreload.pro") diff --git a/test/test_hotreload_stress.lua b/test/test_hotreload_stress.lua index 33ef936..3458de3 100644 --- a/test/test_hotreload_stress.lua +++ b/test/test_hotreload_stress.lua @@ -19,9 +19,9 @@ local function make_func(tag) end print("start sampling luaH_newkey during AGGRESSIVE hot-reload stress...") -v.start("luaH_newkey", "hotreload_stress.pro") +assert(v.start("luaH_newkey", "hotreload_stress.pro") == 0, "start failed") -for round = 1, 30000 do +for round = 1, 15000 do local f = make_func("R" .. round) f(500) f = nil @@ -37,6 +37,7 @@ end collectgarbage("collect") collectgarbage("collect") -v.stop() +local text, err = v.stop() +assert(text, "stop failed: " .. tostring(err)) print("done. no crash -> aggressive hot-reload safety OK") print("see hotreload_stress.pro") diff --git a/test/test_vlua.lua b/test/test_vlua.lua index 2266a25..707a64a 100644 --- a/test/test_vlua.lua +++ b/test/test_vlua.lua @@ -1,10 +1,10 @@ -- test_vlua.lua --- 构造 a.b.c 风格的大量 table get-by-string,验证 vlua 能定位到热点行 +-- 构造 a.b.c 风格的大量 table get-by-string,验证 vlua 能定位到热点行。 +-- CI 断言:hot_a / hot_b 必须排在已缓存的 cold_a 前面。 package.cpath = "../bin/?.so;" .. package.cpath local v = require "libvlua" --- 构造一个深嵌套的大表 local player = { role = { pos = { x = 0, y = 0, z = 0 }, @@ -47,45 +47,112 @@ local function cold_a() end local function work() - for _ = 1, 5000 do + for _ = 1, 2000 do hot_a() hot_b() cold_a() end end -print("start sampling luaH_getshortstr...") -v.start("luaH_getshortstr", "call.pro") +local function hotspot_ranks(report) + local ranks = {} + local n = 0 + for loc in report:gmatch("%d+%.%d+%%%s+(%S+)") do + n = n + 1 + if not ranks[loc] then + ranks[loc] = n + end + end + return ranks, n +end + +local function min_rank(ranks, lineno) + local needle = "test_vlua.lua:" .. tostring(lineno) + local best + for loc, rank in pairs(ranks) do + if loc:find(needle, 1, true) then + if not best or rank < best then + best = rank + end + end + end + return best +end + +print("start sampling luaH_get...") +local ok, err = v.start("luaH_get", "call.pro", 1) +if ok ~= 0 then + error("v.start failed: " .. tostring(err)) +end work() -local text = v.stop() +local text, stop_err = v.stop() +if not text then + error("v.stop failed: " .. tostring(stop_err)) +end print("--- stop() returned text report ---") print(text) --- luaH_newkey 函数范围较大(~1KB),在本机也容易命中,用于验证 --- 机制正确性 -print("") -print("start sampling luaH_newkey (for validation)...") -v.start("luaH_newkey", "call_newkey.pro") +local ranks, n = hotspot_ranks(text) +if n == 0 then + error("no analysable hotspots for luaH_get") +end --- 构造大量新 key 触发 luaH_newkey -local t = {} -for i = 1, 2000000 do - t["k" .. i] = i +local function source_line(snippet) + local src = arg[0] + local i = 0 + for line in io.lines(src) do + i = i + 1 + if line:find(snippet, 1, true) then + return i + end + end + error("snippet not found in " .. tostring(src) .. ": " .. snippet) end -text = v.stop() -print("--- stop() returned text report ---") -print(text) +local r_hot_a = min_rank(ranks, source_line("player.role.pos.x = player.role.pos.x + 1")) + or min_rank(ranks, source_line("player.role.pos.y = player.role.pos.y + 1")) + or min_rank(ranks, source_line("player.role.pos.z = player.role.pos.z + 1")) +local r_hot_b = min_rank(ranks, source_line("player.role.battle.stat.kill = player.role.battle.stat.kill + 1")) +local r_cold = min_rank(ranks, source_line("pos.x = pos.x + 1")) + or min_rank(ranks, source_line("pos.y = pos.y + 1")) + or min_rank(ranks, source_line("pos.z = pos.z + 1")) --- 再用 luaV_execute 验证一下机制(范围大,必然命中) -print("") -print("start sampling luaV_execute (for mechanism validation)...") -v.start("luaV_execute", "call_vexec.pro") +if not r_hot_a then + error("hot_a location missing from report") +end +if not r_hot_b then + error("hot_b location missing from report") +end +print(string.format("ranks: hot_a=%d hot_b=%d cold_a=%s", r_hot_a, r_hot_b, tostring(r_cold))) +if r_cold then + if r_hot_a >= r_cold then + error("hot_a should rank ahead of cached cold_a") + end + if r_hot_b >= r_cold then + error("hot_b should rank ahead of cached cold_a") + end +end +print("luaH_get attribution OK") +-- luaV_execute has a large symbol range, so it must produce samples. +-- Keep this short: it only checks that the sampler attributes *something*. +print("start sampling luaV_execute (mechanism check)...") +ok, err = v.start("luaV_execute", "call_vexec.pro", 1) +if ok ~= 0 then + error("v.start luaV_execute failed: " .. tostring(err)) +end work() - -text = v.stop() -print("--- stop() returned text report ---") -print(text) +text, stop_err = v.stop() +if not text then + error("v.stop luaV_execute failed: " .. tostring(stop_err)) +end +if not text:find("hits in target function") then + error("luaV_execute report missing hit summary") +end +local hits = tonumber(text:match("hits in target function%s*:%s*(%d+)")) +if not hits or hits < 1 then + error("luaV_execute produced no hits") +end +print("luaV_execute mechanism OK, hits=" .. hits) diff --git a/test/unit_test.cpp b/test/unit_test.cpp new file mode 100644 index 0000000..5553b77 --- /dev/null +++ b/test/unit_test.cpp @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +int luaopen_libvlua(lua_State *L); +} + +#define ASSERT_TRUE(cond) \ + do { \ + if (!(cond)) { \ + std::cerr << "Assertion failed: " #cond " at " << __FILE__ << ":" << __LINE__ << std::endl; \ + std::exit(1); \ + } \ + } while (0) + +static void register_vlua(lua_State *L) { + luaL_requiref(L, "libvlua", luaopen_libvlua, 1); + lua_pop(L, 1); +} + +static bool file_exists_and_non_empty(const std::string &path) { + std::ifstream f(path, std::ios::binary | std::ios::ate); + if (!f.is_open()) return false; + return f.tellg() > 0; +} + +static void busy_work(lua_State *L) { + int r = luaL_dostring(L, + "local t = { a = { b = { c = 0 } } }\n" + "for _ = 1, 80 do\n" + " for i = 1, 200000 do\n" + " t.a.b.c = t.a.b.c + 1\n" + " end\n" + "end\n" + ); + if (r != 0) { + std::cerr << lua_tostring(L, -1) << std::endl; + } + ASSERT_TRUE(r == 0); +} + +static int run_multistate_tests() { + std::cout << "[C++ MultiState] two independent lua_State sessions..." << std::endl; + lua_State *L1 = luaL_newstate(); + lua_State *L2 = luaL_newstate(); + ASSERT_TRUE(L1 && L2); + luaL_openlibs(L1); + luaL_openlibs(L2); + register_vlua(L1); + register_vlua(L2); + + const char *f1 = "unit_state1.pro"; + const char *f2 = "unit_state2.pro"; + std::remove(f1); + std::remove(f2); + + int r = luaL_dostring(L1, + "local v = require('libvlua')\n" + "assert(v.start('luaH_get', 'unit_state1.pro', 1) == 0)\n" + "local st = v.status()\n" + "assert(st.running == true)\n" + "assert(st.output == 'unit_state1.pro')\n" + "assert(st.interval_ms == 1)\n" + ); + if (r != 0) std::cerr << lua_tostring(L1, -1) << std::endl; + ASSERT_TRUE(r == 0); + + r = luaL_dostring(L2, + "local v = require('libvlua')\n" + "assert(v.start('luaH_get', 'unit_state2.pro', 1) == 0)\n" + "assert(v.status().running == true)\n" + ); + if (r != 0) std::cerr << lua_tostring(L2, -1) << std::endl; + ASSERT_TRUE(r == 0); + + busy_work(L1); + busy_work(L2); + + r = luaL_dostring(L1, + "local v = require('libvlua')\n" + "local text, err = v.stop()\n" + "assert(text, err)\n" + "assert(v.status().running == false)\n" + "local hits = tonumber(text:match('hits in target function%s*:%s*(%d+)'))\n" + "assert(hits and hits > 0, 'expected hits in L1 profile')\n" + ); + if (r != 0) std::cerr << lua_tostring(L1, -1) << std::endl; + ASSERT_TRUE(r == 0); + ASSERT_TRUE(file_exists_and_non_empty(f1)); + + // Stopping L1 must not stop L2. + r = luaL_dostring(L2, + "local v = require('libvlua')\n" + "assert(v.status().running == true, 'L2 should still be running after L1 stop')\n" + ); + if (r != 0) std::cerr << lua_tostring(L2, -1) << std::endl; + ASSERT_TRUE(r == 0); + + busy_work(L2); + + r = luaL_dostring(L2, + "local v = require('libvlua')\n" + "local text, err = v.stop()\n" + "assert(text, err)\n" + "local hits = tonumber(text:match('hits in target function%s*:%s*(%d+)'))\n" + "assert(hits and hits > 0, 'expected hits in L2 profile')\n" + "assert(v.close() == 0)\n" + "assert(v.status().running == false)\n" + ); + if (r != 0) std::cerr << lua_tostring(L2, -1) << std::endl; + ASSERT_TRUE(r == 0); + ASSERT_TRUE(file_exists_and_non_empty(f2)); + + r = luaL_dostring(L1, "assert(require('libvlua').close() == 0)\n"); + ASSERT_TRUE(r == 0); + + lua_close(L1); + lua_close(L2); + std::remove(f1); + std::remove(f2); + std::cout << " -> two-state independence OK" << std::endl; + return 0; +} + +static int run_error_tests() { + std::cout << "[C++ Test] function-not-found error..." << std::endl; + lua_State *L = luaL_newstate(); + ASSERT_TRUE(L); + luaL_openlibs(L); + register_vlua(L); + int r = luaL_dostring(L, + "local v = require('libvlua')\n" + "local ok, err = v.start('definitely_missing_c_function', 'unit_missing.pro')\n" + "assert(ok == nil)\n" + "assert(type(err) == 'string' and err:find('not found', 1, true))\n" + "assert(v.status().running == false)\n" + ); + if (r != 0) std::cerr << lua_tostring(L, -1) << std::endl; + ASSERT_TRUE(r == 0); + lua_close(L); + std::cout << " -> function-not-found OK" << std::endl; + return 0; +} + +int main() { + run_error_tests(); + run_multistate_tests(); + std::cout << "[C++ Test] All unit tests passed." << std::endl; + return 0; +} diff --git a/tools/show.sh b/tools/show.sh index 2ac42bd..8390c81 100755 --- a/tools/show.sh +++ b/tools/show.sh @@ -68,8 +68,16 @@ elif command -v pprof >/dev/null 2>&1; then elif command -v google-pprof >/dev/null 2>&1; then PPROF_BIN="google-pprof" else - echo "Tip: pprof is not installed. Callgraph dot/png generation will be skipped." - echo " Install gperftools/google-perftools to enable callgraph visualization." + # Go-installed pprof (google-perftools apt package is gone on newer Ubuntu). + GOPATH_BIN="$(go env GOPATH 2>/dev/null)/bin" + if [ -n "$GOPATH_BIN" ] && [ -x "$GOPATH_BIN/pprof" ]; then + PPROF_BIN="$GOPATH_BIN/pprof" + elif command -v go >/dev/null 2>&1 && go tool pprof -h >/dev/null 2>&1; then + PPROF_BIN="go tool pprof" + else + echo "Tip: pprof is not installed. Callgraph dot/png generation will be skipped." + echo " Install with: go install github.com/google/pprof@latest" + fi fi # Check graphviz dot @@ -83,7 +91,8 @@ for PRO_PATH in "${PRO_FILES[@]}"; do echo "Processing profile: $PRO_PATH" # 1. Convert .pro to flamegraph collapsed stacks - "$VLUA_BIN" -i "$PRO_PATH" -flame "$BASE_NAME.fl" -pprof "$BASE_NAME.prof" + "$VLUA_BIN" -i "$PRO_PATH" -flame "$BASE_NAME.fl" -pprof "$BASE_NAME.prof" -proto "$BASE_NAME.pb.gz" + echo " -> Generated collapsed / legacy pprof / proto: $BASE_NAME.fl $BASE_NAME.prof $BASE_NAME.pb.gz" # 2. Generate Flamegraph SVG if [ -n "$FLAMEGRAPH_BIN" ]; then @@ -96,7 +105,7 @@ for PRO_PATH in "${PRO_FILES[@]}"; do # 3. Generate call graph (.dot and .png) if pprof is available if [ -n "$PPROF_BIN" ]; then - if "$PPROF_BIN" --dot "$BASE_NAME.prof" > "$BASE_NAME.dot" 2>/dev/null; then + if $PPROF_BIN --dot "$BASE_NAME.prof" > "$BASE_NAME.dot" 2>/dev/null; then echo " -> Generated dot file: $BASE_NAME.dot" if [ $HAS_DOT -eq 1 ]; then dot -Tpng "$BASE_NAME.dot" -o "$BASE_NAME.png" diff --git a/tools/vlua.go b/tools/vlua.go index 534c86d..48d006e 100644 --- a/tools/vlua.go +++ b/tools/vlua.go @@ -1,17 +1,21 @@ package main import ( + "bytes" + "compress/gzip" "encoding/binary" "flag" "fmt" "math" "os" + "sort" "strings" ) const ( MAX_FUNC_NAME_SIZE = 127 MAX_STACK_SIZE = 64 + proMagic = 0x41554C50 // 'PLUA' little-endian ) type CallStack struct { @@ -21,13 +25,16 @@ type CallStack struct { } type FileData struct { - str2id map[string]int - id2str map[int]string - callstack []CallStack + version uint32 + kind, backend, intervalMs, hookCount uint32 + str2id map[string]int + id2str map[int]string + callstack []CallStack } func main() { input := flag.String("i", "", "input file (.pro)") + proto := flag.String("proto", "", "gzip profile.proto CPU output (modern go tool pprof)") pprof := flag.String("pprof", "", "gen pprof symbolized-profiles") flame := flag.String("flame", "", "gen flamegraph collapsed stacks file") collapsed := flag.String("collapsed", "", "alias for -flame") @@ -44,6 +51,12 @@ func main() { os.Exit(1) } + if *proto != "" { + if err := showproto(filedata, *proto); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + } if *pprof != "" { showpprof(filedata, *pprof) } @@ -64,13 +77,45 @@ func parse(filename string) (*FileData, bool) { return nil, false } + return parseData(data) +} + +func parseData(data []byte) (*FileData, bool) { if len(data) < 4 { fmt.Printf("data error too small\n") return nil, false } + headerSize := 0 + version := uint32(0) + var kind, backend, intervalMs, hookCount uint32 + if len(data) >= 8 { + magic := binary.LittleEndian.Uint32(data[0:4]) + if magic == proMagic { + version = binary.LittleEndian.Uint32(data[4:8]) + if version < 1 || version > 2 { + fmt.Printf("unsupported .pro version %v\n", version) + return nil, false + } + headerSize = 8 + if version == 2 { + headerSize = 24 + if len(data) < headerSize+4 { + return nil, false + } + kind = binary.LittleEndian.Uint32(data[8:12]) + backend = binary.LittleEndian.Uint32(data[12:16]) + intervalMs = binary.LittleEndian.Uint32(data[16:20]) + hookCount = binary.LittleEndian.Uint32(data[20:24]) + if kind != 1 || (backend != 1 && backend != 2) || intervalMs == 0 || hookCount == 0 { + return nil, false + } + } + } + } + namemaplen := int(binary.LittleEndian.Uint32(data[len(data)-4 : len(data)])) - if namemaplen < 0 { + if len(data) < headerSize+4 || namemaplen > (len(data)-headerSize-4)/9 { fmt.Printf("name map len fail %v\n", namemaplen) return nil, false } @@ -82,7 +127,7 @@ func parse(filename string) (*FileData, bool) { end := len(data) - 4 for i := 0; i < len(data) && namenum < namemaplen; i++ { start := end - 4 - if start < 0 || end < 0 { + if start < headerSize || end < headerSize { fmt.Printf("get id fail %v %v\n", start, end) return nil, false } @@ -90,7 +135,7 @@ func parse(filename string) (*FileData, bool) { end -= 4 start = end - 4 - if start < 0 || end < 0 { + if start < headerSize || end < headerSize { fmt.Printf("get name len fail %v %v\n", start, end) return nil, false } @@ -103,26 +148,44 @@ func parse(filename string) (*FileData, bool) { } start = end - namelen + if start < headerSize { + fmt.Printf("name out of range\n") + return nil, false + } str := string(data[start:end]) end -= namelen + if _, exists := id2str[id]; exists { + return nil, false + } str2id[str] = id id2str[id] = str namenum++ } + if (end-headerSize)%((MAX_STACK_SIZE+2)*4) != 0 { + return nil, false + } callstack := make([]CallStack, 0) - for end > 0 { + for end > headerSize { stacks := make([]int, MAX_STACK_SIZE) for i := 0; i < MAX_STACK_SIZE; i++ { start := end - 4 + if start < headerSize { + fmt.Printf("stack underflow\n") + return nil, false + } stack := int(binary.LittleEndian.Uint32(data[start:end])) end -= 4 stacks[MAX_STACK_SIZE-i-1] = stack } start := end - 4 + if start < headerSize { + fmt.Printf("deps underflow\n") + return nil, false + } deps := int(binary.LittleEndian.Uint32(data[start:end])) end -= 4 @@ -132,14 +195,23 @@ func parse(filename string) (*FileData, bool) { } start = end - 4 + if start < headerSize { + fmt.Printf("count underflow\n") + return nil, false + } count := int(binary.LittleEndian.Uint32(data[start:end])) end -= 4 - if count <= 0 { + if count <= 0 || (version == 2 && count > math.MaxInt32) { fmt.Printf("count error %v\n", count) return nil, false } + for _, id := range stacks[:deps] { + if _, ok := id2str[id]; !ok { + return nil, false + } + } cs := CallStack{ count: count, deps: deps, @@ -150,6 +222,8 @@ func parse(filename string) (*FileData, bool) { } filedata := &FileData{ + version: version, + kind: kind, backend: backend, intervalMs: intervalMs, hookCount: hookCount, str2id: str2id, id2str: id2str, callstack: callstack, @@ -162,12 +236,12 @@ func showpprof(filedata *FileData, filename string) { var output []byte output = append(output, []byte("--- symbol\n")...) - output = append(output, []byte("binary=vLua\n")...) + output = append(output, []byte("binary=pLua\n")...) for id, str := range filedata.id2str { - name := strings.ReplaceAll(str, "<", "'") - name = strings.ReplaceAll(name, ">", "'") - name = strings.ReplaceAll(name, "\"", "\\\"") + name := strings.Replace(str, "<", "'", -1) + name = strings.Replace(name, ">", "'", -1) + name = strings.Replace(name, "\"", "\\\"", -1) name = strings.ToValidUTF8(name, "?") tmp := fmt.Sprintf("0x%016x %s\n", id+0xFF000000, name) output = append(output, []byte(tmp)...) @@ -244,3 +318,120 @@ func showcollapsed(filedata *FileData, filename string) { fmt.Printf("total collapsed sample %v\n", total) } + +// Minimal profile.proto wire encoder. Only varint and length-delimited fields +// are needed; no generated runtime or external dependencies. Field numbers are +// from github.com/google/pprof/proto/profile.proto. +func pv(dst []byte, field int, v uint64) []byte { + dst = appendVarint(dst, uint64(field<<3)) + return appendVarint(dst, v) +} +func pb(dst []byte, field int, v []byte) []byte { + dst = appendVarint(dst, uint64(field<<3|2)) + dst = appendVarint(dst, uint64(len(v))) + return append(dst, v...) +} + +func profileProto(f *FileData) ([]byte, error) { + // v0/v1 do not identify CPU vs memory or carry a sampling period. Guessing + // from filenames would silently turn bytes/instructions into CPU time. + if f.version != 2 || f.kind != 1 { + return nil, fmt.Errorf("-proto requires a v2 CPU .pro; legacy/v1 and memory profiles lack CPU metadata (use -flame or -pprof)") + } + stringsTable := []string{""} + stringsIndex := map[string]uint64{"": 0} + intern := func(s string) uint64 { + s = strings.ToValidUTF8(s, "?") + if i, ok := stringsIndex[s]; ok { + return i + } + i := uint64(len(stringsTable)) + stringsIndex[s] = i + stringsTable = append(stringsTable, s) + return i + } + valueType := func(name, unit string) []byte { return pv(pv(nil, 1, intern(name)), 2, intern(unit)) } + var out []byte + out = pb(out, 1, valueType("samples", "count")) + if f.backend == 1 { + out = pb(out, 1, valueType("cpu", "nanoseconds")) + out = pb(out, 11, valueType("cpu", "nanoseconds")) + out = pv(out, 12, uint64(f.intervalMs)*1000000) + } else if f.backend == 2 { + out = pb(out, 11, valueType("instructions", "count")) + out = pv(out, 12, uint64(f.hookCount)) + } else { + return nil, fmt.Errorf("unknown CPU backend %d", f.backend) + } + ids := make([]int, 0, len(f.id2str)) + for id := range f.id2str { + ids = append(ids, id) + } + sort.Ints(ids) + locations := make(map[int]uint64) + for i, id := range ids { + n := uint64(i + 1) + locations[id] = n + function := pv(nil, 1, n) + function = pv(function, 2, intern(f.id2str[id])) + out = pb(out, 5, function) + line := pv(nil, 1, n) + location := pv(nil, 1, n) + location = pb(location, 4, line) + out = pb(out, 4, location) + } + for _, cs := range f.callstack { + if cs.count <= 0 || len(cs.stacks) == 0 { + return nil, fmt.Errorf("invalid sample") + } + var sample []byte + // .pro is root-first; profile.proto requires leaf-first location IDs. + for i := len(cs.stacks) - 1; i >= 0; i-- { + id, ok := locations[cs.stacks[i]] + if !ok { + return nil, fmt.Errorf("unknown frame ID") + } + sample = pv(sample, 1, id) + } + sample = pv(sample, 2, uint64(cs.count)) + if f.backend == 1 { + period := uint64(f.intervalMs) * 1000000 + if uint64(cs.count) > math.MaxInt64/period { + return nil, fmt.Errorf("CPU weight overflow") + } + sample = pv(sample, 2, uint64(cs.count)*period) + } + out = pb(out, 2, sample) + } + comment := "vLua: SIGPROF samples while the target Lua VM C function is on CPU; estimated CPU time; Lua stack only" + if f.backend == 2 { + comment = "vLua: count backend is accepted for pLua-compatible files; vLua itself writes SIGPROF CPU profiles" + } + out = pv(out, 13, intern(comment)) + for _, s := range stringsTable { + out = pb(out, 6, []byte(s)) + } + return out, nil +} + +func showproto(f *FileData, filename string) error { + data, err := profileProto(f) + if err != nil { + return err + } + var buf bytes.Buffer + z := gzip.NewWriter(&buf) + if _, err = z.Write(data); err != nil { + return err + } + if err = z.Close(); err != nil { + return err + } + return os.WriteFile(filename, buf.Bytes(), 0644) +} + +func appendVarint(dst []byte, v uint64) []byte { + var b [10]byte + n := binary.PutUvarint(b[:], v) + return append(dst, b[:n]...) +} diff --git a/tools/vlua_test.go b/tools/vlua_test.go new file mode 100644 index 0000000..4a6bdbb --- /dev/null +++ b/tools/vlua_test.go @@ -0,0 +1,292 @@ +package main + +import ( + "bytes" + "compress/gzip" + "encoding/binary" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func fixture(version, backend uint32) []byte { + var b bytes.Buffer + put := func(v uint32) { + if err := binary.Write(&b, binary.LittleEndian, v); err != nil { + panic(err) + } + } + if version > 0 { + put(proMagic) + put(version) + } + if version == 2 { + put(1) + put(backend) + put(10) + put(1000) + } + put(7) + put(2) + for i := 0; i < 64; i++ { + if i == 0 { + put(10) + } else if i == 1 { + put(20) + } else { + put(0) + } + } + for _, e := range []struct { + id uint32 + name string + }{{10, "root"}, {20, "hot_leaf"}} { + b.WriteString(e.name) + put(uint32(len(e.name))) + put(e.id) + } + put(2) + return b.Bytes() +} + +// Independent tiny wire reader: tests field identities, reference consistency, +// stack orientation and units instead of comparing an encoder to itself. +type field struct { + num int + v uint64 + b []byte +} + +func fields(t *testing.T, data []byte) []field { + t.Helper() + var out []field + for len(data) > 0 { + key, n := binary.Uvarint(data) + if n <= 0 { + t.Fatal("bad key") + } + data = data[n:] + f := field{num: int(key >> 3)} + v, n := binary.Uvarint(data) + if n <= 0 { + t.Fatal("bad value/length") + } + data = data[n:] + switch key & 7 { + case 0: + f.v = v + case 2: + if v > uint64(len(data)) { + t.Fatal("bad length") + } + f.b = data[:int(v)] + data = data[int(v):] + default: + t.Fatalf("unexpected wire %d", key&7) + } + out = append(out, f) + } + return out +} +func values(fs []field, num int) []uint64 { + var vs []uint64 + for _, f := range fs { + if f.num == num { + vs = append(vs, f.v) + } + } + return vs +} +func TestProtoSemantics(t *testing.T) { + for _, backend := range []uint32{1, 2} { + t.Run(map[uint32]string{1: "cpu", 2: "count"}[backend], func(t *testing.T) { + f, ok := parseData(fixture(2, backend)) + if !ok { + t.Fatal("parse") + } + data, err := profileProto(f) + if err != nil { + t.Fatal(err) + } + fs := fields(t, data) + var st []string + var samples, types [][]field + functions := map[uint64]uint64{} + locations := map[uint64]uint64{} + var period []field + for _, v := range fs { + switch v.num { + case 6: + st = append(st, string(v.b)) + case 1: + types = append(types, fields(t, v.b)) + case 2: + samples = append(samples, fields(t, v.b)) + case 4: + ls := fields(t, v.b) + var id uint64 + for _, l := range ls { + if l.num == 1 { + id = l.v + } + } + for _, l := range ls { + if l.num == 4 { + locations[id] = values(fields(t, l.b), 1)[0] + } + } + case 5: + fn := fields(t, v.b) + functions[values(fn, 1)[0]] = values(fn, 2)[0] + case 11: + period = fields(t, v.b) + } + } + if len(st) == 0 || st[0] != "" { + t.Fatal("string index zero") + } + if len(samples) != 1 { + t.Fatal("samples") + } + ids := values(samples[0], 1) + weights := values(samples[0], 2) + if len(ids) != 2 || ids[0] == 0 || ids[1] == 0 || st[functions[locations[ids[0]]]] != "hot_leaf" || st[functions[locations[ids[1]]]] != "root" { + t.Fatal("leaf-first/ID references") + } + if weights[0] != 7 { + t.Fatal(weights) + } + if st[values(types[0], 1)[0]] != "samples" || st[values(types[0], 2)[0]] != "count" { + t.Fatal("sample type") + } + if backend == 1 { + if len(weights) != 2 || weights[1] != 70000000 || len(types) != 2 || values(fs, 12)[0] != 10000000 { + t.Fatal("CPU weights/period", weights) + } + if st[values(types[1], 1)[0]] != "cpu" || st[values(types[1], 2)[0]] != "nanoseconds" { + t.Fatal("CPU type") + } + } else { + if len(weights) != 1 || len(types) != 1 || values(fs, 12)[0] != 1000 || st[values(period, 1)[0]] != "instructions" || st[values(period, 2)[0]] != "count" { + t.Fatal("count must not be CPU ns") + } + } + }) + } +} +func TestParsingAndErrors(t *testing.T) { + for _, v := range []uint32{0, 1, 2} { + if _, ok := parseData(fixture(v, 1)); !ok { + t.Fatalf("v%d", v) + } + } + valid := fixture(2, 1) + for i := 0; i < len(valid); i++ { + if _, ok := parseData(valid[:i]); ok { + t.Fatalf("accepted truncated offset %d", i) + } + } + cases := map[string][]byte{} + mutation := func(name string, offset int, v uint32) { + d := append([]byte(nil), valid...) + binary.LittleEndian.PutUint32(d[offset:], v) + cases[name] = d + } + mutation("version", 4, 99) + mutation("kind", 8, 2) + mutation("backend", 12, 3) + mutation("zero interval", 16, 0) + mutation("zero step", 20, 0) + mutation("depth", 28, 65) + mutation("unknown frame", 32, 999) + mutation("zero count", 24, 0) + mutation("negative count", 24, 0xffffffff) + mutation("name count", len(valid)-4, 0xffffffff) + mutation("name length", len(valid)-12, 128) + mutation("duplicate ID", len(valid)-8, 10) + for name, d := range cases { + t.Run(name, func(t *testing.T) { + if _, ok := parseData(d); ok { + t.Fatal("accepted malformed input") + } + }) + } + for _, v := range []uint32{0, 1} { + f, _ := parseData(fixture(v, 1)) + if _, err := profileProto(f); err == nil { + t.Fatal("legacy/memory must require metadata") + } + } + f, _ := parseData(valid) + f.intervalMs = 0xffffffff + f.callstack[0].count = 0x7fffffff + if _, err := profileProto(f); err == nil { + t.Fatal("overflow") + } +} +func TestModernPprof(t *testing.T) { + goexe, err := exec.LookPath("go") + if err != nil { + t.Skip("go tool unavailable") + } + for _, backend := range []uint32{1, 2} { + f, _ := parseData(fixture(2, backend)) + path := filepath.Join(t.TempDir(), "cpu.pb.gz") + if err := showproto(f, path); err != nil { + t.Fatal(err) + } + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + z, err := gzip.NewReader(file) + if err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(z) + if err != nil { + t.Fatal(err) + } + z.Close() + file.Close() + if len(fields(t, data)) == 0 { + t.Fatal("empty") + } + output, err := exec.Command(goexe, "tool", "pprof", "-top", path).CombinedOutput() + if err != nil { + t.Fatalf("go tool pprof: %s %v", output, err) + } + if !strings.Contains(string(output), "hot_leaf") || !strings.Contains(string(output), "100%") { + t.Fatalf("bad top: %s", output) + } + if backend == 1 && !strings.Contains(string(output), "70ms") { + t.Fatalf("CPU units: %s", output) + } + if backend == 2 && !strings.Contains(string(output), "Type: samples") { + t.Fatalf("count units: %s", output) + } + t.Logf("backend %d: %s", backend, output) + } +} +func TestLegacyAndFlameStillWork(t *testing.T) { + for _, v := range []uint32{0, 1, 2} { + f, ok := parseData(fixture(v, 1)) + if !ok { + t.Fatal("parse") + } + dir := t.TempDir() + showcollapsed(f, filepath.Join(dir, "stacks.fl")) + showpprof(f, filepath.Join(dir, "legacy.prof")) + d, _ := os.ReadFile(filepath.Join(dir, "stacks.fl")) + if string(d) != "root;hot_leaf 7\n" { + t.Fatalf("flame: %q", d) + } + d, _ = os.ReadFile(filepath.Join(dir, "legacy.prof")) + if !bytes.HasPrefix(d, []byte("--- symbol\n")) { + t.Fatal("legacy output") + } + } +}