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
-
-
-
-#### 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
+
+
+
+#### 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