Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion .github/workflows/ccpp.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ src/lzio.h
*.prof
*.dot
*.fl
*.pb.gz
*.svg
test/*.png
!test/getstr.png
Expand Down
329 changes: 180 additions & 149 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,149 +1,180 @@
# vLua

[English](README.md) | [中文说明](README_CN.md)

[<img src="https://img.shields.io/github/license/esrrhs/vLua">](https://github.com/esrrhs/vLua)
[<img src="https://img.shields.io/github/languages/top/esrrhs/vLua">](https://github.com/esrrhs/vLua)
[<img src="https://img.shields.io/github/actions/workflow/status/esrrhs/vLua/ccpp.yml?branch=master">](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:

- `<name>.fl`: Folded stack traces
- `<name>.svg`: Interactive SVG flame graph
- `<name>.prof`: Symbolized pprof profile
- `<name>.dot`: Graphviz call graph
- `<name>.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 <binary> | 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)

[<img src="https://img.shields.io/github/license/esrrhs/vLua">](https://github.com/esrrhs/vLua)
[<img src="https://img.shields.io/github/languages/top/esrrhs/vLua">](https://github.com/esrrhs/vLua)
[<img src="https://img.shields.io/github/actions/workflow/status/esrrhs/vLua/ccpp.yml?branch=master">](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:

- `<name>.fl`: Folded stack traces
- `<name>.svg`: Interactive SVG flame graph
- `<name>.prof`: Legacy symbolized pprof profile
- `<name>.pb.gz`: gzip `profile.proto` for modern `go tool pprof`
- `<name>.dot` / `<name>.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 <binary> | 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 <binary> | 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
Loading
Loading